diff --git a/TARGET.md b/TARGET.md index 6556418..c9639d9 100644 --- a/TARGET.md +++ b/TARGET.md @@ -389,3 +389,100 @@ https://docs.polymarket.com/api-reference/core/get-user-combo-positions.md https://docs.polymarket.com/api-reference/maker/cancel-a-quote.md https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look.md https://docs.polymarket.com/api-reference/maker/submit-a-quote.md + +## NEW - Perps (2026-07-13) +https://docs.polymarket.com/perps/overview.md +https://docs.polymarket.com/perps/account-management.md +https://docs.polymarket.com/perps/authenticated-sessions.md +https://docs.polymarket.com/perps/changelog.md +https://docs.polymarket.com/perps/concepts.md +https://docs.polymarket.com/perps/faq.md +https://docs.polymarket.com/perps/fund-your-account.md +https://docs.polymarket.com/perps/market-data.md +https://docs.polymarket.com/perps/overview.md +https://docs.polymarket.com/perps/place-your-first-trade.md +https://docs.polymarket.com/perps/rate-limits.md +https://docs.polymarket.com/perps/realtime-updates.md +https://docs.polymarket.com/perps/referral-program.md +https://docs.polymarket.com/perps/trading.md +https://docs.polymarket.com/perps/learn-about-trading/architecture.md +https://docs.polymarket.com/perps/learn-about-trading/fees.md +https://docs.polymarket.com/perps/learn-about-trading/funding.md +https://docs.polymarket.com/perps/learn-about-trading/geographic-restrictions.md +https://docs.polymarket.com/perps/learn-about-trading/index-price.md +https://docs.polymarket.com/perps/learn-about-trading/liquidation-mechanics.md +https://docs.polymarket.com/perps/learn-about-trading/margin.md +https://docs.polymarket.com/perps/learn-about-trading/mark-price.md +https://docs.polymarket.com/perps/learn-about-trading/market-sessions.md +https://docs.polymarket.com/perps/learn-about-trading/markets.md +https://docs.polymarket.com/perps/learn-about-trading/overview.md + +## NEW - Perps WebSocket (2026-07-13) +https://docs.polymarket.com/api-reference/wss/perps-auth.md +https://docs.polymarket.com/api-reference/wss/perps-auto-cancel.md +https://docs.polymarket.com/api-reference/wss/perps-balances.md +https://docs.polymarket.com/api-reference/wss/perps-bbo.md +https://docs.polymarket.com/api-reference/wss/perps-book.md +https://docs.polymarket.com/api-reference/wss/perps-cancel-orders.md +https://docs.polymarket.com/api-reference/wss/perps-cancel-orders-coid.md +https://docs.polymarket.com/api-reference/wss/perps-deposits.md +https://docs.polymarket.com/api-reference/wss/perps-fills.md +https://docs.polymarket.com/api-reference/wss/perps-funding.md +https://docs.polymarket.com/api-reference/wss/perps-klines.md +https://docs.polymarket.com/api-reference/wss/perps-orders.md +https://docs.polymarket.com/api-reference/wss/perps-ping.md +https://docs.polymarket.com/api-reference/wss/perps-place-orders.md +https://docs.polymarket.com/api-reference/wss/perps-portfolio.md +https://docs.polymarket.com/api-reference/wss/perps-statistics.md +https://docs.polymarket.com/api-reference/wss/perps-tickers.md +https://docs.polymarket.com/api-reference/wss/perps-trades.md +https://docs.polymarket.com/api-reference/wss/perps-update-leverage.md +https://docs.polymarket.com/api-reference/wss/perps-withdrawals.md + +## NEW - Account & Trading API (2026-07-13) +https://docs.polymarket.com/api-reference/apply-referral-code.md +https://docs.polymarket.com/api-reference/cancel-orders.md +https://docs.polymarket.com/api-reference/cancel-orders-coid.md +https://docs.polymarket.com/api-reference/check-invite-code.md +https://docs.polymarket.com/api-reference/create-account-invite.md +https://docs.polymarket.com/api-reference/create-orders.md +https://docs.polymarket.com/api-reference/create-proxy.md +https://docs.polymarket.com/api-reference/delete-proxy.md +https://docs.polymarket.com/api-reference/get-account-limits.md +https://docs.polymarket.com/api-reference/get-account-referral.md +https://docs.polymarket.com/api-reference/get-account-rewards.md +https://docs.polymarket.com/api-reference/get-account-stats.md +https://docs.polymarket.com/api-reference/get-auto-cancel-status.md +https://docs.polymarket.com/api-reference/get-balances.md +https://docs.polymarket.com/api-reference/get-bbo.md +https://docs.polymarket.com/api-reference/get-book.md +https://docs.polymarket.com/api-reference/get-collateral-assets.md +https://docs.polymarket.com/api-reference/get-credentials.md +https://docs.polymarket.com/api-reference/get-deposits.md +https://docs.polymarket.com/api-reference/get-equity.md +https://docs.polymarket.com/api-reference/get-exchange-info.md +https://docs.polymarket.com/api-reference/get-fees.md +https://docs.polymarket.com/api-reference/get-fills.md +https://docs.polymarket.com/api-reference/get-funding-charges.md +https://docs.polymarket.com/api-reference/get-historical-funding.md +https://docs.polymarket.com/api-reference/get-index.md +https://docs.polymarket.com/api-reference/get-instrument-config.md +https://docs.polymarket.com/api-reference/get-instruments.md +https://docs.polymarket.com/api-reference/get-internal-transfers.md +https://docs.polymarket.com/api-reference/get-klines.md +https://docs.polymarket.com/api-reference/get-limit-tiers.md +https://docs.polymarket.com/api-reference/get-open-orders.md +https://docs.polymarket.com/api-reference/get-orders.md +https://docs.polymarket.com/api-reference/get-pnl.md +https://docs.polymarket.com/api-reference/get-portfolio.md +https://docs.polymarket.com/api-reference/get-public-portfolio.md +https://docs.polymarket.com/api-reference/get-recent-trades.md +https://docs.polymarket.com/api-reference/get-server-time.md +https://docs.polymarket.com/api-reference/get-statistics.md +https://docs.polymarket.com/api-reference/get-tickers.md +https://docs.polymarket.com/api-reference/get-withdrawals.md +https://docs.polymarket.com/api-reference/internal-transfer.md +https://docs.polymarket.com/api-reference/set-auto-cancel.md +https://docs.polymarket.com/api-reference/test-connection.md +https://docs.polymarket.com/api-reference/update-leverage.md +https://docs.polymarket.com/api-reference/withdraw.md diff --git a/docs/api-reference/apply-referral-code.md b/docs/api-reference/apply-referral-code.md new file mode 100644 index 0000000..6abaeb4 --- /dev/null +++ b/docs/api-reference/apply-referral-code.md @@ -0,0 +1,226 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Apply Referral Code + +> Apply a referral code to the authenticated account after signup. Accounts +can only apply a referral code if they do not already have one. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/referral +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/referral: + post: + summary: Apply Referral Code + description: > + Apply a referral code to the authenticated account after signup. + Accounts + + can only apply a referral code if they do not already have one. + operationId: applyReferral + requestBody: + required: true + description: Referral code to apply. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountReferralRequest' + examples: + applyReferral: + summary: Apply a referral code + value: + code: ABC123 + responses: + '200': + description: Referral code accepted. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountReferralRequest: + type: object + required: + - code + properties: + code: + $ref: '#/components/schemas/code' + GenericAccepted: + type: object + required: + - status + properties: + status: + type: string + enum: + - ok + code: + type: string + description: Referral or invite code + example: ABC123 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/cancel-orders-coid.md b/docs/api-reference/cancel-orders-coid.md new file mode 100644 index 0000000..077ae15 --- /dev/null +++ b/docs/api-reference/cancel-orders-coid.md @@ -0,0 +1,278 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders COID + +> Cancel orders by client order ID. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **0** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/trade/orders-coid +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders-coid: + delete: + summary: Cancel Orders COID + description: > + Cancel orders by client order ID. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: cancelOrdersByCoid + requestBody: + description: Cancel by coid request. + content: + application/json: + schema: + $ref: '#/components/schemas/CancelByCoidRequest' + responses: + '200': + description: Cancel response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + CancelByCoidRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCancelOrdersByCoid' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + CancelResponse: + oneOf: + - $ref: '#/components/schemas/CancelAccepted' + - $ref: '#/components/schemas/CancelRejected' + OpCancelOrdersByCoid: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrdersCOID + args: + type: array + description: | + Array of client order IDs to cancel. Cancelling an order that has + attached take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to those children — they are cancelled with reason + `ParentCancelled`. + items: + $ref: '#/components/schemas/coid' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + CancelAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + CancelRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + oid: + type: integer + description: Order ID + example: 1234567890 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/cancel-orders.md b/docs/api-reference/cancel-orders.md new file mode 100644 index 0000000..8922897 --- /dev/null +++ b/docs/api-reference/cancel-orders.md @@ -0,0 +1,277 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders + +> Cancel orders. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **0** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/trade/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders: + delete: + summary: Cancel Orders + description: > + Cancel orders. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: cancelOrders + requestBody: + description: Cancel request. + content: + application/json: + schema: + $ref: '#/components/schemas/CancelRequest' + responses: + '200': + description: Cancel response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + CancelRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCancelOrders' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + CancelResponse: + oneOf: + - $ref: '#/components/schemas/CancelAccepted' + - $ref: '#/components/schemas/CancelRejected' + OpCancelOrders: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrders + args: + type: array + description: | + Array of order IDs to cancel. Cancelling an order that has attached + take-profit / stop-loss children (see `CreateOrder.tr`) cascades to + those children — they are cancelled with reason `ParentCancelled`. + items: + $ref: '#/components/schemas/oid' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + CancelAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + CancelRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + oid: + type: integer + description: Order ID + example: 1234567890 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/check-invite-code.md b/docs/api-reference/check-invite-code.md new file mode 100644 index 0000000..9b6e619 --- /dev/null +++ b/docs/api-reference/check-invite-code.md @@ -0,0 +1,162 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Check Invite Code + +> Check whether an invite code can be used. When `address` is provided, the +response is invalid if that address already has an account. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/invite +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/invite: + get: + summary: Check Invite Code + description: > + Check whether an invite code can be used. When `address` is provided, + the + + response is invalid if that address already has an account. + operationId: checkInviteCode + parameters: + - name: code + in: query + required: true + schema: + $ref: '#/components/schemas/code' + - name: address + in: query + required: false + schema: + $ref: '#/components/schemas/address' + responses: + '200': + description: Invite code validation response. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteCheckResponse' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + code: + type: string + description: Referral or invite code + example: ABC123 + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + InviteCheckResponse: + type: object + required: + - valid + properties: + valid: + type: boolean + description: Whether the invite code can be used. + error: + type: string + description: Present when the invite code is invalid or unusable. + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/create-account-invite.md b/docs/api-reference/create-account-invite.md new file mode 100644 index 0000000..49ed06a --- /dev/null +++ b/docs/api-reference/create-account-invite.md @@ -0,0 +1,236 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Account Invite + +> Create or return the authenticated account's primary invite code. The call +is idempotent for accounts that already have a primary invite code. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/invite +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/invite: + post: + summary: Create Account Invite + description: > + Create or return the authenticated account's primary invite code. The + call + + is idempotent for accounts that already have a primary invite code. + operationId: createAccountInvite + requestBody: + description: Empty invite creation request. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateInviteRequest' + examples: + createAccountInvite: + summary: Create or get the authenticated account invite code + value: {} + responses: + '200': + description: Account invite response. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateInviteResponse' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + CreateInviteRequest: + type: object + additionalProperties: false + CreateInviteResponse: + type: object + required: + - status + - code + - referrals_available + - cooldown_ms + properties: + status: + type: string + enum: + - ok + code: + $ref: '#/components/schemas/code' + referrals_available: + type: integer + minimum: 0 + description: Remaining lifetime referrals for this invite code. + cooldown_ms: + type: integer + nullable: true + minimum: 0 + description: >- + Milliseconds until referrals become available again. Null for + lifetime caps because no windowed cooldown applies. + code: + type: string + description: Referral or invite code + example: ABC123 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/create-orders.md b/docs/api-reference/create-orders.md new file mode 100644 index 0000000..7c2fd4c --- /dev/null +++ b/docs/api-reference/create-orders.md @@ -0,0 +1,362 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Orders + +> Create new orders. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **1 / order** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/trade/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders: + post: + summary: Create Orders + description: > + Create new orders. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: createOrders + requestBody: + description: Order request. + content: + application/json: + schema: + $ref: '#/components/schemas/OrderRequest' + responses: + '200': + description: >- + Order ACK response. Order result should be fetched using the get + orders endpoint. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + OrderRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCreateOrders' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + OrderResponse: + oneOf: + - $ref: '#/components/schemas/OrderAccepted' + - $ref: '#/components/schemas/OrderRejected' + OpCreateOrders: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createOrders + args: + type: array + items: + $ref: '#/components/schemas/CreateOrder' + grp: + $ref: '#/components/schemas/grp' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + OrderAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + OrderRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + CreateOrder: + type: object + required: + - iid + - buy + - qty + properties: + iid: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + p: + $ref: '#/components/schemas/p' + qty: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + po: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + c: + $ref: '#/components/schemas/coid' + tr: + type: object + description: Optional trigger attached to this order. + properties: + market: + $ref: '#/components/schemas/market' + trp: + $ref: '#/components/schemas/trp' + tpsl: + $ref: '#/components/schemas/tpsl' + grp: + type: string + description: TPSL grouping + enum: + - order + - position + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + oid: + type: integer + description: Order ID + example: 1234567890 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + iid: + type: integer + description: Instrument ID + example: 1 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + market: + type: boolean + description: Whether the trigger executes as a market order + trp: + type: string + description: Trigger price + example: '110.00' + tpsl: + type: string + description: Trigger type + enum: + - tp + - sl + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/create-proxy.md b/docs/api-reference/create-proxy.md new file mode 100644 index 0000000..a327027 --- /dev/null +++ b/docs/api-reference/create-proxy.md @@ -0,0 +1,302 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Proxy + +> Create a new proxy to sign orders. Returns an API secret for private account access. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/proxy +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/proxy: + post: + summary: Create Proxy + description: > + Create a new proxy to sign orders. Returns an API secret for private + account access. + + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + operationId: createProxy + requestBody: + description: Proxy creation request. + content: + application/json: + schema: + $ref: '#/components/schemas/ProxyRequest' + examples: + createProxy: + summary: Create a proxy + value: + op: + type: createProxy + args: + owner: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + proxy: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + expiry: 1767225600000 + sig: >- + 0x4d11d89f6d8e2f0fd22fb5dd9e6e88a35f3a2c0f3a9e4ff9f8f0da5e6c5f241d2ed7d173f7fcb15726b8a7e7f1f1277ec54c060f5b3ab4d72dbf4d0e40ee6e9a1c + salt: 123456789 + ts: 1767000000000 + responses: + '200': + description: Proxy creation response. + content: + application/json: + schema: + $ref: '#/components/schemas/ProxyResponse' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + ProxyRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCreateProxy' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + label: + $ref: '#/components/schemas/label' + code: + $ref: '#/components/schemas/code' + ProxyResponse: + type: object + required: + - status + - secret + properties: + status: + type: string + enum: + - ok + secret: + $ref: '#/components/schemas/secret' + OpCreateProxy: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createProxy + args: + type: object + required: + - owner + - proxy + - expiry + properties: + owner: + $ref: '#/components/schemas/owner' + proxy: + $ref: '#/components/schemas/proxy' + expiry: + $ref: '#/components/schemas/expiry' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + code: + type: string + description: Referral or invite code + example: ABC123 + secret: + type: string + description: API secret + example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + owner: + type: string + description: Owner address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + expiry: + type: integer + description: Expiry timestamp in milliseconds + example: 1767225600000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/delete-proxy.md b/docs/api-reference/delete-proxy.md new file mode 100644 index 0000000..b6caa38 --- /dev/null +++ b/docs/api-reference/delete-proxy.md @@ -0,0 +1,263 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Delete Proxy + +> Delete a proxy by address. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/account/proxy +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/proxy: + delete: + summary: Delete Proxy + description: | + Delete a proxy by address. + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + operationId: deleteProxy + requestBody: + description: Delete proxy request. + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteProxyRequest' + examples: + deleteProxy: + summary: Delete a proxy + value: + op: + type: deleteProxy + args: + proxy: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a1c + salt: 888888888 + ts: 1767000020000 + responses: + '200': + description: Delete proxy response. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + DeleteProxyRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpDeleteProxy' + - $ref: '#/components/schemas/BaseOp' + GenericAccepted: + type: object + required: + - status + properties: + status: + type: string + enum: + - ok + OpDeleteProxy: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - deleteProxy + args: + type: object + required: + - proxy + properties: + proxy: + $ref: '#/components/schemas/proxy' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-account-limits.md b/docs/api-reference/get-account-limits.md new file mode 100644 index 0000000..f48086c --- /dev/null +++ b/docs/api-reference/get-account-limits.md @@ -0,0 +1,242 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Limits + +> Get the authenticated account's effective rate-limit allowances for its current +volume-based tier: order-action rate, open-order cap, and the display-only +messages-per-minute figure. `open_orders` reflects the account's current live +open-order count; the rate-usage counters (`actions_per_minute`, +`actions_burst`, and `reset`) are not tracked here and are reported as 0. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/limits +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/limits: + get: + summary: Get Account Limits + description: > + Get the authenticated account's effective rate-limit allowances for its + current + + volume-based tier: order-action rate, open-order cap, and the + display-only + + messages-per-minute figure. `open_orders` reflects the account's current + live + + open-order count; the rate-usage counters (`actions_per_minute`, + + `actions_burst`, and `reset`) are not tracked here and are reported as + 0. + operationId: getAccountLimits + responses: + '200': + description: Account limits response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountLimits' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountLimits: + type: object + required: + - actions_per_minute + - actions_per_minute_limit + - actions_burst + - actions_burst_limit + - open_orders + - open_orders_limit + - reset + - messages_per_minute + properties: + actions_per_minute: + $ref: '#/components/schemas/actions_per_minute' + actions_per_minute_limit: + $ref: '#/components/schemas/actions_per_minute_limit' + actions_burst: + $ref: '#/components/schemas/actions_burst' + actions_burst_limit: + $ref: '#/components/schemas/actions_burst_limit' + open_orders: + $ref: '#/components/schemas/open_orders' + open_orders_limit: + $ref: '#/components/schemas/open_orders_limit' + reset: + $ref: '#/components/schemas/rate_reset' + messages_per_minute: + $ref: '#/components/schemas/messages_per_minute' + actions_per_minute: + type: integer + description: Order action tokens used by the account in the current minute + example: 23 + actions_per_minute_limit: + type: integer + description: Maximum order action tokens per account per minute + example: 300 + actions_burst: + type: integer + description: Additional account action allowance remaining + actions_burst_limit: + type: integer + description: Additional account action allowance limit + open_orders: + type: integer + description: Current number of open orders + example: 42 + open_orders_limit: + type: integer + description: Maximum number of open orders per account + example: 1000 + rate_reset: + type: integer + description: Timestamp in milliseconds when the current interval resets + example: 1767225660000 + messages_per_minute: + type: integer + description: >- + Display-only per-minute action/message allowance, equal to + actions_per_minute_limit. Not separately configured or enforced. + example: 300 + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-account-referral.md b/docs/api-reference/get-account-referral.md new file mode 100644 index 0000000..f4bf745 --- /dev/null +++ b/docs/api-reference/get-account-referral.md @@ -0,0 +1,207 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Referral + +> Get the authenticated account's invite code, parent referral code, direct +referral count, and fee share rate. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/referral +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/referral: + get: + summary: Get Account Referral + description: > + Get the authenticated account's invite code, parent referral code, + direct + + referral count, and fee share rate. + operationId: getAccountReferral + responses: + '200': + description: Account referral response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountReferral' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountReferral: + type: object + required: + - code + - children_count + - referrals_left + - fee_share_rate + properties: + code: + $ref: '#/components/schemas/code' + parent: + $ref: '#/components/schemas/code' + description: >- + Parent referral code, omitted when the account has no parent + referral. + children_count: + $ref: '#/components/schemas/children_count' + referrals_left: + $ref: '#/components/schemas/referrals_left' + fee_share_rate: + $ref: '#/components/schemas/fee_share_rate' + code: + type: string + description: Referral or invite code + example: ABC123 + children_count: + type: integer + description: Number of directly referred child accounts + example: 12 + referrals_left: + type: integer + description: Number of additional referrals remaining for this account's invite code + example: 11 + fee_share_rate: + type: string + description: Referral fee share rate. Defaults to 0.2. + example: '0.2' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-account-rewards.md b/docs/api-reference/get-account-rewards.md new file mode 100644 index 0000000..2327cc0 --- /dev/null +++ b/docs/api-reference/get-account-rewards.md @@ -0,0 +1,333 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Rewards + +> Get per-instrument daily liquidity reward shares for the authenticated account. +Reward periods run from 12:00 UTC to 12:00 UTC and are labeled by their UTC end date. +OI rewards pay 6% APR on the account's full daily average gross OI across all +instruments when the combined daily average gross OI of its rewards entity is +at least $1M. Accounts without an entity mapping qualify independently. +The first reward period starts at 2026-05-08 12:00 UTC. If no date range is provided, +the latest computed reward period is returned. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/rewards +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/rewards: + get: + summary: Get Account Rewards + description: > + Get per-instrument daily liquidity reward shares for the authenticated + account. + + Reward periods run from 12:00 UTC to 12:00 UTC and are labeled by their + UTC end date. + + OI rewards pay 6% APR on the account's full daily average gross OI + across all + + instruments when the combined daily average gross OI of its rewards + entity is + + at least $1M. Accounts without an entity mapping qualify independently. + + The first reward period starts at 2026-05-08 12:00 UTC. If no date range + is provided, + + the latest computed reward period is returned. + operationId: getAccountRewards + parameters: + - name: date + in: query + required: false + schema: + $ref: '#/components/schemas/date' + - name: start_date + in: query + required: false + schema: + $ref: '#/components/schemas/start_date' + - name: end_date + in: query + required: false + schema: + $ref: '#/components/schemas/end_date' + - name: limit + in: query + required: false + schema: + $ref: '#/components/schemas/limit' + responses: + '200': + description: Account rewards response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountRewards' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + date: + type: string + description: UTC reward period end date in YYYY-MM-DD format + example: '2026-05-10' + start_date: + type: string + description: Inclusive UTC start date in YYYY-MM-DD format + example: '2026-05-01' + end_date: + type: string + description: Inclusive UTC end date in YYYY-MM-DD format + example: '2026-05-10' + limit: + type: integer + description: Maximum number of entries to return + example: 100 + AccountRewards: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountReward' + more: + $ref: '#/components/schemas/more' + AccountReward: + type: object + required: + - date + - maker_share_7d + - reward_distributed + - breakdown + properties: + date: + $ref: '#/components/schemas/date' + maker_share_7d: + $ref: '#/components/schemas/maker_share_7d' + reward_distributed: + $ref: '#/components/schemas/reward_distributed' + breakdown: + type: array + items: + $ref: '#/components/schemas/AccountRewardInstrument' + oi_rewards: + $ref: '#/components/schemas/AccountRewardOi' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + maker_share_7d: + type: string + description: Rolling 7-day account maker volume divided by total exchange volume + example: '0.35' + reward_distributed: + type: boolean + description: Whether rewards for this period have been marked as distributed + example: true + AccountRewardInstrument: + type: object + required: + - instrument_id + - reward_pool + - reward_amount + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + reward_pool: + $ref: '#/components/schemas/reward_pool' + reward_amount: + $ref: '#/components/schemas/reward_amount' + AccountRewardOi: + type: object + required: + - account_oi + - reward_amount + properties: + account_oi: + $ref: '#/components/schemas/account_oi' + reward_amount: + $ref: '#/components/schemas/reward_amount' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + instrument_id: + type: integer + description: Instrument ID + reward_pool: + type: string + description: Configured reward pool for the instrument + example: '1000' + reward_amount: + type: string + description: Reward amount attributed to this reward row + example: '127.50344' + account_oi: + type: string + description: >- + Daily average gross open-interest notional for this account across all + instruments + example: '3200000' + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-account-stats.md b/docs/api-reference/get-account-stats.md new file mode 100644 index 0000000..5c840e5 --- /dev/null +++ b/docs/api-reference/get-account-stats.md @@ -0,0 +1,223 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Stats + +> Get the authenticated account's 7-day trading stats (taker volume, maker volume, +account maker share, and entity maker share when applicable). +Stats are cached by UTC day and may be stale by up to 24 hours. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/stats +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/stats: + get: + summary: Get Account Stats + description: > + Get the authenticated account's 7-day trading stats (taker volume, maker + volume, + + account maker share, and entity maker share when applicable). + + Stats are cached by UTC day and may be stale by up to 24 hours. + operationId: getAccountStats + responses: + '200': + description: Account stats response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountStats' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountStats: + type: object + required: + - volume_7d + - taker_volume_7d + - maker_volume_7d + - account_maker_share_7d + properties: + volume_7d: + $ref: '#/components/schemas/volume_7d' + taker_volume_7d: + $ref: '#/components/schemas/taker_volume_7d' + maker_volume_7d: + $ref: '#/components/schemas/maker_volume_7d' + account_maker_share_7d: + $ref: '#/components/schemas/account_maker_share_7d' + entity_maker_share_7d: + $ref: '#/components/schemas/entity_maker_share_7d' + entity_id: + $ref: '#/components/schemas/entity_id' + entity_name: + $ref: '#/components/schemas/entity_name' + volume_7d: + type: string + description: Rolling 7-day perpetual trading volume in USD + example: '5000000' + taker_volume_7d: + type: string + description: Rolling 7-day perpetual taker volume in USD + example: '3500000' + maker_volume_7d: + type: string + description: Rolling 7-day perpetual maker volume in USD + example: '1500000' + account_maker_share_7d: + type: string + description: Rolling 7-day account maker volume divided by total exchange volume + example: '0.35' + entity_maker_share_7d: + type: string + description: Rolling 7-day entity maker volume divided by total exchange volume + example: '0.35' + entity_id: + type: integer + description: Liquidity rewards entity ID + example: 42 + entity_name: + type: string + description: Liquidity rewards entity name + example: desk + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-auto-cancel-status.md b/docs/api-reference/get-auto-cancel-status.md new file mode 100644 index 0000000..4c19601 --- /dev/null +++ b/docs/api-reference/get-auto-cancel-status.md @@ -0,0 +1,210 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Auto-Cancel Status + +> Get the current auto-cancel dead-man-switch status for the authenticated +account, including the armed deadline, today's trigger count, and when +the daily counter resets. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/auto-cancel +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/auto-cancel: + get: + summary: Get Auto-Cancel Status + description: | + Get the current auto-cancel dead-man-switch status for the authenticated + account, including the armed deadline, today's trigger count, and when + the daily counter resets. + operationId: getAutoCancel + responses: + '200': + description: Auto-cancel status response. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelStatus' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AutoCancelStatus: + type: object + required: + - deadline + - triggered + - daily_limit + - next_reset + properties: + deadline: + $ref: '#/components/schemas/auto_cancel_deadline' + triggered: + $ref: '#/components/schemas/auto_cancel_triggered' + daily_limit: + $ref: '#/components/schemas/auto_cancel_daily_limit' + next_reset: + $ref: '#/components/schemas/auto_cancel_next_reset' + auto_cancel_deadline: + type: integer + description: | + Unix-ms deadline for the per-account auto-cancel dead-man-switch. + Zero means no schedule is armed. When the deadline elapses, every + open order on the account is cancelled and the schedule clears. + example: 1767000045000 + auto_cancel_triggered: + type: integer + description: | + Number of times auto-cancel has fired for this account during the + current UTC day. Resets to zero at 00:00 UTC. + example: 0 + auto_cancel_daily_limit: + type: integer + description: | + Maximum number of auto-cancel triggers allowed per UTC day. + example: 10 + auto_cancel_next_reset: + type: integer + description: | + Unix-ms timestamp of the next UTC midnight when the daily trigger + count resets to zero. + example: 1767052800000 + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-balances.md b/docs/api-reference/get-balances.md new file mode 100644 index 0000000..3c7730a --- /dev/null +++ b/docs/api-reference/get-balances.md @@ -0,0 +1,191 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Balances + +> Get asset balances for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/balances +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/balances: + get: + summary: Get Balances + description: Get asset balances for the authenticated account. + operationId: getBalances + responses: + '200': + description: Balances response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Balance' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Balance: + type: object + required: + - asset + - balance + - value + properties: + asset: + $ref: '#/components/schemas/asset' + balance: + $ref: '#/components/schemas/balance' + value: + $ref: '#/components/schemas/value' + asset: + type: string + description: Asset name + example: USDC + balance: + type: string + description: Total balance + example: '10000.00' + value: + type: string + description: USD value + example: '10000.00' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-bbo.md b/docs/api-reference/get-bbo.md new file mode 100644 index 0000000..59bbf95 --- /dev/null +++ b/docs/api-reference/get-bbo.md @@ -0,0 +1,211 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get BBO + +> Get best bid and offer for all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/bbo +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/bbo: + get: + summary: Get BBO + description: Get best bid and offer for all instruments. + operationId: getBBO + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: BBO response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BBO' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + BBO: + title: BBO + type: object + required: + - instrument_id + - bid_price + - bid_quantity + - ask_price + - ask_quantity + - timestamp + properties: + instrument_id: + $ref: '#/components/schemas/iid' + bid_price: + $ref: '#/components/schemas/best_bid_price' + bid_quantity: + $ref: '#/components/schemas/best_bid_quantity' + ask_price: + $ref: '#/components/schemas/best_ask_price' + ask_quantity: + $ref: '#/components/schemas/best_ask_quantity' + timestamp: + $ref: '#/components/schemas/ts' + iid: + type: integer + description: Instrument ID + example: 1 + best_bid_price: + type: string + description: Best bid price + example: '99.50' + best_bid_quantity: + type: string + description: Best bid quantity + example: '10.00' + best_ask_price: + type: string + description: Best ask price + example: '100.50' + best_ask_quantity: + type: string + description: Best ask quantity + example: '10.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-book.md b/docs/api-reference/get-book.md new file mode 100644 index 0000000..7734972 --- /dev/null +++ b/docs/api-reference/get-book.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Book + +> Get book for an instrument. + +Request Weight: + +
+ +Depth 10: **2** + +
+ +Depth 100: **5** + +
+ +Depth 500: **10** + +
+ +Depth 1000: **20** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/book +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/book: + get: + summary: Get Book + description: Get book for an instrument. + operationId: getBook + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: depth + in: query + required: false + schema: + $ref: '#/components/schemas/depth' + responses: + '200': + description: Book response. + content: + application/json: + schema: + $ref: '#/components/schemas/Book' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + depth: + type: integer + description: Number of book levels to return + enum: + - 10 + - 100 + - 500 + - 1000 + default: 100 + Book: + type: object + required: + - instrument_id + - bids + - asks + - timestamp + - sequence + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + bids: + type: array + items: + $ref: '#/components/schemas/level' + description: Bid levels + asks: + type: array + items: + $ref: '#/components/schemas/level' + description: Ask levels + timestamp: + $ref: '#/components/schemas/timestamp' + sequence: + $ref: '#/components/schemas/sequence' + level: + type: array + items: + type: string + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + timestamp: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + sequence: + type: integer + description: Sequence number + example: 1234567890 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-collateral-assets.md b/docs/api-reference/get-collateral-assets.md new file mode 100644 index 0000000..6afb9ab --- /dev/null +++ b/docs/api-reference/get-collateral-assets.md @@ -0,0 +1,169 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Collateral Assets + +> Get a list of collateral assets. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/assets +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/assets: + get: + summary: Get Collateral Assets + description: | + Get a list of collateral assets. + operationId: getAssets + responses: + '200': + description: Assets response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Asset' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Asset: + type: object + required: + - asset + - address + - decimals + - collateral_ratio + - withdrawal_fee + properties: + asset: + $ref: '#/components/schemas/asset' + address: + $ref: '#/components/schemas/address' + decimals: + $ref: '#/components/schemas/decimals' + collateral_ratio: + $ref: '#/components/schemas/collateral_ratio' + withdrawal_fee: + $ref: '#/components/schemas/withdrawal_fee' + asset: + type: string + description: Asset name + example: USDC + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + decimals: + type: integer + description: Asset decimals + example: 6 + collateral_ratio: + type: string + description: Collateral ratio + example: '1.00' + withdrawal_fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-credentials.md b/docs/api-reference/get-credentials.md new file mode 100644 index 0000000..5c30ec5 --- /dev/null +++ b/docs/api-reference/get-credentials.md @@ -0,0 +1,230 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Credentials + +> Get the account ID, address, and proxy keys for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/credentials +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/credentials: + get: + summary: Get Credentials + description: >- + Get the account ID, address, and proxy keys for the authenticated + account. + operationId: getCredentials + responses: + '200': + description: Credentials response. + content: + application/json: + schema: + $ref: '#/components/schemas/Credentials' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Credentials: + type: object + required: + - address + - keys + properties: + address: + $ref: '#/components/schemas/address' + keys: + type: array + items: + $ref: '#/components/schemas/Key' + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + Key: + type: object + required: + - proxy + - expiry + properties: + proxy: + $ref: '#/components/schemas/proxy' + label: + $ref: '#/components/schemas/label' + expiry: + $ref: '#/components/schemas/expiry' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + expiry: + type: integer + description: Expiry timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-deposits.md b/docs/api-reference/get-deposits.md new file mode 100644 index 0000000..4a700bf --- /dev/null +++ b/docs/api-reference/get-deposits.md @@ -0,0 +1,318 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Deposits + +> Get deposit history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/deposits +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/deposits: + get: + summary: Get Deposits + description: | + Get deposit history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getDeposits + parameters: + - name: deposit_status + in: query + required: false + schema: + $ref: '#/components/schemas/deposit_status' + - name: hash + in: query + required: false + schema: + $ref: '#/components/schemas/hash' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Deposit history response. + content: + application/json: + schema: + $ref: '#/components/schemas/Deposits' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + deposit_status: + type: string + description: Deposit status + enum: + - pending + - confirmed + - removed + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Deposits: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/Deposit' + more: + $ref: '#/components/schemas/more' + Deposit: + type: object + required: + - hash + - asset + - amount + - status + - from + - to + - confirmations + - required_confirmations + - created_timestamp + properties: + hash: + $ref: '#/components/schemas/hash' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + from: + $ref: '#/components/schemas/from' + to: + $ref: '#/components/schemas/to' + status: + $ref: '#/components/schemas/deposit_status' + confirmations: + $ref: '#/components/schemas/confirmations' + required_confirmations: + $ref: '#/components/schemas/required_confirmations' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + confirmed_timestamp: + $ref: '#/components/schemas/confirmed_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + from: + type: string + description: Sender address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + confirmations: + type: integer + description: Number of block confirmations + example: 12 + required_confirmations: + type: integer + description: Required number of block confirmations + example: 12 + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + confirmed_timestamp: + type: integer + description: Confirmation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-equity.md b/docs/api-reference/get-equity.md new file mode 100644 index 0000000..66e6fb3 --- /dev/null +++ b/docs/api-reference/get-equity.md @@ -0,0 +1,255 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Equity + +> Get equity history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/equity +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/equity: + get: + summary: Get Equity + description: | + Get equity history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getEquityHistory + parameters: + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Equity history response. + content: + application/json: + schema: + $ref: '#/components/schemas/EquityHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + interval: + type: string + description: Kline interval + enum: + - 1s + - 1m + - 5m + - 15m + - 30m + - 1h + - 4h + - 6h + - 12h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + EquityHistory: + type: object + required: + - data + - more + properties: + data: + type: array + description: | + - `1767225600000` - Timestamp + - `"10000.00"` - Equity + items: + type: array + example: + - 1767225600000 + - '10000.00' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-exchange-info.md b/docs/api-reference/get-exchange-info.md new file mode 100644 index 0000000..109d3dc --- /dev/null +++ b/docs/api-reference/get-exchange-info.md @@ -0,0 +1,161 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Exchange Info + +> Get exchange information. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/exchange +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/exchange: + get: + summary: Get Exchange Info + description: | + Get exchange information. + operationId: getExchange + responses: + '200': + description: Successful exchange information response. + content: + application/json: + schema: + $ref: '#/components/schemas/Exchange' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Exchange: + type: object + required: + - name + - version + - chain_id + - contract + properties: + name: + $ref: '#/components/schemas/name' + version: + $ref: '#/components/schemas/version' + chain_id: + $ref: '#/components/schemas/chain_id' + contract: + $ref: '#/components/schemas/contract' + name: + type: string + description: Exchange name used in the EIP-712 domain. + example: Polymarket + version: + type: string + description: Exchange version used in the EIP-712 domain. + example: '1' + chain_id: + type: integer + format: uint32 + description: Chain ID of the network the exchange is deployed on. + example: 137 + contract: + type: string + description: Verifying contract address or the EIP-712 domain. + example: '0x1234567890abcdef1234567890abcdef12345678' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-fees.md b/docs/api-reference/get-fees.md new file mode 100644 index 0000000..b5e4e20 --- /dev/null +++ b/docs/api-reference/get-fees.md @@ -0,0 +1,179 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Fees + +> Get the default fee schedule for each instrument type and category. Rates returned are the $0-tier defaults; the account's actual rate on each fill depends on its trailing 30-day volume tier. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/fees +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/fees: + get: + summary: Get Fees + description: >- + Get the default fee schedule for each instrument type and category. + Rates returned are the $0-tier defaults; the account's actual rate on + each fill depends on its trailing 30-day volume tier. + operationId: getInfoFees + responses: + '200': + description: Fee schedule response. + content: + application/json: + schema: + $ref: '#/components/schemas/FeesInfo' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + FeesInfo: + type: object + required: + - fee_schedule + properties: + fee_schedule: + type: array + items: + $ref: '#/components/schemas/FeeScheduleEntry' + FeeScheduleEntry: + type: object + required: + - instrument_type + - category + - taker_fee_rate + - maker_fee_rate + properties: + instrument_type: + $ref: '#/components/schemas/instrument_type' + category: + $ref: '#/components/schemas/category' + taker_fee_rate: + $ref: '#/components/schemas/taker_fee_rate' + maker_fee_rate: + $ref: '#/components/schemas/maker_fee_rate' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_type: + type: string + description: Instrument type + enum: + - perpetual + category: + type: string + description: Instrument category + enum: + - equity + - commodity + - index + - crypto + taker_fee_rate: + type: string + description: >- + Default taker fee rate for the $0 volume tier. Actual rate scales down + with the account's trailing 30-day volume tier. + example: '0.0004' + maker_fee_rate: + type: string + description: >- + Default maker fee rate for the $0 volume tier. Positive at lower tiers, + zero at the $500M tier, and a rebate (negative) at the top tier. + example: '0.000125' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-fills.md b/docs/api-reference/get-fills.md new file mode 100644 index 0000000..5f5fad9 --- /dev/null +++ b/docs/api-reference/get-fills.md @@ -0,0 +1,342 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Fills + +> Get fill history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/fills +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/fills: + get: + summary: Get Fills + description: | + Get fill history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getFills + parameters: + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Fills response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountTrades' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + AccountTrades: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountTradeData' + description: Account's trade history + more: + $ref: '#/components/schemas/more' + AccountTradeData: + type: object + required: + - trade_id + - order_id + - instrument_id + - side + - price + - quantity + - taker + - fee + - fee_asset + - previous_size + - previous_entry_price + - pnl + - timestamp + - liquidation + - hash + properties: + trade_id: + $ref: '#/components/schemas/tid' + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + side: + $ref: '#/components/schemas/side' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + taker: + $ref: '#/components/schemas/taker' + fee: + $ref: '#/components/schemas/fee' + fee_asset: + $ref: '#/components/schemas/fea' + previous_size: + $ref: '#/components/schemas/psz' + previous_entry_price: + $ref: '#/components/schemas/pep' + pnl: + $ref: '#/components/schemas/pnl' + liquidation: + $ref: '#/components/schemas/liq' + timestamp: + $ref: '#/components/schemas/ts' + hash: + $ref: '#/components/schemas/hash' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + tid: + type: integer + description: Trade ID + example: 1 + oid: + type: integer + description: Order ID + example: 1234567890 + iid: + type: integer + description: Instrument ID + example: 1 + side: + type: string + description: Side + enum: + - long + - short + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + taker: + type: boolean + description: Whether this side was the taker + fee: + type: string + description: Fee amount for this trade side + example: '1.25' + fea: + type: string + description: Fee asset name + example: USDC + psz: + type: string + description: Position size before the fill + example: '26.86' + pep: + type: string + description: Position entry price before the fill + example: '100.00' + pnl: + type: string + description: PnL in USD + example: '100.00' + liq: + type: boolean + description: Whether the fill was a liquidation + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-funding-charges.md b/docs/api-reference/get-funding-charges.md new file mode 100644 index 0000000..566eeec --- /dev/null +++ b/docs/api-reference/get-funding-charges.md @@ -0,0 +1,287 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Funding Charges + +> Get funding payment history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/funding +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/funding: + get: + summary: Get Funding Charges + description: | + Get funding payment history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getAccountFunding + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Account funding history response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountFundingHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + AccountFundingHistory: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountFundingData' + more: + $ref: '#/components/schemas/more' + AccountFundingData: + type: object + required: + - instrument_id + - size + - funding_rate + - funding_asset + - funding + - timestamp + properties: + instrument_id: + $ref: '#/components/schemas/iid' + size: + $ref: '#/components/schemas/sz' + funding_rate: + $ref: '#/components/schemas/fr' + funding_asset: + $ref: '#/components/schemas/fua' + funding: + $ref: '#/components/schemas/fund' + timestamp: + $ref: '#/components/schemas/ts' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + iid: + type: integer + description: Instrument ID + example: 1 + sz: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + fr: + type: string + description: Funding rate + example: '0.0001' + fua: + type: string + description: Funding asset name + example: USDC + fund: + type: string + description: Funding paid in USD + example: '1.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-historical-funding.md b/docs/api-reference/get-historical-funding.md new file mode 100644 index 0000000..a6ee0bc --- /dev/null +++ b/docs/api-reference/get-historical-funding.md @@ -0,0 +1,217 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Historical Funding + +> Get public funding rate history for an instrument. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/funding +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/funding: + get: + summary: Get Historical Funding + description: | + Get public funding rate history for an instrument. + Maximum of 100 entries returned per request. + operationId: getFundingHistory + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Funding rate history response. + content: + application/json: + schema: + $ref: '#/components/schemas/FundingHistory' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + FundingHistory: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/FundingRate' + more: + $ref: '#/components/schemas/more' + FundingRate: + type: object + required: + - funding_rate + - timestamp + properties: + funding_rate: + $ref: '#/components/schemas/fr' + timestamp: + $ref: '#/components/schemas/ts' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + fr: + type: string + description: Funding rate + example: '0.0001' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-index.md b/docs/api-reference/get-index.md new file mode 100644 index 0000000..fbea083 --- /dev/null +++ b/docs/api-reference/get-index.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Index + +> Get index price and the list of constituents for an asset. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/index +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/index: + get: + summary: Get Index + description: Get index price and the list of constituents for an asset. + operationId: getIndex + parameters: + - name: asset + in: query + required: true + schema: + $ref: '#/components/schemas/asset' + responses: + '200': + description: Index constituents response. + content: + application/json: + schema: + $ref: '#/components/schemas/Index' + examples: + index: + summary: Index constituents + value: + asset: NVDA + index_price: '160.00' + constituents: + - source: chainlink + symbol: NVDA/USD + weight: '1.0' + price: '160.00' + ts: 1767225600000 + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + asset: + type: string + description: Asset name + example: USDC + Index: + type: object + required: + - asset + - index_price + - constituents + - ts + properties: + asset: + $ref: '#/components/schemas/asset' + index_price: + $ref: '#/components/schemas/index_price' + constituents: + type: array + items: + $ref: '#/components/schemas/IndexConstituent' + ts: + $ref: '#/components/schemas/ts' + index_price: + type: string + description: Index price + example: '100.00' + IndexConstituent: + type: object + required: + - source + - symbol + - weight + - price + properties: + source: + $ref: '#/components/schemas/source' + symbol: + $ref: '#/components/schemas/symbol' + weight: + $ref: '#/components/schemas/weight' + price: + $ref: '#/components/schemas/price' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + source: + type: string + description: Source name + example: chainlink + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + weight: + type: string + description: Index constituent weight + example: '0.25' + price: + type: string + description: Price + example: '100.00' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-instrument-config.md b/docs/api-reference/get-instrument-config.md new file mode 100644 index 0000000..c6cac46 --- /dev/null +++ b/docs/api-reference/get-instrument-config.md @@ -0,0 +1,226 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Instrument Config + +> Get per-instrument configuration (leverage and margin mode) for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/config +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/config: + get: + summary: Get Instrument Config + description: >- + Get per-instrument configuration (leverage and margin mode) for the + authenticated account. + operationId: getConfig + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Instrument config response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AccountConfig' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + AccountConfig: + description: Account configuration. + type: object + required: + - instrument_id + - leverage + - cross + properties: + instrument_id: + $ref: '#/components/schemas/iid' + leverage: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + iid: + type: integer + description: Instrument ID + example: 1 + lev: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-instruments.md b/docs/api-reference/get-instruments.md new file mode 100644 index 0000000..02662a9 --- /dev/null +++ b/docs/api-reference/get-instruments.md @@ -0,0 +1,310 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Instruments + +> Get all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/instruments +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/instruments: + get: + summary: Get Instruments + description: Get all instruments. + operationId: getInstruments + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + - name: instrument_type + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_type' + - name: category + in: query + required: false + schema: + $ref: '#/components/schemas/category' + responses: + '200': + description: Instruments response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Instrument' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + instrument_type: + type: string + description: Instrument type + enum: + - perpetual + category: + type: string + description: Instrument category + enum: + - equity + - commodity + - index + - crypto + Instrument: + type: object + required: + - instrument_id + - instrument_type + - category + - symbol + - base_asset + - quote_asset + - funding_interval + - quantity_decimals + - price_decimals + - price_bounds + - liquidation_fee + - max_order_count + - min_notional + - max_market_notional + - max_limit_notional + - max_leverage + - risk_tiers + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + instrument_type: + $ref: '#/components/schemas/instrument_type' + category: + $ref: '#/components/schemas/category' + symbol: + $ref: '#/components/schemas/symbol' + base_asset: + $ref: '#/components/schemas/base_asset' + quote_asset: + $ref: '#/components/schemas/quote_asset' + funding_interval: + $ref: '#/components/schemas/funding_interval' + quantity_decimals: + $ref: '#/components/schemas/quantity_decimals' + price_decimals: + $ref: '#/components/schemas/price_decimals' + price_bounds: + $ref: '#/components/schemas/price_bounds' + liquidation_fee: + $ref: '#/components/schemas/liquidation_fee' + max_order_count: + $ref: '#/components/schemas/max_order_count' + min_notional: + $ref: '#/components/schemas/min_notional' + max_market_notional: + $ref: '#/components/schemas/max_market_notional' + max_limit_notional: + $ref: '#/components/schemas/max_limit_notional' + max_leverage: + $ref: '#/components/schemas/max_leverage' + risk_tiers: + type: array + items: + $ref: '#/components/schemas/RiskTier' + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + base_asset: + type: string + description: Base asset name + example: NVDA + quote_asset: + type: string + description: Quote asset name + example: USDC + funding_interval: + type: string + description: Funding interval + example: 1h + quantity_decimals: + type: integer + description: Number of decimal places for quantity. + example: 2 + price_decimals: + type: integer + description: >- + Number of decimal places for price. Non-integer prices have a maximum of + 5 significant figures; integer prices are allowed regardless of + significant figures. + example: 2 + price_bounds: + type: string + description: Price bounds percentage + example: '0.05' + liquidation_fee: + type: string + description: Liquidation fee rate + example: '0.025' + max_order_count: + type: integer + description: Maximum open order count + example: 200 + min_notional: + type: string + description: Minimum notional value in USD + example: '1.00' + max_market_notional: + type: string + description: Maximum market order notional value in USD + example: '1000000.00' + max_limit_notional: + type: string + description: Maximum limit order notional value in USD + example: '10000000.00' + max_leverage: + type: integer + description: Maximum leverage + example: 20 + RiskTier: + type: object + required: + - lower_bound + - max_leverage + properties: + lower_bound: + $ref: '#/components/schemas/lower_bound' + max_leverage: + $ref: '#/components/schemas/max_leverage' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + lower_bound: + type: string + description: Position size lower bound + example: '0' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-internal-transfers.md b/docs/api-reference/get-internal-transfers.md new file mode 100644 index 0000000..2d967ae --- /dev/null +++ b/docs/api-reference/get-internal-transfers.md @@ -0,0 +1,282 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Internal Transfers + +> Get settled internal transfer history for the authenticated account. +Returns both inbound and outbound transfers. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/internal-transfers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/internal-transfers: + get: + summary: Get Internal Transfers + description: | + Get settled internal transfer history for the authenticated account. + Returns both inbound and outbound transfers. + operationId: getInternalTransfers + parameters: + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Internal transfer history response. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransfers' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + InternalTransfers: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/InternalTransfer' + more: + $ref: '#/components/schemas/more' + InternalTransfer: + type: object + required: + - transfer_id + - asset + - amount + - direction + - counterparty + - created_timestamp + properties: + transfer_id: + $ref: '#/components/schemas/transfer_id' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + direction: + $ref: '#/components/schemas/direction' + counterparty: + $ref: '#/components/schemas/counterparty' + label: + $ref: '#/components/schemas/label' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + transfer_id: + type: integer + description: Internal transfer ID + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + direction: + type: string + description: Transfer direction relative to the authenticated account + enum: + - in + - out + counterparty: + type: string + description: Counterparty account address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-klines.md b/docs/api-reference/get-klines.md new file mode 100644 index 0000000..343a9b6 --- /dev/null +++ b/docs/api-reference/get-klines.md @@ -0,0 +1,237 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Klines + +> Get klines for an instrument. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **5** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/klines +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/klines: + get: + summary: Get Klines + description: | + Get klines for an instrument. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getKlines + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Klines response. + content: + application/json: + schema: + $ref: '#/components/schemas/KlinesResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + interval: + type: string + description: Kline interval + enum: + - 1s + - 1m + - 5m + - 15m + - 30m + - 1h + - 4h + - 6h + - 12h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + KlinesResponse: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/kline' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + kline: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-limit-tiers.md b/docs/api-reference/get-limit-tiers.md new file mode 100644 index 0000000..a90655d --- /dev/null +++ b/docs/api-reference/get-limit-tiers.md @@ -0,0 +1,188 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Limit Tiers + +> Get the list of account limit tiers. Action and open-order fields are enforced per account; legacy request-rate fields are not used for gateway request enforcement. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/limit-tiers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/limit-tiers: + get: + summary: Get Limit Tiers + description: >- + Get the list of account limit tiers. Action and open-order fields are + enforced per account; legacy request-rate fields are not used for + gateway request enforcement. + operationId: getLimitTiers + responses: + '200': + description: Limit tiers response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LimitTier' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + LimitTier: + type: object + required: + - min_volume_14d + - rate_per_minute_limit + - rate_burst_limit + - actions_per_minute_limit + - actions_burst_limit + - open_orders_limit + - messages_per_minute + properties: + min_volume_14d: + $ref: '#/components/schemas/min_volume' + rate_per_minute_limit: + $ref: '#/components/schemas/rate_per_minute_limit' + rate_burst_limit: + $ref: '#/components/schemas/rate_burst_limit' + actions_per_minute_limit: + $ref: '#/components/schemas/actions_per_minute_limit' + actions_burst_limit: + $ref: '#/components/schemas/actions_burst_limit' + open_orders_limit: + $ref: '#/components/schemas/open_orders_limit' + messages_per_minute: + $ref: '#/components/schemas/messages_per_minute' + min_volume: + type: string + description: Minimum volume threshold for this tier + example: '0' + rate_per_minute_limit: + type: integer + description: >- + Maximum IP request weight per minute. In limit tiers, this is a legacy + field and is not used for gateway enforcement. + example: 1200 + rate_burst_limit: + type: integer + description: >- + Legacy limit-tier request-rate field. It is not used for gateway + enforcement. + actions_per_minute_limit: + type: integer + description: Maximum order action tokens per account per minute + example: 300 + actions_burst_limit: + type: integer + description: Additional account action allowance limit + open_orders_limit: + type: integer + description: Maximum number of open orders per account + example: 1000 + messages_per_minute: + type: integer + description: >- + Display-only per-minute action/message allowance, equal to + actions_per_minute_limit. Not separately configured or enforced. + example: 300 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-open-orders.md b/docs/api-reference/get-open-orders.md new file mode 100644 index 0000000..3160927 --- /dev/null +++ b/docs/api-reference/get-open-orders.md @@ -0,0 +1,382 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Open Orders + +> Get open orders for the authenticated account. + +Request Weight: + +
+ +With instrument ID: **1** + +
+ +Without instrument ID: **20** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/open-orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/open-orders: + get: + summary: Get Open Orders + description: Get open orders for the authenticated account. + operationId: getOpenOrders + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/iid' + responses: + '200': + description: Orders response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderData' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + iid: + type: integer + description: Instrument ID + example: 1 + OrderData: + type: object + required: + - order_id + - instrument_id + - buy + - price + - quantity + - tif + - post_only + - ro + - status + - resting_quantity + - filled_quantity + - created_timestamp + - updated_timestamp + properties: + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + post_only: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + resting_quantity: + $ref: '#/components/schemas/rest' + filled_quantity: + $ref: '#/components/schemas/fill' + status: + $ref: '#/components/schemas/st' + created_timestamp: + $ref: '#/components/schemas/cts' + updated_timestamp: + $ref: '#/components/schemas/uts' + client_order_id: + $ref: '#/components/schemas/coid' + tpsl: + $ref: '#/components/schemas/TpSlOrderFields' + description: >- + Conditional-order fields. Present only when the order is a TP/SL + conditional order — `null`/omitted for regular orders. + oid: + type: integer + description: Order ID + example: 1234567890 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + rest: + type: string + description: Resting quantity + example: '9.00' + fill: + type: string + description: Filled quantity + example: '1.00' + st: + type: string + description: Order status + example: open + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + TpSlOrderFields: + type: object + description: TP/SL-specific fields surfaced alongside the regular order shape. + required: + - kind + - scope + - trp + properties: + kind: + $ref: '#/components/schemas/kind' + scope: + $ref: '#/components/schemas/tr_scope' + trp: + $ref: '#/components/schemas/trp' + parent_oid: + $ref: '#/components/schemas/parent_oid' + armed_qty: + $ref: '#/components/schemas/qty' + description: >- + Quantity armed at attach time (OCO) or `"0"` for position-based + (sized at trigger time). + slip_bps: + $ref: '#/components/schemas/slip_bps' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kind: + type: string + description: Conditional order type (TakeProfit / StopLoss) + enum: + - tp + - sl + tr_scope: + type: string + description: > + How the conditional order sizes itself. + + - `order` - child of a parent entry (bracket / OCO ladder). Quantity is + required. + + - `position` - attached to an open position. v1 always closes the full + position (`qty` must be `"0"`). + enum: + - order + - position + trp: + type: string + description: Trigger price + example: '110.00' + parent_oid: + type: integer + description: >- + Parent entry order id. Optional — omit it (do not send `0`) when the + parent is created in the same request (inline `CreateOrder.tpsl` or + `CreateTpSlArgs.parent`); the gateway auto-wires the child to it. Set it + only to attach an order-scoped leg to an existing resting order. Inline + `CreateOrder.tpsl` rejects a non-zero value; position-scoped legs carry + no parent. + example: 1234567890 + slip_bps: + type: integer + minimum: 0 + maximum: 10000 + description: >- + Per-order market-trigger slippage cap in basis points. 0 = use the + per-instrument default. Clamped to the instrument cap. + example: 1000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-orders.md b/docs/api-reference/get-orders.md new file mode 100644 index 0000000..e02d4c0 --- /dev/null +++ b/docs/api-reference/get-orders.md @@ -0,0 +1,427 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Orders + +> Get historical order snapshots for the authenticated account from the order history database. +Returns the latest known state for each matching order, including accepted, open, partial, +filled, and cancelled orders. For currently resting orders only, use Get Open Orders. +Maximum of 100 entries returned per request. + + +Request Weight: + +
+ +With order ID: **1** + +
+ +Without order ID: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/orders: + get: + summary: Get Orders + description: > + Get historical order snapshots for the authenticated account from the + order history database. + + Returns the latest known state for each matching order, including + accepted, open, partial, + + filled, and cancelled orders. For currently resting orders only, use Get + Open Orders. + + Maximum of 100 entries returned per request. + operationId: getOrders + parameters: + - name: order_id + in: query + required: false + schema: + $ref: '#/components/schemas/order_id' + - name: client_order_id + in: query + required: false + schema: + $ref: '#/components/schemas/coid' + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/iid' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Orders response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderData' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + order_id: + type: integer + description: Order ID + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + iid: + type: integer + description: Instrument ID + example: 1 + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + OrderData: + type: object + required: + - order_id + - instrument_id + - buy + - price + - quantity + - tif + - post_only + - ro + - status + - resting_quantity + - filled_quantity + - created_timestamp + - updated_timestamp + properties: + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + post_only: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + resting_quantity: + $ref: '#/components/schemas/rest' + filled_quantity: + $ref: '#/components/schemas/fill' + status: + $ref: '#/components/schemas/st' + created_timestamp: + $ref: '#/components/schemas/cts' + updated_timestamp: + $ref: '#/components/schemas/uts' + client_order_id: + $ref: '#/components/schemas/coid' + tpsl: + $ref: '#/components/schemas/TpSlOrderFields' + description: >- + Conditional-order fields. Present only when the order is a TP/SL + conditional order — `null`/omitted for regular orders. + oid: + type: integer + description: Order ID + example: 1234567890 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + rest: + type: string + description: Resting quantity + example: '9.00' + fill: + type: string + description: Filled quantity + example: '1.00' + st: + type: string + description: Order status + example: open + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + TpSlOrderFields: + type: object + description: TP/SL-specific fields surfaced alongside the regular order shape. + required: + - kind + - scope + - trp + properties: + kind: + $ref: '#/components/schemas/kind' + scope: + $ref: '#/components/schemas/tr_scope' + trp: + $ref: '#/components/schemas/trp' + parent_oid: + $ref: '#/components/schemas/parent_oid' + armed_qty: + $ref: '#/components/schemas/qty' + description: >- + Quantity armed at attach time (OCO) or `"0"` for position-based + (sized at trigger time). + slip_bps: + $ref: '#/components/schemas/slip_bps' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kind: + type: string + description: Conditional order type (TakeProfit / StopLoss) + enum: + - tp + - sl + tr_scope: + type: string + description: > + How the conditional order sizes itself. + + - `order` - child of a parent entry (bracket / OCO ladder). Quantity is + required. + + - `position` - attached to an open position. v1 always closes the full + position (`qty` must be `"0"`). + enum: + - order + - position + trp: + type: string + description: Trigger price + example: '110.00' + parent_oid: + type: integer + description: >- + Parent entry order id. Optional — omit it (do not send `0`) when the + parent is created in the same request (inline `CreateOrder.tpsl` or + `CreateTpSlArgs.parent`); the gateway auto-wires the child to it. Set it + only to attach an order-scoped leg to an existing resting order. Inline + `CreateOrder.tpsl` rejects a non-zero value; position-scoped legs carry + no parent. + example: 1234567890 + slip_bps: + type: integer + minimum: 0 + maximum: 10000 + description: >- + Per-order market-trigger slippage cap in basis points. 0 = use the + per-instrument default. Clamped to the instrument cap. + example: 1000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-pnl.md b/docs/api-reference/get-pnl.md new file mode 100644 index 0000000..0d2dab3 --- /dev/null +++ b/docs/api-reference/get-pnl.md @@ -0,0 +1,248 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get PnL + +> Get PnL history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/pnl +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/pnl: + get: + summary: Get PnL + description: | + Get PnL history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getPnlHistory + parameters: + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/pnl_interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: PnL history response. + content: + application/json: + schema: + $ref: '#/components/schemas/PnlHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + pnl_interval: + type: string + description: PnL interval + enum: + - 1h + - 4h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + PnlHistory: + type: object + required: + - data + - more + properties: + data: + type: array + description: | + - `1767225600000` - Timestamp + - `"100.50"` - PnL + items: + type: array + example: + - 1767225600000 + - '100.50' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-portfolio.md b/docs/api-reference/get-portfolio.md new file mode 100644 index 0000000..1558fc9 --- /dev/null +++ b/docs/api-reference/get-portfolio.md @@ -0,0 +1,350 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Portfolio + +> Get current portfolio snapshot including open positions, margin summary, and withdrawable balance. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/portfolio +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/portfolio: + get: + summary: Get Portfolio + description: > + Get current portfolio snapshot including open positions, margin summary, + and withdrawable balance. + operationId: getPortfolio + responses: + '200': + description: Portfolio response. + content: + application/json: + schema: + $ref: '#/components/schemas/Portfolio' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Portfolio: + type: object + required: + - positions + - margin + - withdrawable + - in_liquidation + - timestamp + properties: + positions: + type: array + items: + $ref: '#/components/schemas/PortfolioPosition' + margin: + $ref: '#/components/schemas/MarginSummary' + withdrawable: + $ref: '#/components/schemas/withdrawable' + in_liquidation: + $ref: '#/components/schemas/in_liquidation' + timestamp: + $ref: '#/components/schemas/update_timestamp' + PortfolioPosition: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - leverage + - cross + - initial_margin + - maintenance_margin + - position_value + - liquidation_price + - unrealized_pnl + - return_on_equity + - cumulative_funding + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + size: + $ref: '#/components/schemas/size' + entry_price: + $ref: '#/components/schemas/entry_price' + leverage: + $ref: '#/components/schemas/leverage' + cross: + $ref: '#/components/schemas/cross' + initial_margin: + $ref: '#/components/schemas/initial_margin' + maintenance_margin: + $ref: '#/components/schemas/maintenance_margin_amount' + position_value: + $ref: '#/components/schemas/position_value' + liquidation_price: + $ref: '#/components/schemas/liquidation_price' + unrealized_pnl: + $ref: '#/components/schemas/unrealized_pnl' + return_on_equity: + $ref: '#/components/schemas/return_on_equity' + cumulative_funding: + $ref: '#/components/schemas/cumulative_funding' + MarginSummary: + type: object + required: + - total_account_value + - total_initial_margin + - total_maintenance_margin + - total_position_value + properties: + total_account_value: + $ref: '#/components/schemas/total_account_value' + total_initial_margin: + $ref: '#/components/schemas/total_initial_margin' + total_maintenance_margin: + $ref: '#/components/schemas/total_maintenance_margin' + total_position_value: + $ref: '#/components/schemas/total_position_value' + withdrawable: + type: string + description: Withdrawable balance in USD + example: '13104.51' + in_liquidation: + type: boolean + description: Whether the account is currently under liquidation + update_timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_id: + type: integer + description: Instrument ID + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + size: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + entry_price: + type: string + description: Average entry price + example: '2986.30' + leverage: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + initial_margin: + type: string + description: Initial margin in USD + example: '10.00' + maintenance_margin_amount: + type: string + description: Maintenance margin amount + example: '100.00' + position_value: + type: string + description: Notional position value in USD + example: '100.03' + liquidation_price: + type: string + description: Liquidation price + example: '2866.27' + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + cumulative_funding: + type: string + description: Cumulative funding paid/received in USD + example: '514.09' + total_account_value: + type: string + description: Total account value in USD (equity + unrealized PnL) + example: '13109.48' + total_initial_margin: + type: string + description: Total initial margin in use across all positions + example: '4.97' + total_maintenance_margin: + type: string + description: Total maintenance margin across all positions + example: '2.49' + total_position_value: + type: string + description: Total notional position value in USD + example: '100.03' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/get-public-portfolio.md b/docs/api-reference/get-public-portfolio.md new file mode 100644 index 0000000..bed1da3 --- /dev/null +++ b/docs/api-reference/get-public-portfolio.md @@ -0,0 +1,232 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Public Portfolio + +> Get public portfolio for an address including equity and open positions. + + +Request Weight: **5** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/portfolio +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/portfolio: + get: + summary: Get Public Portfolio + description: | + Get public portfolio for an address including equity and open positions. + operationId: getPublicPortfolio + parameters: + - name: address + in: query + required: true + schema: + $ref: '#/components/schemas/address' + responses: + '200': + description: Public portfolio response. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicPortfolio' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + PublicPortfolio: + type: object + required: + - positions + - equity + - timestamp + properties: + positions: + type: array + items: + $ref: '#/components/schemas/PublicPortfolioPosition' + equity: + $ref: '#/components/schemas/equity' + timestamp: + $ref: '#/components/schemas/update_timestamp' + PublicPortfolioPosition: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - unrealized_pnl + - return_on_equity + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + size: + $ref: '#/components/schemas/size' + entry_price: + $ref: '#/components/schemas/entry_price' + unrealized_pnl: + $ref: '#/components/schemas/unrealized_pnl' + return_on_equity: + $ref: '#/components/schemas/return_on_equity' + equity: + type: string + description: Equity in USD + example: '10000.00' + update_timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_id: + type: integer + description: Instrument ID + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + size: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + entry_price: + type: string + description: Average entry price + example: '2986.30' + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-recent-trades.md b/docs/api-reference/get-recent-trades.md new file mode 100644 index 0000000..737a2ea --- /dev/null +++ b/docs/api-reference/get-recent-trades.md @@ -0,0 +1,256 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Recent Trades + +> Get public trades for an instrument. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/trades +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/trades: + get: + summary: Get Recent Trades + description: | + Get public trades for an instrument. + Maximum of 100 entries returned per request. + operationId: getTrades + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Trades response. + content: + application/json: + schema: + $ref: '#/components/schemas/Trades' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Trades: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/TradeData' + description: Public trades for the instrument + more: + $ref: '#/components/schemas/more' + TradeData: + type: object + required: + - trade_id + - instrument_id + - side + - price + - quantity + - timestamp + - hash + properties: + trade_id: + $ref: '#/components/schemas/tid' + instrument_id: + $ref: '#/components/schemas/iid' + side: + $ref: '#/components/schemas/side' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + timestamp: + $ref: '#/components/schemas/ts' + hash: + $ref: '#/components/schemas/hash' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + tid: + type: integer + description: Trade ID + example: 1 + iid: + type: integer + description: Instrument ID + example: 1 + side: + type: string + description: Side + enum: + - long + - short + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-server-time.md b/docs/api-reference/get-server-time.md new file mode 100644 index 0000000..9bd604b --- /dev/null +++ b/docs/api-reference/get-server-time.md @@ -0,0 +1,139 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Server Time + +> Get server time. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/time +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/time: + get: + summary: Get Server Time + description: | + Get server time. + operationId: getTime + responses: + '200': + description: Successful time response. + content: + application/json: + schema: + $ref: '#/components/schemas/Time' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Time: + type: object + required: + - time + properties: + time: + $ref: '#/components/schemas/time' + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-statistics.md b/docs/api-reference/get-statistics.md new file mode 100644 index 0000000..0377284 --- /dev/null +++ b/docs/api-reference/get-statistics.md @@ -0,0 +1,195 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Statistics + +> Get last 24-hour statistics for all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/statistics +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/statistics: + get: + summary: Get Statistics + description: Get last 24-hour statistics for all instruments. + operationId: getStatistics + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Statistics response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Statistic' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + Statistic: + type: object + required: + - instrument_id + - symbol + - volume + - open_price + - klines + properties: + instrument_id: + $ref: '#/components/schemas/iid' + symbol: + $ref: '#/components/schemas/symbol' + volume: + $ref: '#/components/schemas/volume' + open_price: + $ref: '#/components/schemas/open_price' + klines: + $ref: '#/components/schemas/klines' + iid: + type: integer + description: Instrument ID + example: 1 + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + volume: + type: string + description: 24-hour trading volume in contracts + example: '1000.00' + open_price: + type: string + description: Opening price from 24 hours ago + example: '100.50' + klines: + type: array + items: + $ref: '#/components/schemas/kline' + description: Last 24-hour kline data + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kline: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-tickers.md b/docs/api-reference/get-tickers.md new file mode 100644 index 0000000..56213db --- /dev/null +++ b/docs/api-reference/get-tickers.md @@ -0,0 +1,213 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Tickers + +> Get all instrument tickers with live market data. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/tickers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/tickers: + get: + summary: Get Tickers + description: Get all instrument tickers with live market data. + operationId: getTickers + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Tickers response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ticker' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + Ticker: + allOf: + - $ref: '#/components/schemas/TickerData' + - type: object + required: + - timestamp + properties: + timestamp: + $ref: '#/components/schemas/timestamp' + TickerData: + type: object + required: + - instrument_id + - symbol + - index_price + - mark_price + - last_price + - mid_price + - open_interest + - funding_rate + - next_funding + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + index_price: + $ref: '#/components/schemas/index_price' + mark_price: + $ref: '#/components/schemas/mark_price' + last_price: + $ref: '#/components/schemas/last_price' + mid_price: + $ref: '#/components/schemas/mid_price' + open_interest: + $ref: '#/components/schemas/open_interest' + funding_rate: + $ref: '#/components/schemas/funding_rate' + next_funding: + $ref: '#/components/schemas/next_funding' + timestamp: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + index_price: + type: string + description: Index price + example: '100.00' + mark_price: + type: string + description: Mark price + example: '100.00' + last_price: + type: string + description: Last traded price + example: '100.00' + mid_price: + type: string + description: Mid price + example: '100.00' + open_interest: + type: string + description: Open interest in number of contracts + example: '10.00' + funding_rate: + type: string + description: Funding rate + example: '0.0001' + next_funding: + type: integer + description: Next funding timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/get-withdrawals.md b/docs/api-reference/get-withdrawals.md new file mode 100644 index 0000000..75d6657 --- /dev/null +++ b/docs/api-reference/get-withdrawals.md @@ -0,0 +1,325 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Withdrawals + +> Get withdrawal history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/withdrawals +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/withdrawals: + get: + summary: Get Withdrawals + description: | + Get withdrawal history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getWithdrawals + parameters: + - name: withdrawal_status + in: query + required: false + schema: + $ref: '#/components/schemas/withdrawal_status' + - name: hash + in: query + required: false + schema: + $ref: '#/components/schemas/hash' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Withdrawal history response. + content: + application/json: + schema: + $ref: '#/components/schemas/Withdrawals' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + withdrawal_status: + type: string + description: Withdrawal status + enum: + - pending + - confirmed + - removed + - failed + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Withdrawals: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/Withdrawal' + more: + $ref: '#/components/schemas/more' + Withdrawal: + type: object + required: + - withdraw_id + - asset + - amount + - fee + - status + - to + - hash + - confirmations + - required_confirmations + - created_timestamp + properties: + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + fee: + $ref: '#/components/schemas/withdrawal_fee' + status: + $ref: '#/components/schemas/withdrawal_status' + hash: + $ref: '#/components/schemas/hash' + confirmations: + $ref: '#/components/schemas/confirmations' + required_confirmations: + $ref: '#/components/schemas/required_confirmations' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + confirmed_timestamp: + $ref: '#/components/schemas/confirmed_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + withdraw_id: + type: integer + description: Withdraw ID + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + withdrawal_fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + confirmations: + type: integer + description: Number of block confirmations + example: 12 + required_confirmations: + type: integer + description: Required number of block confirmations + example: 12 + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + confirmed_timestamp: + type: integer + description: Confirmation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/docs/api-reference/internal-transfer.md b/docs/api-reference/internal-transfer.md new file mode 100644 index 0000000..4b0580b --- /dev/null +++ b/docs/api-reference/internal-transfer.md @@ -0,0 +1,304 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Internal Transfer + +> Submit a signed internal ledger transfer between two exchange accounts. +Requires proxy signature using the standard signed-op flow. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/internal-transfer +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/internal-transfer: + post: + summary: Internal Transfer + description: | + Submit a signed internal ledger transfer between two exchange accounts. + Requires proxy signature using the standard signed-op flow. + operationId: internalTransfer + requestBody: + description: Internal transfer request. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferRequest' + examples: + transfer: + summary: Transfer USDC to another account + value: + op: + type: internalTransfer + args: + account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: '100.00' + to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a1c + salt: 555555555 + ts: 1767000014000 + label: ops-rebalance + responses: + '200': + description: The accepted transfer, carrying its `transfer_id`. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + description: | + The transfer was rejected on its merits (e.g. insufficient balance, + transfer to self). The body carries `transfer_id` and `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferRejected' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + InternalTransferRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpInternalTransfer' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + label: + $ref: '#/components/schemas/label' + InternalTransferAccepted: + type: object + required: + - status + - transfer_id + properties: + status: + type: string + enum: + - ok + transfer_id: + $ref: '#/components/schemas/transfer_id' + InternalTransferRejected: + type: object + required: + - status + - transfer_id + - error + properties: + status: + type: string + enum: + - err + transfer_id: + $ref: '#/components/schemas/transfer_id' + error: + $ref: '#/components/schemas/error' + OpInternalTransfer: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - internalTransfer + args: + type: object + required: + - account + - token + - amount + - to + properties: + account: + $ref: '#/components/schemas/account' + token: + $ref: '#/components/schemas/token' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + transfer_id: + type: integer + description: Internal transfer ID + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + account: + type: string + description: Account address in hex format + example: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: + type: string + description: Token contract address in hex format + example: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/set-auto-cancel.md b/docs/api-reference/set-auto-cancel.md new file mode 100644 index 0000000..b6f08b2 --- /dev/null +++ b/docs/api-reference/set-auto-cancel.md @@ -0,0 +1,364 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Set Auto-Cancel + +> Set a dead man switch that will cancel all open orders at the specified time. +Time must be at least 5 seconds in the future, or `0` to clear an active +schedule without triggering it. Posting a new auto-cancel replaces the +previous one. + +The switch is one-shot: once the deadline elapses and your open orders are +cancelled, the schedule clears automatically. Orders you place after the +fire are not affected by the expired deadline — re-arm to extend +protection. + +Each account may trigger auto-cancel at most 10 times per UTC day. Once +that limit is reached, further attempts to arm a schedule are rejected with +`auto_cancel_daily_limit_reached` until the next UTC day; clearing an +existing schedule (`time: 0`) is always allowed. + +Use `GET /v1/account/auto-cancel` to check the current deadline, today's +trigger count, and when the daily counter resets. + +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1** Action Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json patch /v1/trade/auto-cancel +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/auto-cancel: + patch: + summary: Set Auto-Cancel + description: > + Set a dead man switch that will cancel all open orders at the specified + time. + + Time must be at least 5 seconds in the future, or `0` to clear an active + + schedule without triggering it. Posting a new auto-cancel replaces the + + previous one. + + + The switch is one-shot: once the deadline elapses and your open orders + are + + cancelled, the schedule clears automatically. Orders you place after the + + fire are not affected by the expired deadline — re-arm to extend + + protection. + + + Each account may trigger auto-cancel at most 10 times per UTC day. Once + + that limit is reached, further attempts to arm a schedule are rejected + with + + `auto_cancel_daily_limit_reached` until the next UTC day; clearing an + + existing schedule (`time: 0`) is always allowed. + + + Use `GET /v1/account/auto-cancel` to check the current deadline, today's + + trigger count, and when the daily counter resets. + + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: setAutoCancel + requestBody: + description: Auto-cancel request. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelRequest' + examples: + enable: + summary: Enable auto-cancel + value: + op: + type: autoCancel + args: + time: 1767000045000 + sig: >- + 0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b1c + salt: 666666666 + ts: 1767000015000 + disable: + summary: Disable auto-cancel + value: + op: + type: autoCancel + args: + time: 0 + sig: >- + 0x8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f1c + salt: 666666667 + ts: 1767000016000 + responses: + '200': + description: The effective auto-cancel schedule after the update. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '404': + $ref: '#/components/responses/Error404Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + AutoCancelRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpAutoCancel' + - $ref: '#/components/schemas/BaseOp' + AutoCancelResponse: + description: > + The effective auto-cancel schedule after the update. `deadline` echoes + the + + armed Unix-ms time, or `0` when the schedule was cleared (`time: 0`). + type: object + required: + - status + - deadline + properties: + status: + type: string + enum: + - ok + deadline: + $ref: '#/components/schemas/auto_cancel_deadline' + OpAutoCancel: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - autoCancel + args: + type: object + required: + - time + properties: + time: + $ref: '#/components/schemas/time' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + auto_cancel_deadline: + type: integer + description: | + Unix-ms deadline for the per-account auto-cancel dead-man-switch. + Zero means no schedule is armed. When the deadline elapses, every + open order on the account is cancelled and the schedule clears. + example: 1767000045000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error404: + title: Error404 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error404Response: + description: | + Not found — the endpoint is disabled on this venue (e.g. auto-cancel) or + the route does not exist. `error` is `not_found`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error404' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/test-connection.md b/docs/api-reference/test-connection.md new file mode 100644 index 0000000..a94604f --- /dev/null +++ b/docs/api-reference/test-connection.md @@ -0,0 +1,134 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Test Connection + +> Test connection to the server. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/ping +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/ping: + get: + summary: Test Connection + description: | + Test connection to the server. + operationId: getPing + responses: + '200': + description: Successful ping response. + content: + application/json: + schema: + type: object + required: + - status + properties: + status: + type: string + example: ok + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + schemas: + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + +```` \ No newline at end of file diff --git a/docs/api-reference/update-leverage.md b/docs/api-reference/update-leverage.md new file mode 100644 index 0000000..16063b5 --- /dev/null +++ b/docs/api-reference/update-leverage.md @@ -0,0 +1,290 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Update Leverage + +> Update leverage for an instrument. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1** Action Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json patch /v1/trade/leverage +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/leverage: + patch: + summary: Update Leverage + description: > + Update leverage for an instrument. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: updateLeverage + requestBody: + description: Leverage request. + content: + application/json: + schema: + $ref: '#/components/schemas/LeverageRequest' + examples: + updateLeverage: + summary: Update leverage for one instrument + value: + op: + type: updateLeverage + args: + iid: 1 + lev: 5 + cross: false + sig: >- + 0x59ed57f6dce8d15aa01e774ef53d9957c84801fb34ec655f6a2ea344af8a58843095314730a3f1bd8f0f4560f6dc6f8de69d3f2d0a6f3365fc877f7f4845d40b1c + salt: 333333333 + ts: 1767000012000 + responses: + '200': + description: The instrument's effective leverage configuration after the update. + content: + application/json: + schema: + $ref: '#/components/schemas/LeverageResponse' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + LeverageRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpUpdateLeverage' + - $ref: '#/components/schemas/BaseOp' + LeverageResponse: + description: The instrument's effective leverage configuration after the update. + type: object + required: + - status + - instrument_id + - leverage + - cross + properties: + status: + type: string + enum: + - ok + instrument_id: + $ref: '#/components/schemas/iid' + leverage: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + OpUpdateLeverage: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - updateLeverage + args: + type: object + required: + - iid + - lev + - cross + properties: + iid: + $ref: '#/components/schemas/iid' + lev: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + iid: + type: integer + description: Instrument ID + example: 1 + lev: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/withdraw.md b/docs/api-reference/withdraw.md new file mode 100644 index 0000000..a0cda59 --- /dev/null +++ b/docs/api-reference/withdraw.md @@ -0,0 +1,318 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Withdraw + +> Submit a signed withdrawal request. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + +The `amount` field is the raw token amount including decimals (e.g. `"100000000"` for 100 USDC). +This must match the `uint256 amount` value used in the EIP-712 `Withdraw` signature. + +The `ts` field is Unix seconds (not milliseconds) because the on-chain contract validates it +against `block.timestamp`. It must also match the `uint64 ts` in the signed EIP-712 struct. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/withdraw +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/withdraw: + post: + summary: Withdraw + description: > + Submit a signed withdrawal request. + + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + + The `amount` field is the raw token amount including decimals (e.g. + `"100000000"` for 100 USDC). + + This must match the `uint256 amount` value used in the EIP-712 + `Withdraw` signature. + + + The `ts` field is Unix seconds (not milliseconds) because the on-chain + contract validates it + + against `block.timestamp`. It must also match the `uint64 ts` in the + signed EIP-712 struct. + operationId: withdraw + requestBody: + description: Withdraw request. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawRequest' + examples: + withdraw: + summary: Withdraw 100 USDC + value: + op: + type: withdraw + args: + account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: '100000000' + to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a1c + salt: 555555555 + ts: 1767000014 + responses: + '200': + description: The accepted withdrawal, carrying its `withdraw_id`. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + description: > + The withdrawal was rejected on its merits (e.g. insufficient + balance). + + The body carries `withdraw_id` and `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawRejected' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + WithdrawRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpWithdraw' + - $ref: '#/components/schemas/BaseOp' + WithdrawAccepted: + type: object + required: + - status + - withdraw_id + properties: + status: + type: string + enum: + - ok + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + WithdrawRejected: + type: object + required: + - status + - withdraw_id + - error + properties: + status: + type: string + enum: + - err + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + error: + $ref: '#/components/schemas/error' + OpWithdraw: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - withdraw + args: + type: object + required: + - account + - token + - amount + - to + properties: + account: + $ref: '#/components/schemas/account' + token: + $ref: '#/components/schemas/token' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + withdraw_id: + type: integer + description: Withdraw ID + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + account: + type: string + description: Account address in hex format + example: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: + type: string + description: Token contract address in hex format + example: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-auth.md b/docs/api-reference/wss/perps-auth.md new file mode 100644 index 0000000..cdedcd2 --- /dev/null +++ b/docs/api-reference/wss/perps-auth.md @@ -0,0 +1,274 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Auth + +> Perps WebSocket authentication. + + + +## AsyncAPI + +````yaml asyncapi-perps.json auth +id: auth +title: Auth +description: Authentication to access private channels. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: AuthSend + title: Auth send + description: Authenticate connection + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Auth + description: Authenticate this WebSocket connection for private channels + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - auth + required: true + - name: args + type: object + required: true + properties: + - name: proxy + type: string + description: Proxy address in hex format + required: true + - name: secret + type: string + description: API secret + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - auth + x-parser-schema-id: + args: + type: object + required: + - proxy + - secret + properties: + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + x-parser-schema-id: + secret: + type: string + description: API secret + example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - req + - op + x-parser-schema-id: + title: Auth + description: Authenticate this WebSocket connection for private channels + example: |- + { + "req": "post", + "op": { + "type": "auth", + "args": { + "proxy": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", + "secret": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" + } + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: auth + - &ref_2 + id: AuthReceive + title: Auth receive + description: Auth response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Auth Response + description: Authentication result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Auth Response + description: Authentication result + example: |- + { + "id": 123, + "data": { + "status": "", + "error": "" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: auth +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-auto-cancel.md b/docs/api-reference/wss/perps-auto-cancel.md new file mode 100644 index 0000000..a380148 --- /dev/null +++ b/docs/api-reference/wss/perps-auto-cancel.md @@ -0,0 +1,305 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Auto Cancel + +> Perps WebSocket dead man's switch updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json autoCancel +id: autoCancel +title: Auto-Cancel +description: | + Arm or clear the per-account auto-cancel schedule. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **10** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: AutoCancelSend + title: Auto cancel send + description: Set or clear auto-cancel + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Auto-Cancel Request + description: Client submits a signed auto-cancel request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - autoCancel + required: true + - name: args + type: object + required: true + properties: + - name: time + type: integer + description: Timestamp in milliseconds + required: true + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - autoCancel + x-parser-schema-id: + args: + type: object + required: + - time + properties: + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Auto-Cancel Request + description: Client submits a signed auto-cancel request + example: |- + { + "req": "post", + "op": { + "type": "autoCancel", + "args": { + "time": 1767225600000 + } + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: autoCancel + - &ref_2 + id: AutoCancelReceive + title: Auto cancel receive + description: Auto-cancel response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Auto-Cancel Response + description: Server responds with auto-cancel result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Auto-Cancel Response + description: Server responds with auto-cancel result + example: |- + { + "id": 5, + "data": { + "status": "ok" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: autoCancel +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-balances.md b/docs/api-reference/wss/perps-balances.md new file mode 100644 index 0000000..95b5a91 --- /dev/null +++ b/docs/api-reference/wss/perps-balances.md @@ -0,0 +1,586 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Balances + +> Perps WebSocket private balance updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json balances +id: balances +title: Balances +description: >- + Real-time balance updates. Pushed every 5 seconds. Requires authentication, + see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BalancesSubscribe + title: Balances subscribe + description: Subscribe to balances + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private balance updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Balances private channel: "balances"' + required: true + properties: + - name: item + type: string + enumValues: + - balances + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Balances private channel: "balances"' + items: + type: string + enum: + - balances + x-parser-schema-id: + example: + - balances + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private balance updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "balances" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: balances + - &ref_3 + id: BalancesSubscribeResponse + title: Balances subscribe response + description: Balances subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to balances subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to balances subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BalancesUnsubscribe + title: Balances unsubscribe + description: Unsubscribe from balances + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private balance updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Balances private channel: "balances"' + required: true + properties: + - name: item + type: string + enumValues: + - balances + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Balances private channel: "balances"' + items: + type: string + enum: + - balances + x-parser-schema-id: + example: + - balances + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private balance updates + example: |- + { + "req": "unsub", + "chs": [ + "balances" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BalancesUnsubscribeResponse + title: Balances unsubscribe response + description: Balances unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to balances unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to balances unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BalancesUpdate + title: Balances update + description: Receive balance updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Balance updates pushed every 5 seconds + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Balance object + required: true + properties: + - name: asset + type: string + description: Asset name + required: true + - name: balance + type: string + description: Total balance + required: true + - name: value + type: string + description: USD value + required: true + headers: [] + jsonPayloadSchema: + title: Balances Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Balance object + properties: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + balance: + type: string + description: Total balance + example: '10000.00' + x-parser-schema-id: + value: + type: string + description: USD value + example: '10000.00' + x-parser-schema-id: + required: + - asset + - balance + - value + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Balance updates pushed every 5 seconds + example: |- + { + "ch": "balances", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "asset": "USDC", + "balance": "10000.00", + "value": "10000.00" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: balances +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-bbo.md b/docs/api-reference/wss/perps-bbo.md new file mode 100644 index 0000000..52221e9 --- /dev/null +++ b/docs/api-reference/wss/perps-bbo.md @@ -0,0 +1,606 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# BBO + +> Perps WebSocket best bid and offer updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json bbo +id: bbo +title: BBO +description: Best bid and offer real-time updates. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BBOSubscribe + title: B b o subscribe + description: Subscribe to BBO + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to BBO updates for a specific instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + items: + type: string + pattern: ^bbo::\d+$ + x-parser-schema-id: + example: + - bbo::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to BBO updates for a specific instrument + example: |- + { + "req": "sub", + "chs": [ + "bbo::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: bbo + - &ref_3 + id: BBOSubscribeResponse + title: B b o subscribe response + description: BBO subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to BBO subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to BBO subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BBOUnsubscribe + title: B b o unsubscribe + description: Unsubscribe from BBO + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from BBO updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + items: + type: string + pattern: ^bbo::\d+$ + x-parser-schema-id: + example: + - bbo::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from BBO updates + example: |- + { + "req": "unsub", + "chs": [ + "bbo::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BBOUnsubscribeResponse + title: B b o unsubscribe response + description: BBO unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to BBO unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to BBO unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BBOUpdate + title: B b o update + description: Receive BBO updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time BBO updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + title: BBO Data + description: BBO object + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: bp + type: string + description: Best bid price + required: true + - name: bq + type: string + description: Best bid quantity + required: true + - name: ap + type: string + description: Best ask price + required: true + - name: aq + type: string + description: Best ask quantity + required: true + headers: [] + jsonPayloadSchema: + title: BBO Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: BBO object + title: BBO Data + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + bp: + type: string + description: Best bid price + example: '99.50' + x-parser-schema-id: + bq: + type: string + description: Best bid quantity + example: '10.00' + x-parser-schema-id: + ap: + type: string + description: Best ask price + example: '100.50' + x-parser-schema-id: + aq: + type: string + description: Best ask quantity + example: '10.00' + x-parser-schema-id: + required: + - iid + - bp + - bq + - ap + - aq + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time BBO updates for subscribed instruments + example: |- + { + "ch": "bbo::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "iid": 1, + "bp": "99.50", + "bq": "10.00", + "ap": "100.50", + "aq": "10.00" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: bbo +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-book.md b/docs/api-reference/wss/perps-book.md new file mode 100644 index 0000000..9388051 --- /dev/null +++ b/docs/api-reference/wss/perps-book.md @@ -0,0 +1,621 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Book + +> Perps WebSocket order book updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json book +id: book +title: Book +description: Order book snapshot updates. Pushed every 100ms. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BookSubscribe + title: Book subscribe + description: Subscribe to book + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to order book updates for an instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + items: + type: string + pattern: ^book::\d+$ + x-parser-schema-id: + example: + - book::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to order book updates for an instrument + example: |- + { + "req": "sub", + "chs": [ + "book::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: book + - &ref_3 + id: BookSubscribeResponse + title: Book subscribe response + description: Book subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to book subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to book subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BookUnsubscribe + title: Book unsubscribe + description: Unsubscribe from book + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from order book updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + items: + type: string + pattern: ^book::\d+$ + x-parser-schema-id: + example: + - book::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from order book updates + example: |- + { + "req": "unsub", + "chs": [ + "book::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BookUnsubscribeResponse + title: Book unsubscribe response + description: Book unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to book unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to book unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BookUpdate + title: Book update + description: Receive book updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time order book updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + required: true + properties: + - name: b + type: array + description: Bid levels + required: true + properties: + - name: item + type: array + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + required: false + properties: + - name: item + type: string + required: false + - name: a + type: array + description: Ask levels + required: true + properties: + - name: item + type: array + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + required: false + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + title: Book Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + required: + - b + - a + properties: + b: + type: array + items: + type: array + items: + type: string + x-parser-schema-id: + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + x-parser-schema-id: + description: Bid levels + x-parser-schema-id: + a: + type: array + items: + type: array + items: + type: string + x-parser-schema-id: + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + x-parser-schema-id: + description: Ask levels + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time order book updates for subscribed instruments + example: |- + { + "ch": "book::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "b": [ + [ + "100.00", + "10.00" + ] + ], + "a": [ + [ + "100.00", + "10.00" + ] + ] + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: book +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-cancel-orders-coid.md b/docs/api-reference/wss/perps-cancel-orders-coid.md new file mode 100644 index 0000000..542d303 --- /dev/null +++ b/docs/api-reference/wss/perps-cancel-orders-coid.md @@ -0,0 +1,406 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders by Client Order ID + +> Perps WebSocket order cancellation by client order ID. + + + +## AsyncAPI + +````yaml asyncapi-perps.json cancelOrdersCOID +id: cancelOrdersCOID +title: Cancel Orders COID +description: | + Cancel orders by client order ID. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **0** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: CancelOrdersCOIDSend + title: Cancel orders c o i d send + description: Cancel orders by client order ID + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Cancel Orders COID Request + description: Client submits a signed cancel-by-client-order-id request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - cancelOrdersCOID + required: true + - name: args + type: array + description: > + Array of client order IDs to cancel. Cancelling an order + that has + + attached take-profit / stop-loss children (see + `CreateOrder.tr`) + + cascades to those children — they are cancelled with + reason + + `ParentCancelled`. + required: true + properties: + - name: item + type: string + description: Client order ID + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrdersCOID + x-parser-schema-id: + args: + type: array + description: > + Array of client order IDs to cancel. Cancelling an order + that has + + attached take-profit / stop-loss children (see + `CreateOrder.tr`) + + cascades to those children — they are cancelled with reason + + `ParentCancelled`. + items: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Cancel Orders COID Request + description: Client submits a signed cancel-by-client-order-id request + example: |- + { + "req": "post", + "op": { + "type": "cancelOrdersCOID", + "args": [ + "550e8400e29b41d4a716446655440000" + ] + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: cancelOrdersCOID + - &ref_2 + id: CancelOrdersCOIDReceive + title: Cancel orders c o i d receive + description: Cancel by client order ID response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Cancel Orders COID Response + description: Server responds with cancel result for each client order ID + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + description: Array of cancel results + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: coid + type: string + description: Client order ID + required: false + - name: status + type: string + enumValues: + - err + required: true + - name: oid + type: integer + description: Order ID + required: false + - name: coid + type: string + description: Client order ID + required: false + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: array + description: Array of cancel results + items: + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Cancel Orders COID Response + description: Server responds with cancel result for each client order ID + example: |- + { + "id": 3, + "data": [ + { + "status": "ok", + "oid": 1234567890, + "coid": "550e8400e29b41d4a716446655440000" + }, + { + "status": "ok", + "oid": 1234567891, + "coid": "550e8400e29b41d4a716446655440001" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: cancelOrdersCOID +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-cancel-orders.md b/docs/api-reference/wss/perps-cancel-orders.md new file mode 100644 index 0000000..2c3aa2e --- /dev/null +++ b/docs/api-reference/wss/perps-cancel-orders.md @@ -0,0 +1,398 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders + +> Perps WebSocket order cancellation by order ID. + + + +## AsyncAPI + +````yaml asyncapi-perps.json cancelOrders +id: cancelOrders +title: Cancel Orders +description: | + Cancel orders. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **0** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: CancelOrdersSend + title: Cancel orders send + description: Cancel orders + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Cancel Orders Request + description: Client submits a signed order cancellation request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - cancelOrders + required: true + - name: args + type: array + description: > + Array of order IDs to cancel. Cancelling an order that has + attached + + take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to + + those children — they are cancelled with reason + `ParentCancelled`. + required: true + properties: + - name: item + type: integer + description: Order ID + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrders + x-parser-schema-id: + args: + type: array + description: > + Array of order IDs to cancel. Cancelling an order that has + attached + + take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to + + those children — they are cancelled with reason + `ParentCancelled`. + items: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Cancel Orders Request + description: Client submits a signed order cancellation request + example: |- + { + "req": "post", + "op": { + "type": "cancelOrders", + "args": [ + 1234567890 + ] + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: cancelOrders + - &ref_2 + id: CancelOrdersReceive + title: Cancel orders receive + description: Cancel response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Cancel Orders Response + description: Server responds with cancel result for each order + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + description: Array of cancel results + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: coid + type: string + description: Client order ID + required: false + - name: status + type: string + enumValues: + - err + required: true + - name: oid + type: integer + description: Order ID + required: false + - name: coid + type: string + description: Client order ID + required: false + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: array + description: Array of cancel results + items: + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Cancel Orders Response + description: Server responds with cancel result for each order + example: |- + { + "id": 3, + "data": [ + { + "status": "ok", + "oid": 1234567890 + }, + { + "status": "ok", + "oid": 1234567891 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: cancelOrders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-deposits.md b/docs/api-reference/wss/perps-deposits.md new file mode 100644 index 0000000..dc57892 --- /dev/null +++ b/docs/api-reference/wss/perps-deposits.md @@ -0,0 +1,614 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Deposits + +> Perps WebSocket private deposit updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json deposits +id: deposits +title: Deposits +description: >- + Real-time deposit status updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: DepositsSubscribe + title: Deposits subscribe + description: Subscribe to deposits + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private deposit updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Deposits private channel: "deposits"' + required: true + properties: + - name: item + type: string + enumValues: + - deposits + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Deposits private channel: "deposits"' + items: + type: string + enum: + - deposits + x-parser-schema-id: + example: + - deposits + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private deposit updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "deposits" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: deposits + - &ref_3 + id: DepositsSubscribeResponse + title: Deposits subscribe response + description: Deposits subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to deposits subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to deposits subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: DepositsUnsubscribe + title: Deposits unsubscribe + description: Unsubscribe from deposits + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private deposit updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Deposits private channel: "deposits"' + required: true + properties: + - name: item + type: string + enumValues: + - deposits + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Deposits private channel: "deposits"' + items: + type: string + enum: + - deposits + x-parser-schema-id: + example: + - deposits + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private deposit updates + example: |- + { + "req": "unsub", + "chs": [ + "deposits" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: DepositsUnsubscribeResponse + title: Deposits unsubscribe response + description: Deposits unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to deposits unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to deposits unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: DepositsUpdate + title: Deposits update + description: Receive deposit updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Deposit status updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of deposit objects + required: true + properties: + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + - name: asset + type: string + description: Asset name + required: true + - name: amount + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + required: true + - name: status + type: string + description: Deposit status + enumValues: + - pending + - confirmed + - removed + required: true + headers: [] + jsonPayloadSchema: + title: Deposits Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of deposit objects + properties: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + example: '100000000' + x-parser-schema-id: + status: + type: string + description: Deposit status + enum: + - pending + - confirmed + - removed + x-parser-schema-id: + required: + - hash + - asset + - amount + - status + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Deposit status updates for authenticated users + example: |- + { + "ch": "deposits", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + "asset": "USDC", + "amount": "100000000", + "status": "pending" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: deposits +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-fills.md b/docs/api-reference/wss/perps-fills.md new file mode 100644 index 0000000..3f1b35e --- /dev/null +++ b/docs/api-reference/wss/perps-fills.md @@ -0,0 +1,727 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fills + +> Perps WebSocket private fill updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json fills +id: fills +title: Fills +description: Real-time fill updates. Requires authentication, see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: FillsSubscribe + title: Fills subscribe + description: Subscribe to fills + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private fill updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Fills private channel: "fills"' + required: true + properties: + - name: item + type: string + enumValues: + - fills + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Fills private channel: "fills"' + items: + type: string + enum: + - fills + x-parser-schema-id: + example: + - fills + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private fill updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "fills" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: fills + - &ref_3 + id: FillsSubscribeResponse + title: Fills subscribe response + description: Fills subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to fills subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to fills subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: FillsUnsubscribe + title: Fills unsubscribe + description: Unsubscribe from fills + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private fill updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Fills private channel: "fills"' + required: true + properties: + - name: item + type: string + enumValues: + - fills + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Fills private channel: "fills"' + items: + type: string + enum: + - fills + x-parser-schema-id: + example: + - fills + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private fill updates + example: |- + { + "req": "unsub", + "chs": [ + "fills" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: FillsUnsubscribeResponse + title: Fills unsubscribe response + description: Fills unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to fills unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to fills unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: FillsUpdate + title: Fills update + description: Receive fill updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time fill updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of fill objects + required: true + properties: + - name: tid + type: integer + description: Trade ID + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: side + type: string + description: Side + enumValues: + - long + - short + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: taker + type: boolean + description: Whether this side was the taker + required: true + - name: fee + type: string + description: Fee amount for this trade side + required: true + - name: fea + type: string + description: Fee asset name + required: true + - name: psz + type: string + description: Position size before the fill + required: true + - name: pep + type: string + description: Position entry price before the fill + required: true + - name: pnl + type: string + description: PnL in USD + required: true + - name: liq + type: boolean + description: Whether the fill was a liquidation + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: coid + type: string + description: Client order ID + required: false + headers: [] + jsonPayloadSchema: + title: Fills Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of fill objects + properties: + tid: + type: integer + description: Trade ID + example: 1 + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + side: + type: string + description: Side + enum: + - long + - short + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + taker: + type: boolean + description: Whether this side was the taker + x-parser-schema-id: + fee: + type: string + description: Fee amount for this trade side + example: '1.25' + x-parser-schema-id: + fea: + type: string + description: Fee asset name + example: USDC + x-parser-schema-id: + psz: + type: string + description: Position size before the fill + example: '26.86' + x-parser-schema-id: + pep: + type: string + description: Position entry price before the fill + example: '100.00' + x-parser-schema-id: + pnl: + type: string + description: PnL in USD + example: '100.00' + x-parser-schema-id: + liq: + type: boolean + description: Whether the fill was a liquidation + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + required: + - tid + - oid + - iid + - side + - p + - qty + - taker + - fee + - fea + - psz + - pep + - pnl + - ts + - liq + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time fill updates for authenticated users + example: |- + { + "ch": "fills", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "tid": 1, + "oid": 1234567890, + "iid": 1, + "side": "long", + "p": "100.00", + "qty": "10.00", + "fee": "1.25", + "fea": "USDC", + "psz": "26.86", + "pep": "100.00", + "pnl": "100.00", + "ts": 1767225600000, + "coid": "550e8400e29b41d4a716446655440000" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: fills +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-funding.md b/docs/api-reference/wss/perps-funding.md new file mode 100644 index 0000000..857173a --- /dev/null +++ b/docs/api-reference/wss/perps-funding.md @@ -0,0 +1,631 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Funding + +> Perps WebSocket private funding updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json funding +id: funding +title: Funding +description: >- + Real-time funding payment updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: FundingSubscribe + title: Funding subscribe + description: Subscribe to funding + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private funding payment updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Funding private channel: "funding"' + required: true + properties: + - name: item + type: string + enumValues: + - funding + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Funding private channel: "funding"' + items: + type: string + enum: + - funding + x-parser-schema-id: + example: + - funding + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private funding payment updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "funding" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: funding + - &ref_3 + id: FundingSubscribeResponse + title: Funding subscribe response + description: Funding subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to funding subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to funding subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: FundingUnsubscribe + title: Funding unsubscribe + description: Unsubscribe from funding + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private funding updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Funding private channel: "funding"' + required: true + properties: + - name: item + type: string + enumValues: + - funding + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Funding private channel: "funding"' + items: + type: string + enum: + - funding + x-parser-schema-id: + example: + - funding + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private funding updates + example: |- + { + "req": "unsub", + "chs": [ + "funding" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: FundingUnsubscribeResponse + title: Funding unsubscribe response + description: Funding unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to funding unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to funding unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: FundingUpdate + title: Funding update + description: Receive funding updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time funding payment updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of funding objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: sz + type: string + description: >- + Signed position size in no. of contracts (positive = long, + negative = short) + required: true + - name: fr + type: string + description: Funding rate + required: true + - name: fund + type: string + description: Funding paid in USD + required: true + - name: fua + type: string + description: Funding asset name + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + title: Funding Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of funding objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + sz: + type: string + description: >- + Signed position size in no. of contracts (positive = long, + negative = short) + example: '10.00' + x-parser-schema-id: + fr: + type: string + description: Funding rate + example: '0.0001' + x-parser-schema-id: + fund: + type: string + description: Funding paid in USD + example: '1.00' + x-parser-schema-id: + fua: + type: string + description: Funding asset name + example: USDC + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - iid + - sz + - fr + - fund + - fua + - ts + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time funding payment updates for authenticated users + example: |- + { + "ch": "funding", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "sz": "10.00", + "fr": "0.0001", + "fund": "1.00", + "fua": "USDC", + "ts": 1767225600000 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: funding +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-klines.md b/docs/api-reference/wss/perps-klines.md new file mode 100644 index 0000000..65f758a --- /dev/null +++ b/docs/api-reference/wss/perps-klines.md @@ -0,0 +1,590 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Klines + +> Perps WebSocket candle updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json klines +id: klines +title: Klines +description: Real-time kline updates. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: KlinesSubscribe + title: Klines subscribe + description: Subscribe to klines + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to kline updates for an instrument and interval + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" + (e.g., "klines::1::1m") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" (e.g., + "klines::1::1m") + items: + type: string + pattern: ^klines::\d+::(1m|5m|15m|30m|1h|4h|6h|12h|1d|1w)$ + x-parser-schema-id: + example: + - klines::1::1m + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to kline updates for an instrument and interval + example: |- + { + "req": "sub", + "chs": [ + "klines::1::1m" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: klines + - &ref_3 + id: KlinesSubscribeResponse + title: Klines subscribe response + description: Klines subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to klines subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to klines subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: KlinesUnsubscribe + title: Klines unsubscribe + description: Unsubscribe from klines + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from kline updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" + (e.g., "klines::1::1m") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" (e.g., + "klines::1::1m") + items: + type: string + pattern: ^klines::\d+::(1m|5m|15m|30m|1h|4h|6h|12h|1d|1w)$ + x-parser-schema-id: + example: + - klines::1::1m + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from kline updates + example: |- + { + "req": "unsub", + "chs": [ + "klines::1::1m" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: KlinesUnsubscribeResponse + title: Klines unsubscribe response + description: Klines unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to klines unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to klines unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: KlinesUpdate + title: Klines update + description: Receive kline updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time kline updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: array + description: Array of kline arrays + required: true + properties: + - name: item + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + required: false + headers: [] + jsonPayloadSchema: + title: Kline Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: array + description: Array of kline arrays + items: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time kline updates for subscribed instruments + example: |- + { + "ch": "klines::1::1m", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + [ + 1767225600000, + "100.00", + "105.00", + "99.00", + "102.00", + "500.00", + 42 + ] + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: klines +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-orders.md b/docs/api-reference/wss/perps-orders.md new file mode 100644 index 0000000..28d71d3 --- /dev/null +++ b/docs/api-reference/wss/perps-orders.md @@ -0,0 +1,716 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Orders + +> Perps WebSocket private order updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json orders +id: orders +title: Orders +description: Real-time order updates. Requires authentication, see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: OrdersSubscribe + title: Orders subscribe + description: Subscribe to orders + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private order updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Orders private channel: "orders"' + required: true + properties: + - name: item + type: string + enumValues: + - orders + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Orders private channel: "orders"' + items: + type: string + enum: + - orders + x-parser-schema-id: + example: + - orders + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private order updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "orders" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: orders + - &ref_3 + id: OrdersSubscribeResponse + title: Orders subscribe response + description: Orders subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to orders subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to orders subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: OrdersUnsubscribe + title: Orders unsubscribe + description: Unsubscribe from orders + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private order updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Orders private channel: "orders"' + required: true + properties: + - name: item + type: string + enumValues: + - orders + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Orders private channel: "orders"' + items: + type: string + enum: + - orders + x-parser-schema-id: + example: + - orders + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private order updates + example: |- + { + "req": "unsub", + "chs": [ + "orders" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: OrdersUnsubscribeResponse + title: Orders unsubscribe response + description: Orders unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to orders unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to orders unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: OrdersUpdate + title: Orders update + description: Receive order updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time order updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Order object + required: true + properties: + - name: oid + type: integer + description: Order ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: buy + type: boolean + description: Is buy + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: tif + type: string + description: Time in force + enumValues: + - gtc + - ioc + - fok + required: true + - name: po + type: boolean + description: Post only + required: true + - name: ro + type: boolean + description: Reduce only + required: true + - name: rest + type: string + description: Resting quantity + required: true + - name: fill + type: string + description: Filled quantity + required: true + - name: cts + type: integer + description: Create timestamp in milliseconds + required: true + - name: uts + type: integer + description: Update timestamp in milliseconds + required: true + - name: status + type: string + description: Order status + required: true + - name: coid + type: string + description: Client order ID + required: false + headers: [] + jsonPayloadSchema: + title: Orders Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Order object + properties: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + buy: + type: boolean + description: Is buy + example: true + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + x-parser-schema-id: + po: + type: boolean + description: Post only + default: false + example: false + x-parser-schema-id: + ro: + type: boolean + description: Reduce only + example: false + default: false + x-parser-schema-id: + rest: + type: string + description: Resting quantity + example: '9.00' + x-parser-schema-id: + fill: + type: string + description: Filled quantity + example: '1.00' + x-parser-schema-id: + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + status: + type: string + description: Order status + example: open + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + required: + - oid + - iid + - buy + - p + - qty + - tif + - po + - ro + - status + - rest + - fill + - cts + - uts + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time order updates for authenticated users + example: |- + { + "ch": "orders", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "oid": 1234567890, + "iid": 1, + "buy": true, + "p": "100.00", + "qty": "10.00", + "tif": "gtc", + "po": false, + "ro": false, + "rest": "9.00", + "fill": "1.00", + "cts": 1767225600000, + "uts": 1767225600000, + "status": "open", + "coid": "550e8400e29b41d4a716446655440000" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: orders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-ping.md b/docs/api-reference/wss/perps-ping.md new file mode 100644 index 0000000..6993025 --- /dev/null +++ b/docs/api-reference/wss/perps-ping.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Ping + +> Perps WebSocket heartbeat. + + + +## AsyncAPI + +````yaml asyncapi-perps.json ping +id: ping +title: Ping +description: >- + Connections are automatically closed after 60 seconds of inactivity. Send a + ping message periodically to keep the connection alive. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PingSend + title: Ping send + description: Send ping + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Ping + description: Client sends ping to test connection and keep alive + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - ping + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + properties: + type: + type: string + enum: + - ping + x-parser-schema-id: + x-parser-schema-id: + required: + - req + - op + x-parser-schema-id: + title: Ping + description: Client sends ping to test connection and keep alive + example: |- + { + "req": "post", + "op": { + "type": "ping" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: ping + - &ref_2 + id: PingReceive + title: Ping receive + description: Pong response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Pong + description: Server responds with pong including connection info + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + description: Result status + enumValues: + - ok + - err + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: object + required: + - status + - ts + - sq + properties: + status: + type: string + enum: + - ok + - err + description: Result status + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Pong + description: Server responds with pong including connection info + example: |- + { + "data": { + "status": "ok", + "ts": 1767225600000, + "sq": 1234567890 + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: ping +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-place-orders.md b/docs/api-reference/wss/perps-place-orders.md new file mode 100644 index 0000000..102c970 --- /dev/null +++ b/docs/api-reference/wss/perps-place-orders.md @@ -0,0 +1,478 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Place Orders + +> Perps WebSocket order placement. + + + +## AsyncAPI + +````yaml asyncapi-perps.json placeOrders +id: placeOrders +title: Create Orders +description: | + Create new orders. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **1 / order** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PlaceOrdersSend + title: Place orders send + description: Submit new orders + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Create Orders Request + description: Client submits a signed order placement request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - createOrders + required: true + - name: args + type: object + description: Array of orders to create + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: buy + type: boolean + description: Is buy + required: true + - name: p + type: string + description: Price + required: false + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: tif + type: string + description: Time in force + enumValues: + - gtc + - ioc + - fok + required: false + - name: po + type: boolean + description: Post only + required: false + - name: ro + type: boolean + description: Reduce only + required: false + - name: c + type: string + description: Client order ID + required: false + - name: tr + type: object + description: Optional trigger attached to this order. + required: false + properties: + - name: market + type: boolean + description: Whether the trigger executes as a market order + required: false + - name: trp + type: string + description: Trigger price + required: false + - name: tpsl + type: string + description: Trigger type + enumValues: + - tp + - sl + required: false + - name: grp + type: string + description: TPSL grouping + enumValues: + - order + - position + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createOrders + x-parser-schema-id: + args: + description: Array of orders to create + type: object + required: + - iid + - buy + - qty + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + buy: + type: boolean + description: Is buy + example: true + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + x-parser-schema-id: + po: + type: boolean + description: Post only + default: false + example: false + x-parser-schema-id: + ro: + type: boolean + description: Reduce only + example: false + default: false + x-parser-schema-id: + c: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + tr: + type: object + description: Optional trigger attached to this order. + properties: + market: + type: boolean + description: Whether the trigger executes as a market order + x-parser-schema-id: + trp: + type: string + description: Trigger price + example: '110.00' + x-parser-schema-id: + tpsl: + type: string + description: Trigger type + enum: + - tp + - sl + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + grp: + type: string + description: TPSL grouping + enum: + - order + - position + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Create Orders Request + description: Client submits a signed order placement request + example: |- + { + "req": "post", + "op": { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "100.00", + "qty": "10.00", + "tif": "gtc", + "po": false, + "ro": false, + "c": "550e8400e29b41d4a716446655440000", + "tr": { + "trp": "110.00", + "tpsl": "tp" + } + } + ], + "grp": "order" + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: placeOrders + - &ref_2 + id: PlaceOrdersReceive + title: Place orders receive + description: Order ACK response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Create Orders Response + description: Server responds with order ACK for each submitted order + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + description: Array of order results + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: object + description: Array of order results + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Create Orders Response + description: Server responds with order ACK for each submitted order + example: |- + { + "id": 1, + "data": [ + { + "status": "ok", + "oid": 1234567890 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: placeOrders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-portfolio.md b/docs/api-reference/wss/perps-portfolio.md new file mode 100644 index 0000000..ca64306 --- /dev/null +++ b/docs/api-reference/wss/perps-portfolio.md @@ -0,0 +1,798 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Portfolio + +> Perps WebSocket private portfolio updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json portfolio +id: portfolio +title: Portfolio +description: >- + Real-time portfolio updates. Pushed every 5 seconds. Requires authentication, + see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PortfolioSubscribe + title: Portfolio subscribe + description: Subscribe to portfolio + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private portfolio updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Portfolio private channel: "portfolio"' + required: true + properties: + - name: item + type: string + enumValues: + - portfolio + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Portfolio private channel: "portfolio"' + items: + type: string + enum: + - portfolio + x-parser-schema-id: + example: + - portfolio + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private portfolio updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "portfolio" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: portfolio + - &ref_3 + id: PortfolioSubscribeResponse + title: Portfolio subscribe response + description: Portfolio subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to portfolio subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to portfolio subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: PortfolioUnsubscribe + title: Portfolio unsubscribe + description: Unsubscribe from portfolio + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private portfolio updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Portfolio private channel: "portfolio"' + required: true + properties: + - name: item + type: string + enumValues: + - portfolio + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Portfolio private channel: "portfolio"' + items: + type: string + enum: + - portfolio + x-parser-schema-id: + example: + - portfolio + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private portfolio updates + example: |- + { + "req": "unsub", + "chs": [ + "portfolio" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: PortfolioUnsubscribeResponse + title: Portfolio unsubscribe response + description: Portfolio unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to portfolio unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to portfolio unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: PortfolioUpdate + title: Portfolio update + description: Receive portfolio updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Portfolio updates pushed every 5 seconds + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + required: true + properties: + - name: positions + type: array + required: true + properties: + - name: instrument_id + type: integer + description: Instrument ID + required: true + - name: symbol + type: string + description: Instrument symbol + required: true + - name: size + type: string + description: >- + Signed position size in no. of contracts (positive = + long, negative = short) + required: true + - name: entry_price + type: string + description: Average entry price + required: true + - name: leverage + type: integer + description: Leverage + required: true + - name: cross + type: boolean + description: Whether to use cross margin mode + required: true + - name: initial_margin + type: string + description: Initial margin in USD + required: true + - name: maintenance_margin + type: string + description: Maintenance margin amount + required: true + - name: position_value + type: string + description: Notional position value in USD + required: true + - name: liquidation_price + type: string + description: Liquidation price + required: true + - name: unrealized_pnl + type: string + description: Unrealized PnL in USD + required: true + - name: return_on_equity + type: string + description: Return on equity as a decimal + required: true + - name: cumulative_funding + type: string + description: Cumulative funding paid/received in USD + required: true + - name: margin + type: object + required: true + properties: + - name: total_account_value + type: string + description: Total account value in USD (equity + unrealized PnL) + required: true + - name: total_initial_margin + type: string + description: Total initial margin in use across all positions + required: true + - name: total_maintenance_margin + type: string + description: Total maintenance margin across all positions + required: true + - name: total_position_value + type: string + description: Total notional position value in USD + required: true + - name: withdrawable + type: string + description: Withdrawable balance in USD + required: true + - name: in_liquidation + type: boolean + description: Whether the account is currently under liquidation + required: true + - name: timestamp + type: integer + description: Update timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + title: Portfolio Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + required: + - positions + - margin + - withdrawable + - in_liquidation + - timestamp + properties: + positions: + type: array + items: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - leverage + - cross + - initial_margin + - maintenance_margin + - position_value + - liquidation_price + - unrealized_pnl + - return_on_equity + - cumulative_funding + properties: + instrument_id: + type: integer + description: Instrument ID + x-parser-schema-id: + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + x-parser-schema-id: + size: + type: string + description: >- + Signed position size in no. of contracts (positive = + long, negative = short) + example: '10.00' + x-parser-schema-id: + entry_price: + type: string + description: Average entry price + example: '2986.30' + x-parser-schema-id: + leverage: + type: integer + description: Leverage + example: 10 + x-parser-schema-id: + cross: + type: boolean + description: Whether to use cross margin mode + x-parser-schema-id: + initial_margin: + type: string + description: Initial margin in USD + example: '10.00' + x-parser-schema-id: + maintenance_margin: + type: string + description: Maintenance margin amount + example: '100.00' + x-parser-schema-id: + position_value: + type: string + description: Notional position value in USD + example: '100.03' + x-parser-schema-id: + liquidation_price: + type: string + description: Liquidation price + example: '2866.27' + x-parser-schema-id: + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + x-parser-schema-id: + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + x-parser-schema-id: + cumulative_funding: + type: string + description: Cumulative funding paid/received in USD + example: '514.09' + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + margin: + type: object + required: + - total_account_value + - total_initial_margin + - total_maintenance_margin + - total_position_value + properties: + total_account_value: + type: string + description: Total account value in USD (equity + unrealized PnL) + example: '13109.48' + x-parser-schema-id: + total_initial_margin: + type: string + description: Total initial margin in use across all positions + example: '4.97' + x-parser-schema-id: + total_maintenance_margin: + type: string + description: Total maintenance margin across all positions + example: '2.49' + x-parser-schema-id: + total_position_value: + type: string + description: Total notional position value in USD + example: '100.03' + x-parser-schema-id: + x-parser-schema-id: + withdrawable: + type: string + description: Withdrawable balance in USD + example: '13104.51' + x-parser-schema-id: + in_liquidation: + type: boolean + description: Whether the account is currently under liquidation + x-parser-schema-id: + timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Portfolio updates pushed every 5 seconds + example: |- + { + "ch": "portfolio", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "positions": [ + { + "symbol": "NVDA-USDC", + "size": "10.00", + "entry_price": "2986.30", + "leverage": 10, + "initial_margin": "10.00", + "maintenance_margin": "100.00", + "position_value": "100.03", + "liquidation_price": "2866.27", + "unrealized_pnl": "-0.01", + "return_on_equity": "-0.0027", + "cumulative_funding": "514.09" + } + ], + "margin": { + "total_account_value": "13109.48", + "total_initial_margin": "4.97", + "total_maintenance_margin": "2.49", + "total_position_value": "100.03" + }, + "withdrawable": "13104.51", + "timestamp": 1767225600000 + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: portfolio +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-statistics.md b/docs/api-reference/wss/perps-statistics.md new file mode 100644 index 0000000..9f4e1e5 --- /dev/null +++ b/docs/api-reference/wss/perps-statistics.md @@ -0,0 +1,655 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Statistics + +> Perps WebSocket 24-hour statistics updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json statistics +id: statistics +title: Statistics +description: 24-hour statistics updates. Pushed every 1 second. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: StatisticsSubscribe + title: Statistics subscribe + description: Subscribe to statistics + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: >- + Subscribe to 24-hour statistics updates for all instruments or a + specific one + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + items: + type: string + pattern: ^statistics::(\d+|all)$ + x-parser-schema-id: + example: + - statistics::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: >- + Subscribe to 24-hour statistics updates for all instruments or a + specific one + example: |- + { + "req": "sub", + "chs": [ + "statistics::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: statistics + - &ref_3 + id: StatisticsSubscribeResponse + title: Statistics subscribe response + description: Statistics subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to statistics subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to statistics subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: StatisticsUnsubscribe + title: Statistics unsubscribe + description: Unsubscribe from statistics + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from statistics updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + items: + type: string + pattern: ^statistics::(\d+|all)$ + x-parser-schema-id: + example: + - statistics::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from statistics updates + example: |- + { + "req": "unsub", + "chs": [ + "statistics::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: StatisticsUnsubscribeResponse + title: Statistics unsubscribe response + description: Statistics unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to statistics unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to statistics unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: StatisticsUpdate + title: Statistics update + description: Receive statistics updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: 24-hour statistics for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of statistics objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: vol + type: string + description: 24-hour trading volume in contracts + required: true + - name: open + type: string + description: Opening price from 24 hours ago + required: true + - name: klines + type: array + description: Last 24-hour kline data + required: true + properties: + - name: item + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + required: false + headers: [] + jsonPayloadSchema: + title: Statistics Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of statistics objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + vol: + type: string + description: 24-hour trading volume in contracts + example: '1000.00' + x-parser-schema-id: + open: + type: string + description: Opening price from 24 hours ago + example: '100.50' + x-parser-schema-id: + klines: + type: array + items: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + x-parser-schema-id: + description: Last 24-hour kline data + x-parser-schema-id: + required: + - iid + - vol + - open + - klines + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: 24-hour statistics for subscribed instruments + example: |- + { + "ch": "statistics::all", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "vol": "1000.00", + "open": "100.50", + "klines": [ + [ + 1767225600000, + "100.00", + "105.00", + "99.00", + "102.00", + "500.00", + 42 + ] + ] + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: statistics +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-tickers.md b/docs/api-reference/wss/perps-tickers.md new file mode 100644 index 0000000..58c3278 --- /dev/null +++ b/docs/api-reference/wss/perps-tickers.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Tickers + +> Perps WebSocket ticker updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json tickers +id: tickers +title: Tickers +description: Ticker updates. Pushed every 100ms. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: TickersSubscribe + title: Tickers subscribe + description: Subscribe to tickers + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to ticker updates for all instruments or a specific one + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Ticker subscription: `tickers::all` for every active + instrument, + + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + Ticker subscription: `tickers::all` for every active instrument, + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + items: + type: string + pattern: ^tickers::(\d+|all)$ + x-parser-schema-id: + example: + - tickers::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to ticker updates for all instruments or a specific one + example: |- + { + "req": "sub", + "chs": [ + "tickers::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: tickers + - &ref_3 + id: TickersSubscribeResponse + title: Tickers subscribe response + description: Tickers subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to tickers subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to tickers subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: TickersUnsubscribe + title: Tickers unsubscribe + description: Unsubscribe from tickers + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from ticker updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Ticker subscription: `tickers::all` for every active + instrument, + + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + Ticker subscription: `tickers::all` for every active instrument, + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + items: + type: string + pattern: ^tickers::(\d+|all)$ + x-parser-schema-id: + example: + - tickers::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from ticker updates + example: |- + { + "req": "unsub", + "chs": [ + "tickers::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: TickersUnsubscribeResponse + title: Tickers unsubscribe response + description: Tickers unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to tickers unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to tickers unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: TickersUpdate + title: Tickers update + description: Receive ticker updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time ticker updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of ticker objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: idx + type: string + description: Index price + required: true + - name: mark + type: string + description: Mark price + required: true + - name: last + type: string + description: Last traded price + required: true + - name: mid + type: string + description: Mid price + required: true + - name: oi + type: string + description: Open interest in number of contracts + required: true + - name: fr + type: string + description: Funding rate + required: true + - name: nxf + type: integer + description: Next funding timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + title: Ticker Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of ticker objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + idx: + type: string + description: Index price + example: '100.00' + x-parser-schema-id: + mark: + type: string + description: Mark price + example: '100.00' + x-parser-schema-id: + last: + type: string + description: Last traded price + example: '100.00' + x-parser-schema-id: + mid: + type: string + description: Mid price + example: '100.00' + x-parser-schema-id: + oi: + type: string + description: Open interest in number of contracts + example: '10.00' + x-parser-schema-id: + fr: + type: string + description: Funding rate + example: '0.0001' + x-parser-schema-id: + nxf: + type: integer + description: Next funding timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + required: + - iid + - idx + - mark + - last + - mid + - oi + - fr + - nxf + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time ticker updates for subscribed instruments + example: |- + { + "ch": "tickers::all", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "idx": "100.00", + "mark": "100.00", + "last": "100.00", + "mid": "100.00", + "oi": "10.00", + "fr": "0.0001", + "nxf": 1767225600000 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: tickers +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-trades.md b/docs/api-reference/wss/perps-trades.md new file mode 100644 index 0000000..d194222 --- /dev/null +++ b/docs/api-reference/wss/perps-trades.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Trades + +> Perps WebSocket public trade updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json trades +id: trades +title: Trades +description: Real-time trade stream. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: TradesSubscribe + title: Trades subscribe + description: Subscribe to trades + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to public trade updates for an instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + items: + type: string + pattern: ^trades::\d+$ + x-parser-schema-id: + example: + - trades::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to public trade updates for an instrument + example: |- + { + "req": "sub", + "chs": [ + "trades::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: trades + - &ref_3 + id: TradesSubscribeResponse + title: Trades subscribe response + description: Trades subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to trades subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to trades subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: TradesUnsubscribe + title: Trades unsubscribe + description: Unsubscribe from trades + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from public trade updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + items: + type: string + pattern: ^trades::\d+$ + x-parser-schema-id: + example: + - trades::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from public trade updates + example: |- + { + "req": "unsub", + "chs": [ + "trades::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: TradesUnsubscribeResponse + title: Trades unsubscribe response + description: Trades unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to trades unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to trades unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: TradesUpdate + title: Trades update + description: Receive trade updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time trade updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + title: TradeResponse + description: Array of trade objects + required: true + properties: + - name: tid + type: integer + description: Trade ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: side + type: string + description: Side + enumValues: + - long + - short + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + headers: [] + jsonPayloadSchema: + title: Trades Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of trade objects + title: TradeResponse + properties: + tid: + type: integer + description: Trade ID + example: 1 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + side: + type: string + description: Side + enum: + - long + - short + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + required: + - tid + - iid + - side + - p + - qty + - ts + - hash + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time trade updates for subscribed instruments + example: |- + { + "ch": "trades::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "tid": 1, + "iid": 1, + "side": "long", + "p": "100.00", + "qty": "10.00", + "ts": 1767225600000, + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: trades +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-update-leverage.md b/docs/api-reference/wss/perps-update-leverage.md new file mode 100644 index 0000000..8414254 --- /dev/null +++ b/docs/api-reference/wss/perps-update-leverage.md @@ -0,0 +1,325 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Update Leverage + +> Perps WebSocket leverage updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json updateLeverage +id: updateLeverage +title: Update Leverage +description: | + Set leverage and margin type for an instrument. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **1** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: UpdateLeverageSend + title: Update leverage send + description: Update leverage + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Update Leverage Request + description: Client submits a signed leverage update request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - updateLeverage + required: true + - name: args + type: object + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: lev + type: integer + description: Leverage + required: true + - name: cross + type: boolean + description: Whether to use cross margin mode + required: true + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - updateLeverage + x-parser-schema-id: + args: + type: object + required: + - iid + - lev + - cross + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + lev: + type: integer + description: Leverage + example: 10 + x-parser-schema-id: + cross: + type: boolean + description: Whether to use cross margin mode + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Update Leverage Request + description: Client submits a signed leverage update request + example: |- + { + "req": "post", + "op": { + "type": "updateLeverage", + "args": { + "iid": 1, + "lev": 10 + } + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: updateLeverage + - &ref_2 + id: UpdateLeverageReceive + title: Update leverage receive + description: Update leverage response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Update Leverage Response + description: Server responds with leverage update result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Update Leverage Response + description: Server responds with leverage update result + example: |- + { + "id": 6, + "data": { + "status": "ok" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: updateLeverage +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/api-reference/wss/perps-withdrawals.md b/docs/api-reference/wss/perps-withdrawals.md new file mode 100644 index 0000000..9214d20 --- /dev/null +++ b/docs/api-reference/wss/perps-withdrawals.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Withdrawals + +> Perps WebSocket private withdrawal updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json withdrawals +id: withdrawals +title: Withdrawals +description: >- + Real-time withdrawal status updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: WithdrawalsSubscribe + title: Withdrawals subscribe + description: Subscribe to withdrawals + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private withdrawal updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Withdrawals private channel: "withdrawals"' + required: true + properties: + - name: item + type: string + enumValues: + - withdrawals + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Withdrawals private channel: "withdrawals"' + items: + type: string + enum: + - withdrawals + x-parser-schema-id: + example: + - withdrawals + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private withdrawal updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "withdrawals" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: withdrawals + - &ref_3 + id: WithdrawalsSubscribeResponse + title: Withdrawals subscribe response + description: Withdrawals subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to withdrawals subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to withdrawals subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: WithdrawalsUnsubscribe + title: Withdrawals unsubscribe + description: Unsubscribe from withdrawals + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private withdrawal updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Withdrawals private channel: "withdrawals"' + required: true + properties: + - name: item + type: string + enumValues: + - withdrawals + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Withdrawals private channel: "withdrawals"' + items: + type: string + enum: + - withdrawals + x-parser-schema-id: + example: + - withdrawals + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private withdrawal updates + example: |- + { + "req": "unsub", + "chs": [ + "withdrawals" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: WithdrawalsUnsubscribeResponse + title: Withdrawals unsubscribe response + description: Withdrawals unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to withdrawals unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to withdrawals unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: WithdrawalsUpdate + title: Withdrawals update + description: Receive withdrawal updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Withdrawal status updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of withdrawal objects + required: true + properties: + - name: withdraw_id + type: integer + description: Withdraw ID + required: true + - name: asset + type: string + description: Asset name + required: true + - name: amount + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + required: true + - name: fee + type: string + description: Withdrawal transaction fee in decimalized asset units + required: true + - name: to + type: string + description: Destination address in hex format + required: true + - name: status + type: string + description: Withdrawal status + enumValues: + - pending + - confirmed + - removed + - failed + required: true + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + headers: [] + jsonPayloadSchema: + title: Withdrawals Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of withdrawal objects + properties: + withdraw_id: + type: integer + description: Withdraw ID + x-parser-schema-id: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + example: '100000000' + x-parser-schema-id: + fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + x-parser-schema-id: + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + x-parser-schema-id: + status: + type: string + description: Withdrawal status + enum: + - pending + - confirmed + - removed + - failed + x-parser-schema-id: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + required: + - withdraw_id + - asset + - amount + - fee + - to + - status + - hash + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Withdrawal status updates for authenticated users + example: |- + { + "ch": "withdrawals", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "asset": "USDC", + "amount": "100000000", + "fee": "5.00", + "to": "0x1234567890abcdef1234567890abcdef12345678", + "status": "pending", + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: withdrawals +securitySchemes: [] + +```` \ No newline at end of file diff --git a/docs/perps/account-management.md b/docs/perps/account-management.md new file mode 100644 index 0000000..234fb1c --- /dev/null +++ b/docs/perps/account-management.md @@ -0,0 +1,1186 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Account Management + +> Monitor balances, positions, and account history + +Use account reads to turn Perps activity into a reliable local view of account +health, trading history, and performance. + + + Account management workflows require an [authenticated + session](/perps/authenticated-sessions). + + +## Review Account Health + +Start with the account's current collateral and exposure when showing portfolio +health or checking whether a trade fits the account's risk state. + +### Balances + +Use balances to show collateral by asset and account value. + + + + ```ts theme={null} + const balances = await session.fetchBalances(); + ``` + + Use this shape to render collateral balances and account value by asset. + + + + ```ts Type theme={null} + type PerpsBalance = { + asset: string; + balance: string; + value: string; + }; + + type Output = PerpsBalance[]; + ``` + + ```json Example theme={null} + [ + { + "asset": "pUSD", + "balance": "1000", + "value": "1000" + } + ] + ``` + + + + + + ```python theme={null} + balances = await session.fetch_balances() + ``` + + Use this shape to render collateral balances and account value by asset. + + + ```json theme={null} + [ + { + "asset": "pUSD", + "balance": "1000", + "value": "1000" + } + ] + ``` + + + + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/balances" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + Use this shape to render collateral balances and account value by asset. + + + ```json theme={null} + [ + { + "asset": "pUSD", + "balance": "1000", + "value": "1000" + } + ] + ``` + + + + +### Portfolio + +Use the portfolio to show open positions, margin usage, withdrawable collateral, +and liquidation state. + + + + ```ts theme={null} + const portfolio = await session.fetchPortfolio(); + ``` + + Use this shape to render positions, margin usage, and liquidation state. + + + + ```ts Type theme={null} + type PerpsPortfolio = { + positions: Array<{ + instrumentId: number; + symbol: string; + size: string; + entryPrice: string; + leverage: number; + cross: boolean; + initialMargin: string; + maintenanceMargin: string; + positionValue: string; + liquidationPrice: string; + unrealizedPnl: string; + returnOnEquity: string; + cumulativeFunding: string; + }>; + margin: { + totalAccountValue: string; + totalInitialMargin: string; + totalMaintenanceMargin: string; + totalPositionValue: string; + }; + withdrawable: string; + inLiquidation: boolean; + timestamp: number; + }; + + type Output = PerpsPortfolio; + ``` + + ```json Example theme={null} + { + "positions": [ + { + "instrumentId": 1, + "symbol": "BTC-PERP", + "size": "0.01", + "entryPrice": "65000", + "leverage": 5, + "cross": false, + "initialMargin": "130", + "maintenanceMargin": "65", + "positionValue": "650", + "liquidationPrice": "52000", + "unrealizedPnl": "0", + "returnOnEquity": "0", + "cumulativeFunding": "0" + } + ], + "margin": { + "totalAccountValue": "1000", + "totalInitialMargin": "130", + "totalMaintenanceMargin": "65", + "totalPositionValue": "650" + }, + "withdrawable": "870", + "inLiquidation": false, + "timestamp": 1767000000000 + } + ``` + + + + + + ```python theme={null} + portfolio = await session.fetch_portfolio() + ``` + + Use this shape to render positions, margin usage, and liquidation state. + + + ```json theme={null} + { + "positions": [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "size": "0.01", + "entry_price": "65000", + "leverage": 5, + "cross": false, + "initial_margin": "130", + "maintenance_margin": "65", + "position_value": "650", + "liquidation_price": "52000", + "unrealized_pnl": "0", + "return_on_equity": "0", + "cumulative_funding": "0" + } + ], + "margin": { + "total_account_value": "1000", + "total_initial_margin": "130", + "total_maintenance_margin": "65", + "total_position_value": "650" + }, + "withdrawable": "870", + "in_liquidation": false, + "timestamp": 1767000000000 + } + ``` + + + + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + Use this shape to render positions, margin usage, and liquidation state. + + + ```json theme={null} + { + "positions": [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "size": "0.01", + "entry_price": "65000", + "leverage": 5, + "cross": false, + "initial_margin": "130", + "maintenance_margin": "65", + "position_value": "650", + "liquidation_price": "52000", + "unrealized_pnl": "0", + "return_on_equity": "0", + "cumulative_funding": "0" + } + ], + "margin": { + "total_account_value": "1000", + "total_initial_margin": "130", + "total_maintenance_margin": "65", + "total_position_value": "650" + }, + "withdrawable": "870", + "in_liquidation": false, + "timestamp": 1767000000000 + } + ``` + + + + +### Account Stats + +Use account stats to review trailing 7-day trading activity such as volume and +maker share. Stats are cached by UTC day and may be stale by up to 24 hours. See +[Fee Metrics](/perps/learn-about-trading/fees#fee-metrics) for what each metric +means. + + + + ```ts theme={null} + const stats = await session.fetchStats(); + ``` + + Use this shape to render trailing 7-day volume and maker-share activity. + + + + ```ts Type theme={null} + type PerpsAccountStats = { + volume7d: string; + takerVolume7d: string; + makerVolume7d: string; + accountMakerShare7d: string; + entityMakerShare7d?: string; + entityId?: number; + entityName?: string; + }; + ``` + + ```json Example theme={null} + { + "volume7d": "5000000", + "takerVolume7d": "3500000", + "makerVolume7d": "1500000", + "accountMakerShare7d": "0.35", + "entityMakerShare7d": "0.40", + "entityId": 42, + "entityName": "desk" + } + ``` + + + + + + ```python theme={null} + stats = await session.fetch_stats() + ``` + + Use this shape to render trailing 7-day volume and maker-share activity. + + + ```json theme={null} + { + "volume_7d": "5000000", + "taker_volume_7d": "3500000", + "maker_volume_7d": "1500000", + "account_maker_share_7d": "0.35", + "entity_maker_share_7d": "0.40", + "entity_id": 42, + "entity_name": "desk" + } + ``` + + + + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/stats" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + Use this shape to render trailing 7-day volume and maker-share activity. + + + ```json theme={null} + { + "volume_7d": "5000000", + "taker_volume_7d": "3500000", + "maker_volume_7d": "1500000", + "account_maker_share_7d": "0.35", + "entity_maker_share_7d": "0.40", + "entity_id": 42, + "entity_name": "desk" + } + ``` + + + + +## Reconcile Orders and Fills + +Use order state and fills to connect submitted orders with resting liquidity, +executions, fees, and exposure changes. + +### Open Orders + +Use open orders to show what is still resting on the book. + + + + ```ts theme={null} + const openOrders = await session.fetchOpenOrders({ + instrumentId: instrument.id, + }); + ``` + + Use this shape to render resting orders that can still fill or be canceled. + + + ```json theme={null} + [ + { + "id": 1234567890, + "instrumentId": 1, + "buy": true, + "price": "65000", + "quantity": "0.01", + "timeInForce": "gtc", + "postOnly": false, + "status": "open", + "restingQuantity": "0.01", + "filledQuantity": "0", + "createdTimestamp": 1767000010000, + "updatedTimestamp": 1767000010000 + } + ] + ``` + + + + + ```python theme={null} + open_orders = await session.fetch_open_orders( + instrument_id=instrument.id, + ) + ``` + + Use this shape to render resting orders that can still fill or be canceled. + + + ```json theme={null} + [ + { + "id": 1234567890, + "instrument_id": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "gtc", + "post_only": false, + "status": "open", + "resting_quantity": "0.01", + "filled_quantity": "0", + "created_at": 1767000010000, + "updated_at": 1767000010000 + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/open-orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + Use this shape to render resting orders that can still fill or be canceled. + + + ```json theme={null} + [ + { + "order_id": 1234567890, + "instrument_id": 1, + "buy": true, + "price": "65000", + "quantity": "0.01", + "tif": "gtc", + "post_only": false, + "ro": false, + "status": "open", + "resting_quantity": "0.01", + "filled_quantity": "0", + "created_timestamp": 1767000010000, + "updated_timestamp": 1767000010000 + } + ] + ``` + + + + +### Orders + +Use orders to inspect the latest known state for submitted orders. + + + + ```ts theme={null} + const orders = await session.fetchOrders({ + instrumentId: instrument.id, + }); + ``` + + Use this shape to reconcile submitted orders with their latest known state. + + + ```json theme={null} + [ + { + "id": 1234567890, + "instrumentId": 1, + "buy": true, + "price": "65000", + "quantity": "0.01", + "timeInForce": "ioc", + "postOnly": false, + "status": "filled", + "restingQuantity": "0", + "filledQuantity": "0.01", + "createdTimestamp": 1767000010000, + "updatedTimestamp": 1767000010500 + } + ] + ``` + + + + + ```python theme={null} + orders = await session.fetch_orders( + instrument_id=instrument.id, + ) + ``` + + Use this shape to reconcile submitted orders with their latest known state. + + + ```json theme={null} + [ + { + "id": 1234567890, + "instrument_id": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "ioc", + "post_only": false, + "status": "filled", + "resting_quantity": "0", + "filled_quantity": "0.01", + "created_at": 1767000010000, + "updated_at": 1767000010500 + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + Use this shape to reconcile submitted orders with their latest known state. + + + ```json theme={null} + [ + { + "order_id": 1234567890, + "instrument_id": 1, + "buy": true, + "price": "65000", + "quantity": "0.01", + "tif": "ioc", + "post_only": false, + "ro": false, + "status": "filled", + "resting_quantity": "0", + "filled_quantity": "0.01", + "created_timestamp": 1767000010000, + "updated_timestamp": 1767000010500 + } + ] + ``` + + + + +### Fills + +Use fills to reconcile executions, fees, realized PnL, and exposure changes. + + + + ```ts theme={null} + const fills = session.listFills({ + start: Date.now() - 24 * 60 * 60 * 1000, + end: Date.now(), + }); + + for await (const page of fills) { + // page.items: PerpsAccountFill[] + } + ``` + + Each page returns execution records you can use to reconcile fees, PnL, and exposure. + + + ```json theme={null} + [ + { + "tradeId": 987654321, + "orderId": 1234567890, + "instrumentId": 1, + "side": "long", + "price": "65000", + "quantity": "0.01", + "taker": true, + "fee": "0.26", + "feeAsset": "pUSD", + "previousSize": "0", + "previousEntryPrice": "0", + "pnl": "0", + "liquidation": false, + "timestamp": 1767000010500, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ] + ``` + + + + + ```python theme={null} + from datetime import datetime, timedelta, timezone + + end = datetime.now(timezone.utc) + start = end - timedelta(days=1) + + fills = session.list_fills(start=start, end=end) + + async for page in fills: + # page.items: tuple[PerpsFill, ...] + pass + ``` + + Each page returns execution records you can use to reconcile fees, PnL, and exposure. + + + ```json theme={null} + [ + { + "trade_id": 987654321, + "order_id": 1234567890, + "instrument_id": 1, + "side": "long", + "price": "65000", + "quantity": "0.01", + "taker": true, + "fee": "0.26", + "fee_asset": "pUSD", + "previous_size": "0", + "previous_entry_price": "0", + "pnl": "0", + "liquidation": false, + "timestamp": 1767000010500, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/fills" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "start_timestamp=1766913600000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns execution records you can use to reconcile fees, PnL, and exposure. + + + ```json theme={null} + { + "data": [ + { + "trade_id": 987654321, + "order_id": 1234567890, + "instrument_id": 1, + "side": "long", + "price": "65000", + "quantity": "0.01", + "taker": true, + "fee": "0.26", + "fee_asset": "pUSD", + "previous_size": "0", + "previous_entry_price": "0", + "pnl": "0", + "liquidation": false, + "timestamp": 1767000010500, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ], + "more": false + } + ``` + + + + +## Reconcile Funding and Transfers + +Funding, deposits, and withdrawals explain collateral changes that did not come +from order fills. Use [Fund Your Account](/perps/fund-your-account) for deposit +and withdrawal submission workflows. + +### Funding Payments + +Use funding payments to explain periodic funding debits or credits for a market. + + + + ```ts theme={null} + const fundingPayments = session.listFundingPayments({ + instrumentId: instrument.id, + }); + + for await (const page of fundingPayments) { + // page.items: PerpsAccountFundingPayment[] + } + ``` + + Each page returns funding records you can use to explain non-trade PnL changes. + + + ```json theme={null} + [ + { + "instrumentId": 1, + "size": "0.01", + "fundingRate": "0.0001", + "fundingAsset": "pUSD", + "funding": "0.05", + "timestamp": 1767000010000 + } + ] + ``` + + + + + ```python theme={null} + funding_payments = session.list_funding_payments( + instrument_id=instrument.id, + ) + + async for page in funding_payments: + # page.items: tuple[PerpsFundingPayment, ...] + pass + ``` + + Each page returns funding records you can use to explain non-trade PnL changes. + + + ```json theme={null} + [ + { + "instrument_id": 1, + "size": "0.01", + "funding_rate": "0.0001", + "funding_asset": "pUSD", + "funding": "0.05", + "timestamp": 1767000010000 + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/funding" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" \ + --data-urlencode "start_timestamp=1766913600000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns funding records you can use to explain non-trade PnL changes. + + + ```json theme={null} + { + "data": [ + { + "instrument_id": 1, + "size": "0.01", + "funding_rate": "0.0001", + "funding_asset": "pUSD", + "funding": "0.05", + "timestamp": 1767000010000 + } + ], + "more": false + } + ``` + + + + +### Deposits + +Use deposits to reconcile collateral added to the Perps account. + + + + ```ts theme={null} + const deposits = session.listDeposits(); + + for await (const page of deposits) { + // page.items: PerpsDeposit[] + } + ``` + + Each page returns deposits you can match against collateral arriving in the account. + + + ```json theme={null} + [ + { + "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", + "asset": "pUSD", + "amount": "100000000", + "status": "confirmed", + "from": "0x1234567890abcdef1234567890abcdef12345678", + "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", + "confirmations": 12, + "requiredConfirmations": 12, + "createdTimestamp": 1767000010000, + "confirmedTimestamp": 1767000030000 + } + ] + ``` + + + + + ```python theme={null} + deposits = session.list_deposits() + + async for page in deposits: + # page.items: tuple[PerpsDeposit, ...] + pass + ``` + + Each page returns deposits you can match against collateral arriving in the account. + + + ```json theme={null} + [ + { + "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", + "asset": "pUSD", + "amount": "100000000", + "status": "confirmed", + "from_address": "0x1234567890abcdef1234567890abcdef12345678", + "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", + "confirmations": 12, + "required_confirmations": 12, + "created_at": 1767000010000, + "confirmed_at": 1767000030000 + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/deposits" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "start_timestamp=1766913600000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns deposits you can match against collateral arriving in the account. + + + ```json theme={null} + { + "data": [ + { + "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", + "asset": "pUSD", + "amount": "100000000", + "status": "confirmed", + "from": "0x1234567890abcdef1234567890abcdef12345678", + "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", + "confirmations": 12, + "required_confirmations": 12, + "created_timestamp": 1767000010000, + "confirmed_timestamp": 1767000030000 + } + ], + "more": false + } + ``` + + + + +### Withdrawals + +Use withdrawals to reconcile collateral leaving the Perps account. + + + + ```ts theme={null} + const withdrawals = session.listWithdrawals(); + + for await (const page of withdrawals) { + // page.items: PerpsWithdrawal[] + } + ``` + + Each page returns withdrawals you can match against collateral leaving the account. + + + ```json theme={null} + [ + { + "withdrawalId": 1234567891, + "asset": "pUSD", + "amount": "50000000", + "fee": "1.5", + "status": "confirmed", + "to": "0x1234567890abcdef1234567890abcdef12345678", + "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", + "confirmations": 12, + "requiredConfirmations": 12, + "createdTimestamp": 1767000010000, + "confirmedTimestamp": 1767000030000 + } + ] + ``` + + + + + ```python theme={null} + withdrawals = session.list_withdrawals() + + async for page in withdrawals: + # page.items: tuple[PerpsWithdrawal, ...] + pass + ``` + + Each page returns withdrawals you can match against collateral leaving the account. + + + ```json theme={null} + [ + { + "withdrawal_id": 1234567891, + "asset": "pUSD", + "amount": "50000000", + "fee": "1.5", + "status": "confirmed", + "to": "0x1234567890abcdef1234567890abcdef12345678", + "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", + "confirmations": 12, + "required_confirmations": 12, + "created_at": 1767000010000, + "confirmed_at": 1767000030000 + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "start_timestamp=1766913600000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns withdrawals you can match against collateral leaving the account. + + + ```json theme={null} + { + "data": [ + { + "withdrawal_id": 1234567891, + "asset": "pUSD", + "amount": "50000000", + "fee": "1.5", + "status": "confirmed", + "to": "0x1234567890abcdef1234567890abcdef12345678", + "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", + "confirmations": 12, + "required_confirmations": 12, + "created_timestamp": 1767000010000, + "confirmed_timestamp": 1767000030000 + } + ], + "more": false + } + ``` + + + + +## Track Equity and PnL + +Use equity and PnL history to explain how the account's value changed over time. + +### Equity + +Use equity history to chart account value over time. + + + + ```ts theme={null} + const equity = session.listEquityHistory({ + interval: "1h", + start: Date.now() - 7 * 24 * 60 * 60 * 1000, + end: Date.now(), + }); + + for await (const page of equity) { + // page.items: PerpsEquityPoint[] + } + ``` + + Each page returns points you can plot as account equity over time. + + + ```json theme={null} + [ + { + "timestamp": 1767000000000, + "equity": "1000" + } + ] + ``` + + + + + ```python theme={null} + from datetime import datetime, timedelta, timezone + + end = datetime.now(timezone.utc) + start = end - timedelta(days=7) + + equity = session.list_equity_history( + interval="1h", + start=start, + end=end, + ) + + async for page in equity: + # page.items: tuple[PerpsEquityPoint, ...] + pass + ``` + + Each page returns points you can plot as account equity over time. + + + ```json theme={null} + [ + { + "timestamp": 1767000000000, + "equity": "1000" + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/equity" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "interval=1h" \ + --data-urlencode "start_timestamp=1766395200000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns points you can plot as account equity over time. + + + ```json theme={null} + { + "data": [[1767000000000, "1000"]], + "more": false + } + ``` + + + + +### PnL + +Use PnL history to chart account profit and loss over the same interval. + + + + ```ts theme={null} + const pnl = session.listPnlHistory({ + interval: "1h", + start: Date.now() - 7 * 24 * 60 * 60 * 1000, + end: Date.now(), + }); + + for await (const page of pnl) { + // page.items: PerpsPnlPoint[] + } + ``` + + Each page returns points you can plot as account PnL over time. + + + ```json theme={null} + [ + { + "timestamp": 1767000000000, + "pnl": "12.5" + } + ] + ``` + + + + + ```python theme={null} + from datetime import datetime, timedelta, timezone + + end = datetime.now(timezone.utc) + start = end - timedelta(days=7) + + pnl = session.list_pnl_history( + interval="1h", + start=start, + end=end, + ) + + async for page in pnl: + # page.items: tuple[PerpsPnlPoint, ...] + pass + ``` + + Each page returns points you can plot as account PnL over time. + + + ```json theme={null} + [ + { + "timestamp": 1767000000000, + "pnl": "12.5" + } + ] + ``` + + + + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/pnl" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "interval=1h" \ + --data-urlencode "start_timestamp=1766395200000" \ + --data-urlencode "end_timestamp=1767000000000" + ``` + + Use the response's `more` field to continue fetching older or newer records. + + Each page returns points you can plot as account PnL over time. + + + ```json theme={null} + { + "data": [[1767000000000, "12.5"]], + "more": false + } + ``` + + + diff --git a/docs/perps/authenticated-sessions.md b/docs/perps/authenticated-sessions.md new file mode 100644 index 0000000..8a102d2 --- /dev/null +++ b/docs/perps/authenticated-sessions.md @@ -0,0 +1,653 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Authenticated Sessions + +> Set up authenticated access for Perps trading and account data + +An authenticated session is a two-way authenticated communication channel with +the Perps system that allows your app to place orders, read private Perps account +data, and receive private real-time updates. + +## Set Up Perps Access + + + + + + Create a `SecureClient` for the Polymarket wallet that owns the Perps account, + using the signer that controls it. + + ```ts theme={null} + import { createSecureClient } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + wallet: process.env.POLYMARKET_WALLET_ADDRESS!, + signer: privateKey(process.env.PRIVATE_KEY!), + }); + ``` + + + This example uses Viem for wallet signing. See the [TypeScript tooling + guide](/dev-tooling/typescript#wallet-integrations) for other wallet library + integrations. + + + + + Open a Perps session. By default, delegated Perps credentials expire after one + week. + + ```ts theme={null} + const session = await client.openPerpsSession(); + ``` + + You can also set the session lifetime and label explicitly. `expiresIn` is + measured in milliseconds. + + ```ts theme={null} + const session = await client.openPerpsSession({ + expiresIn: 7 * 24 * 60 * 60 * 1000, + label: "trading-app", + }); + ``` + + + + + + + + Create an `AsyncSecureClient` for the Polymarket wallet that owns the Perps + account, using the signer that controls it. + + ```python theme={null} + import os + + from polymarket import AsyncSecureClient + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], + ) + ``` + + + + Open a Perps session. By default, delegated Perps credentials expire after one + week. + + ```python theme={null} + session = await client.open_perps_session() + ``` + + You can also set the session lifetime and label explicitly. `expires_in` is a + `timedelta`. + + ```python theme={null} + from datetime import timedelta + + session = await client.open_perps_session( + expires_in=timedelta(days=7), + label="trading-app", + ) + ``` + + + + + + Start by registering new proxy credentials for an existing Polymarket account. + If you do not have one yet, create an account at + [polymarket.com](https://polymarket.com) first. + + + + Generate a fresh keypair for the proxy signer. Perps uses this key to authorize + trading operations on behalf of the Polymarket account signer, without requiring + the account signer to sign every order. + + Use any secure EVM key-generation flow. + + + ```bash Foundry theme={null} + $ cast wallet new + Successfully created new keypair. + Address: + Private key: + ``` + + ```ts Viem theme={null} + import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; + + const privateKey = generatePrivateKey(); + const { address } = privateKeyToAccount(privateKey); + ``` + + + Store the private key securely. It will be used to sign Perps trading operations + for the Polymarket account signer. + + + + Create an EIP-712 `CreateProxy` payload. + + ```json theme={null} + { + "domain": { + "name": "Polymarket", + "version": "1", + "chainId": 137 + }, + "primaryType": "CreateProxy", + "types": { + "CreateProxy": [ + { "name": "addr", "type": "address" }, + { "name": "exp", "type": "uint64" }, + { "name": "salt", "type": "uint64" }, + { "name": "ts", "type": "uint64" } + ] + }, + "message": { + "addr": "", + "exp": 1767225600000, + "salt": 123456789, + "ts": 1767000000000 + } + } + ``` + + Use these values consistently in the typed data and request body. + + | Field | Value | + | ------ | ----------------------------------------------------------------------- | + | `addr` | `` from the previous step. | + | `exp` | Unix timestamp in milliseconds when the proxy signer stops being valid. | + | `ts` | Current Unix timestamp in milliseconds. | + | `salt` | Random integer generated for this signed request. | + + + + Sign the `CreateProxy` typed data with the signer for the Polymarket account. + + ```ts Viem theme={null} + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(""); + + const signature = await account.signTypedData({ + domain: { + name: "Polymarket", + version: "1", + chainId: 137, + }, + primaryType: "CreateProxy", + types: { + CreateProxy: [ + { name: "addr", type: "address" }, + { name: "exp", type: "uint64" }, + { name: "salt", type: "uint64" }, + { name: "ts", type: "uint64" }, + ], + }, + message: { + addr: "", + exp: 1767225600000, + salt: 123456789, + ts: 1767000000000, + }, + }); + ``` + + + + Authorize the generated proxy signer for your Perps account. + + ```bash theme={null} + curl -X POST "https://api.perpetuals.polymarket.com/v1/account/proxy" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "createProxy", + "args": { + "owner": "", + "proxy": "", + "expiry": 1767225600000 + } + }, + "sig": "", + "salt": 123456789, + "ts": 1767000000000, + "label": "trading-app" + }' + ``` + + Map the request fields to the values from the previous steps. + + * `owner` is the signer address for the Polymarket account. + * `proxy` is `` from the first step. + * `sig` is `` from the previous step. + * `salt` and `ts` are the same values used in the typed data from step 2. + * `label` is an identifier for this proxy credential instance. + + The response contains the proxy secret. + + ```json theme={null} + { + "secret": "" + } + ``` + + Store the proxy private key, proxy address, proxy secret, and expiry securely. + + + + + +## Session Lifecycle + +Open an authenticated session to start trading, read private Perps account data, +and receive private real-time updates. + + + + + + After opening a Perps session, iterate over it to receive private real-time + updates. + + ```ts theme={null} + const session = await client.openPerpsSession(); + + for await (const event of session) { + switch (event.type) { + case "order": + // Update local order state. + break; + + case "fill": + // Update position, PnL, or execution history. + break; + + case "portfolio": + // Refresh margin, equity, and position views. + break; + } + } + ``` + + This example handles a few common session events. `order` and `fill` are the + core trading updates, while `portfolio` provides periodic account-level snapshots + for margin, equity, positions, and withdrawable balance. + + See [Reconcile Trade State](/perps/trading#reconcile-trade-state) for how to use + these events to keep local trading state in sync. + + + + You can close the session at any time by calling `session.close()`. Closing a + session releases local resources; stored credentials can still be resumed until + they expire. + + ```ts theme={null} + for await (const event of session) { + if (shouldCloseSession) { + await session.close(); + break; + } + + // … + } + ``` + + + + + + + + After opening a Perps session, iterate over it to receive private real-time + updates. + + ```python theme={null} + session = await client.open_perps_session() + + async for event in session: + if event.type == "order": + # Update local order state. + pass + elif event.type == "fill": + # Update position, PnL, or execution history. + pass + elif event.type == "portfolio": + # Refresh margin, equity, and position views. + pass + ``` + + This example handles a few common session events. `order` and `fill` are the + core trading updates, while `portfolio` provides periodic account-level snapshots + for margin, equity, positions, and withdrawable balance. + + See [Reconcile Trade State](/perps/trading#reconcile-trade-state) for how to use + these events to keep local trading state in sync. + + + + You can close the session at any time by calling `session.close()`. Closing a + session releases local resources; stored credentials can still be resumed until + they expire. + + ```python theme={null} + async for event in session: + if should_close_session: + await session.close() + break + + # … + ``` + + + + + + + + Connect to the Perps WebSocket production URL. + + ```text theme={null} + wss://ws.perpetuals.polymarket.com/v1/ws + ``` + + After the connection opens, send an authentication frame with the proxy address + and proxy secret. + + ```json theme={null} + { + "id": 1, + "req": "post", + "op": { + "type": "auth", + "args": { + "proxy": "", + "secret": "" + } + } + } + ``` + + Check the authentication response before subscribing to private channels. + + + ```json Success theme={null} + { + "id": 1, + "data": { + "status": "ok" + } + } + ``` + + ```json Failure theme={null} + { + "id": 1, + "data": { + "status": "err", + "error": "" + } + } + ``` + + + + + Authenticated WebSocket connections receive private session update frames. These + examples show a few common events: `orders` and `fills` for trading activity, + and `portfolio` for periodic account-level snapshots. + + + ```json Order theme={null} + { + "ch": "orders", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "oid": 1234567890, + "iid": 1, + "buy": true, + "p": "65000.00", + "qty": "0.01", + "tif": "gtc", + "po": false, + "status": "open", + "rest": "0.01", + "fill": "0", + "cts": 1767225600000, + "uts": 1767225600000 + } + } + ``` + + ```json Fill theme={null} + { + "ch": "fills", + "ts": 1767225600000, + "sq": 1234567891, + "data": { + "tid": 987654321, + "oid": 1234567890, + "iid": 1, + "side": "long", + "p": "65000.00", + "qty": "0.01", + "taker": true, + "fee": "0.26", + "fea": "pUSD", + "psz": "0", + "pep": "0", + "pnl": "0", + "liq": false, + "ts": 1767225600000 + } + } + ``` + + ```json Portfolio theme={null} + { + "ch": "portfolio", + "ts": 1767225600000, + "sq": 1234567892, + "data": { + "positions": [], + "margin": { + "total_account_value": "10.00", + "total_initial_margin": "0", + "total_maintenance_margin": "0", + "total_position_value": "0" + }, + "withdrawable": "10.00", + "in_liquidation": false, + "timestamp": 1767225600000 + } + } + ``` + + + These are examples of common session events, not the full event list. + + + + Send an application-level ping from the client about every 25 seconds. + + ```json theme={null} + { + "id": 0, + "req": "post", + "op": { + "type": "ping" + } + } + ``` + + The server responds with a pong payload. + + ```json theme={null} + { + "id": 0, + "data": { + "status": "ok", + "ts": 1767225600000, + "sq": 1234567890 + } + } + ``` + + Treat the connection as stale if no messages arrive for about 65 seconds. + + + + Close the WebSocket connection when the current workflow is finished. Closing the + connection does not revoke the proxy credential. + + + + + +## Resume a Session + +Resume a session when stored credentials are still valid and a Perps workflow +needs to continue in a new runtime context. + + + + Read `session.credentials` after opening a session and store the object in secure + credential storage. + + ```ts theme={null} + const credentials = session.credentials; + // credentials: PerpsCredentials + ``` + + where `PerpsCredentials` is: + + + ```ts Type theme={null} + type PerpsCredentials = { + proxy: EvmAddress; + privateKey: PrivateKey; + secret: string; + expiresAt: number; + }; + ``` + + ```json Example theme={null} + { + "proxy": "0x1111111111111111111111111111111111111111", + "privateKey": "0x2222222222222222222222222222222222222222222222222222222222222222", + "secret": "", + "expiresAt": 1766725200000 + } + ``` + + + Pass stored credentials back to `openPerpsSession()` while they are still valid. + The SDK validates them and resumes the session. + + ```ts theme={null} + const session = await client.openPerpsSession({ + credentials, + }); + // session: PerpsSession + ``` + + + + Read `session.credentials` after opening a session and store the object in secure + credential storage. + + ```python theme={null} + credentials = session.credentials + # credentials: PerpsCredentials + ``` + + where `PerpsCredentials` is: + + + ```python Type theme={null} + from polymarket import PerpsCredentials + + # credentials: PerpsCredentials + ``` + + ```json Example theme={null} + { + "proxy": "0x1111111111111111111111111111111111111111", + "private_key": "0x2222222222222222222222222222222222222222222222222222222222222222", + "secret": "", + "expires_at": "2026-01-25T18:20:00Z" + } + ``` + + + For JSON-backed storage, serialize the model and keep the result encrypted. + + ```python theme={null} + stored_credentials = credentials.model_dump(mode="json") + ``` + + Pass stored credentials back to `open_perps_session()` while they are still + valid. The SDK validates them and resumes the session. + + ```python theme={null} + from polymarket import PerpsCredentials + + credentials = PerpsCredentials.model_validate(stored_credentials) + + session = await client.open_perps_session(credentials=credentials) + # session: PerpsSession + ``` + + + + Resume an API session by reusing stored proxy credentials while they are still + valid. + + Store the credential material from the setup flow in secure credential storage. + + | Field | Use it to | + | --------------------- | ----------------------------------------------- | + | `` | Identify the proxy credential. | + | `` | Sign Perps trading operations. | + | `` | Authenticate private REST and real-time access. | + | `expiry` | Know when to register a new proxy credential. | + + For private REST reads, pass the proxy address and proxy secret as headers. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + For a new WebSocket connection, send the same authentication frame used when the + session was opened. + + ```json theme={null} + { + "id": 1, + "req": "post", + "op": { + "type": "auth", + "args": { + "proxy": "", + "secret": "" + } + } + } + ``` + + If the credential has expired, register a new proxy credential before resuming + private workflows. + + diff --git a/docs/perps/changelog.md b/docs/perps/changelog.md new file mode 100644 index 0000000..335a586 --- /dev/null +++ b/docs/perps/changelog.md @@ -0,0 +1,53 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Changelog + +> Recent changes to the Polymarket Perps API and platform + +Notable changes to the Polymarket Perps API. + + + Cancel responses now include `oid` and `coid` fields. + + + + Added a 20ms taker delay for orders that immediately match on entry. + + + + Added the reduce-only field to order submission and order updates. + + + +
    +
  • + Added PATCH /v1/trade/auto-cancel to arm or clear a dead + man's switch that cancels all open orders at a specified time. +
  • + +
  • + Added GET /v1/account/auto-cancel to check the current + auto-cancel status, trigger count, and daily reset time. +
  • + +
  • Auto-cancel is limited to 10 triggers per UTC day per account.
  • + +
  • + Added updateLeverage and autoCancel WebSocket + post messages. +
  • + +
  • + portfolio and balances WebSocket channels no + longer push updates on every order or fill, only periodically. +
  • + +
  • + Rate limit error messages now distinguish between{" "} + ip\_rate\_limited, action\_rate\_limited, and{" "} + message\_rate\_limited. +
  • +
+
diff --git a/docs/perps/concepts.md b/docs/perps/concepts.md new file mode 100644 index 0000000..f349f25 --- /dev/null +++ b/docs/perps/concepts.md @@ -0,0 +1,186 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Concepts + +> Core concepts for Polymarket perpetual markets + +Perps trading depends on how order fills create or change positions, how prices +affect account equity, and how collateral supports trading risk. The concepts +below describe the moving parts that determine what an account can trade and when +a position is at risk. + +## Instruments + +An instrument identifies a Perps market: a tradable perpetual contract that +tracks an underlying asset such as the S\&P 500 Index, gold, or bitcoin. Each +instrument carries the information needed to identify the market and the rules +for trading it. + +| Attribute | Meaning | +| ------------------- | ---------------------------------------------------------------------------------------------- | +| ID | The instrument identifier used in market data and orders | +| Symbol | A short market label, such as `SP500-USD`, `GOLD-USD`, or `BTC-USD` | +| Underlying asset | The asset or index the market tracks, such as the S\&P 500 Index, gold, or bitcoin | +| Collateral asset | The asset used to fund Perps accounts and support open positions. Polymarket Perps use pUSD. | +| Trading constraints | Market-specific rules such as price precision, quantity precision, order limits, and leverage. | + +## Perps Accounts + +A Perps account is tied to a signer account. The signer account controls private +actions such as trading and withdrawals. + +The Perps account holds the state created by those actions: collateral, open +positions, orders, fills, and history. Later sections explain how those pieces +change as orders execute, prices move, and funding payments settle. + +Perps accounts are funded through onchain collateral deposits. + + + If you're building on Perps, delegated credentials let your app act for the + Perps account without using the owner key for every private action. See + [Authenticated Sessions](/perps/authenticated-sessions). + + +## Prices + +A Perps market has two broad categories of prices: execution prices and +calculated prices. Execution prices come from trades in the order book. +Calculated prices are produced by Polymarket and used for reference, margin, and +liquidation checks. + +This separation matters because one small or isolated trade should not be able to +change an account's risk state or trigger liquidation by itself. + +| Price | Category | Meaning | Used for | +| ------------ | ---------------- | ---------------------------------------------------------- | --------------------------------------------------- | +| Traded price | Execution price | The price of an executed order book fill | Trade history and execution records | +| Index price | Calculated price | Polymarket's estimate of the underlying asset's fair value | Reference price and price anchoring | +| Mark price | Calculated price | The price used to value positions | Unrealized PnL, margin checks, and liquidation risk | + +Calculated prices are computed from external price feeds. The feed set can +change with market sessions, such as regular hours, overnight trading, and +weekends, while funding, margin, and liquidation rules stay the same around the +clock. See [Market Sessions](/perps/learn-about-trading/market-sessions). + +## Orders And Fills + +Orders are requests to trade in a Perps market. They can execute immediately or +rest in the order book until another order matches them. + +The order book is the list of resting buy and sell orders for a market. A fill is +an executed match between orders in that book. + + + Fills update Perps account state; they are not separate onchain transactions. + + +```mermaid theme={null} +flowchart LR + A[Submit order] --> B{Matches now?} + B -->|Yes| C[Fill updates account] + B -->|No| D[Order rests in book] + D --> E[Later fill or cancel] + E --> C +``` + +Limit orders are useful when the trade needs an explicit price. If the order does +not fill immediately, it can rest in the book where it can be inspected, +modified, or cancelled. + +## Trading Positions + +Once an order fills, it changes the account's position in that market. A position +is what the account currently holds: long exposure, short exposure, or no open +exposure. + +| Position | Benefits when | Loses when | +| -------- | ----------------------- | ----------------------- | +| Long | The tracked asset rises | The tracked asset falls | +| Short | The tracked asset falls | The tracked asset rises | + +A fill that adds to the account's current side increases exposure. A fill against +the current side reduces exposure. When the position size reaches zero, the +position is closed. If losses exceed what the account can support, the position +can also be liquidated. + +## Margin And Liquidation + +Perps accounts use collateral to support open positions. Margin checks compare +the account's current value against the collateral required to open, increase, or +maintain those positions. + +Margin checks use these terms: + +| Term | Meaning | +| ------------------ | --------------------------------------------------------------------------------------------- | +| Collateral | Funds available to support positions and withdrawals | +| Account equity | The current value of the account after open-position gains, losses, fees, and funding effects | +| Initial margin | Collateral required to open or increase a position | +| Maintenance margin | Minimum collateral required to keep a position open | +| Liquidation | Forced position closing when account equity falls below maintenance margin | + +Account equity moves as the mark price changes and as account debits or credits +settle. It can move up or down even before a position is closed. + + + If you're building on Perps, monitor account equity to decide when to reduce + exposure, add collateral, or stop placing new orders. + + +At a high level, account equity is the account's collateral plus open-position +gains or losses, minus amounts owed. + +```text theme={null} +Account equity = collateral + unrealized PnL - amounts owed +``` + +If account equity falls below maintenance margin, the account is at risk of +liquidation. Liquidation closes exposure to prevent losses from exceeding the +account's collateral. + +## Funding Payments + +**Funding payments** help keep a Perps market close to its index price. They are +not order-book trades; they are account debits or credits applied to open +positions over time. + + + Funding payments are different from collateral deposits. Deposits add + collateral to a Perps account; funding payments are debits or credits between + long and short positions. + + +| Market state | Typical payment direction | +| ------------------------------- | ------------------------- | +| Market trades above index price | Longs pay shorts | +| Market trades below index price | Shorts pay longs | + +A funding payment credited to the account increases account equity. A funding +payment owed by the account reduces account equity. + +The **funding rate** is the rate used to calculate these payments. Public market +data shows funding rates over time, while private account history shows the +funding payments applied to an account. + +## Realtime Account State + +If you're building on Perps, realtime account state helps your integration keep a +local view in sync. + +Integrations often keep a local view of account state so they can react quickly +to fills, risk changes, and collateral movements. Realtime updates help keep that +local view in sync. + +| State change | Why it matters | +| --------------------- | -------------------------------------------------------------- | +| Order update | A resting order opened, changed, filled, or cancelled | +| Fill | A trade executed and changed the account's position or balance | +| Portfolio update | Account equity, margin, or position state changed | +| Funding payment | A funding debit or credit changed account state | +| Deposit or withdrawal | Collateral moved into or out of the account | + +Realtime streams can reconnect or detect gaps. When that happens, the integration +should resync by refetching the account state it depends on before trusting the +local view again. diff --git a/docs/perps/faq.md b/docs/perps/faq.md new file mode 100644 index 0000000..3cd3a60 --- /dev/null +++ b/docs/perps/faq.md @@ -0,0 +1,261 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# FAQ + +> Common questions about Polymarket Perps trading, pricing, margin, liquidation, fees, and integration + +Common questions about Polymarket Perps. + +## General + + + + Polymarket Perps is a perpetual futures exchange offering continuous exposure to equities, indices, commodities, and other underlyings. Positions have no expiry. A funding rate keeps the contract price tethered to the underlying's spot price over time. + + + + Fetch the current product list, symbols, underlyings, reference feeds, and + leverage settings from [`GET + /v1/info/instruments`](/perps/market-data#fetch-instruments). + + + + Hybrid. Order matching, margin, and funding run off-chain for low latency. + Deposits and withdrawals settle on Polygon, and the exchange periodically + posts state-root commitments on-chain so off-chain activity stays verifiable. + + + + Yes. The order book, matching, funding, margin checks, and liquidations all + run continuously. What changes outside of regular hours is the set of external + feeds used to compute Index and Mark. + + + + No. Perpetual futures have no expiration date. A Perps position stays open + until you close it or it is force-closed by liquidation. + + + + Yes. "Perps" is trader shorthand for "perpetual futures." Both refer to the + same derivative contract: a futures-style instrument with no expiry, anchored + to the underlying's spot price through periodic funding. + + + + Polymarket's prediction markets settle Yes or No shares at $1 or $0 based on a discrete event outcome. Perps are continuous: there is no event resolution and no $0/$1 settlement. Instead you take a long or short position whose value moves with the underlying asset's price, subject to funding payments and margin requirements like any perpetual futures contract. + + + +## Trading and Orders + + + + Limit and market-style orders are supported with `gtc`, `ioc`, and `fok` time-in-force values. GTC orders can be tagged post-only, which rejects the order if it would take liquidity. Closing orders can be tagged reduce-only, which prevents the order from increasing exposure. See [Configure Order Behavior](/perps/trading#configure-order-behavior) and [Close a Position](/perps/trading#close-a-position). + + + + Pre-trade margin uses the worst-case position size from your existing exposure plus all resting orders on each side, not just the current position. + + ```text theme={null} + WorstCaseSize = max(|Position + OpenBuys|, |Position - OpenSells|) + ``` + + If `Equity < IM_required` for that worst case, the order is rejected even though current equity is comfortable. + + + + Self-trade prevention is on by default for every order and runs in CancelMaker mode: when a taker would match against a resting order on the same account, the conflicting resting maker is canceled and the taker continues matching against other makers. It is not an API setting. There is no way to turn it off or change its mode. + + + +## Pricing, Mark, Index, and Funding + + + + * Index Price is the protocol's estimate of the underlying's fair value, aggregated from external oracle feeds. + * Mark Price is the price the system uses for margin, PnL, liquidation, and funding. + * Last trade price is the price of the most recent fill on the local book. It is not used for margining. + + See [Prices](/perps/concepts#prices). + + + + Each Mark candidate degrades gracefully to the Index. If the order book mid is + missing, the candidate falls back to Index. If there are no recent trades or + quotes, the candidate falls back to Index. If external mark feeds are + unavailable, the candidate falls back to Index. In the worst case, all + candidates converge to Index and Mark tracks Index directly. + + + + A premium index is sampled every 5 seconds by walking the book for 1,000 + quote-asset notional on each side. Samples are averaged over a 1-hour charge + window, run through an 8-hour formula with a fixed interest leg and clamp, + divided by 8, and capped at +/-4% per hour. Settlement happens once per + window. Longs pay shorts when the rate is positive, and shorts pay longs when + negative. The protocol takes no cut. + + + + Yes. A rolling 5-second premium sample and its implied 8-hour rate are published continuously through public market data. You can also read funding history with [`GET /v1/info/funding`](/perps/market-data#list-funding-history). + + + +## Margin and Leverage + + + + * Isolated margin funds each position with a dedicated margin allocation. Liquidation only closes the affected position. + * Cross margin shares account collateral across all cross positions. Unrealized PnL on one position can offset margin on another, but a liquidation evaluates and can unwind the whole cross account. + + The web app opens new positions in isolated mode by default. Cross is opt-in through the API using leverage configuration. See [Update Leverage](/perps/trading#update-leverage). + + + + Margin requirements scale with position notional through tiers. Larger + positions need proportionally more margin to limit system-wide risk and reduce + liquidation cascades. Margin is calculated incrementally across tiers, + equivalent to summing bracket by bracket. Fetch live tier values from [`GET + /v1/info/instruments`](/perps/market-data#fetch-instruments). + + + + By design, maintenance margin rate is half of the maximum leverage requirement + for the tier. A position is liquidated only after losing roughly half of the + margin posted to open it, which gives traders a buffer between entering a + position and being force-closed. + + + + Three states are evaluated continuously. + + | State | Condition | Behavior | + | ----------- | ------------------- | ------------------------------------------------- | + | Healthy | `Equity >= IM` | Normal trading | + | Margin call | `MM <= Equity < IM` | Reduce-only: close exposure or deposit collateral | + | Liquidation | `Equity < MM` | System closes the position | + + A deposit during margin call instantly increases equity and can restore healthy status. + + + + Yes, as long as `Equity_after >= IM_required` after the withdrawal. You cannot withdraw yourself into a margin call. + + + +## Liquidation + + + + Liquidation occurs when account equity falls below maintenance margin. Cross and isolated positions are checked independently: each isolated position has its own equity and maintenance margin, while cross uses the account's combined equity and combined maintenance margin. See [Margin and Liquidation](/perps/concepts#margin-and-liquidation). + + + + For cross positions, the liquidation price depends on available balance: + everything in the cross account that is not this position's own equity. Mark + moves on other cross positions, size changes, or collateral changes can all + shift the liquidation price for every cross position simultaneously. + + + + The affected scope is flagged and new orders on it are blocked. Cross blocks + the whole account. Isolated blocks just that instrument. The system closes + positions with reduce-only IOC orders, rate-limited per account, re-evaluating + margin between fills. Cross liquidation closes one position at a time across + cycles. If equity recovers above the recovery initial margin, the flag clears. + + + + When equity falls below two-thirds of maintenance margin, order-book + liquidation is unlikely to recover value, so the system absorbs the position + directly into the insurance-fund account along with its margin. For cross + backstop, the system absorbs all cross positions plus quote balance. + + + + Yes. While flagged, every fill pays an additional liquidation fee rate on top of the maker or taker rate. + + ```text theme={null} + FillFee = Notional * (MakerOrTakerRate + LiquidationFeeRate) + ``` + + Fetch the live rate per instrument from [`GET /v1/info/instruments`](/perps/market-data#fetch-instruments). + + + +## Fees + + + + Fees are tiered by trailing 30-day trading volume. New accounts start at the \$0 tier and move up as their volume crosses each threshold. + + | 30-Day Volume ≥ | Taker | Maker | + | --------------- | ------- | -------- | + | \$0 | 0.0400% | 0.0125% | + | \$1M | 0.0370% | 0.0100% | + | \$5M | 0.0350% | 0.0080% | + | \$25M | 0.0300% | 0.0050% | + | \$100M | 0.0270% | 0.0020% | + | \$500M | 0.0250% | 0.0000% | + | \$1B | 0.0200% | -0.0050% | + + Fees are calculated per fill as `abs(Price * Quantity) * Rate`, denominated in the instrument's quote asset (pUSD). Only the top tier earns a maker rebate; lower tiers pay a positive maker fee. See [Fees](/perps/learn-about-trading/fees) and [Trading Fees](/perps/trading#trading-fees). + + + +## API and Integration + + + + Your main wallet signs the one-time create-proxy request and never trades directly. The returned proxy address and secret are what you use day to day: the proxy private key signs trade requests, and the `(proxy, secret)` pair authenticates private REST and WebSocket reads. This isolates the trading key from the wallet that holds funds. See [Set Up Authentication](/perps/authenticated-sessions#set-up-authentication). + + + + Your account is keyed by your EOA base address, the externally-owned account + that signs `createProxy`, not a Safe smart-contract wallet address. Even if + you use a Safe wallet elsewhere on Polymarket, your Perps balances, positions, + and history are all tracked against the underlying EOA. Use that EOA when + looking up your account or referencing it in support requests. + + + + * Signed requests with `sig`, `salt`, and `ts`: `POST /account/key`, all `/trade/*` actions, and `PATCH /trade/leverage`. The signer is the main address for `createProxy` and the proxy address for everything else. + * Header credentials with `POLYMARKET-PROXY` and `POLYMARKET-SECRET`: private `/account/*` reads. + * WebSocket authentication: send a single `auth` message after connecting, then subscribe to private channels. + + See [Authenticated Sessions](/perps/authenticated-sessions). + + + + Each signed request must include a fresh `ts` request timestamp in + milliseconds and `salt`. Reused or stale values are rejected. Sync against + `GET /v1/info/time` and do not sign requests far in the past or future. The + optional `expa` field caps the validity window. + + + + Deposits and withdrawals are the only operations that move assets in or out of the exchange. Both settle on Polygon. Deposits credit equity as soon as the engine sees them. Withdrawals are signed off-chain and require `Equity_after >= IM_required`. See [Fund Your Account](/perps/fund-your-account). + + + + Yes. Order placement is not permitted from the United States, Canada, Cuba, Iran, North Korea, Syria, Crimea, Donetsk, or Luhansk. Builders are responsible for verifying user location before submitting orders. + + + +## Sessions + + + + Sessions affect which set of external feeds is used to compute Index Price and Mark Price. They do not change funding, margin, leverage tiers, order matching, or liquidation triggers. Those run identically around the clock. + + + + * Disrupted means external feeds are unavailable or failing sanity checks. The system falls back to whatever feed set is still healthy. + * Halted means the underlying itself has a trading halt or corporate-action freeze. + + Both are categorizations of feed-source health and only affect Index and Mark sourcing. The perp continues to match orders. + + diff --git a/docs/perps/fund-your-account.md b/docs/perps/fund-your-account.md new file mode 100644 index 0000000..619876d --- /dev/null +++ b/docs/perps/fund-your-account.md @@ -0,0 +1,740 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fund Your Account + +> Deposit and withdraw pUSD collateral for Perps trading + +Fund the Perps account with pUSD before placing orders. Deposits move pUSD from +the user's Polymarket wallet into the Perps account. Withdrawals move available +pUSD back to the authenticated wallet. + +## Deposit Collateral + +Deposit pUSD when the account needs collateral for opening or maintaining Perps +positions. + + + + + + Create a `SecureClient` for the wallet that will fund the Perps account. If you + already have a Polymarket wallet, pass it as `wallet` and include a Relayer API + key so the SDK can submit gasless transactions. If you are creating a wallet + programmatically, use a Builder API key so the SDK can create the Deposit Wallet + for that signer. + + + ```ts Existing Account theme={null} + import { createSecureClient, relayerApiKey } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + wallet: process.env.POLYMARKET_WALLET_ADDRESS!, + signer: privateKey(process.env.PRIVATE_KEY!), + apiKey: relayerApiKey({ + key: process.env.RELAYER_API_KEY!, + address: process.env.RELAYER_API_KEY_ADDRESS!, + }), + }); + ``` + + ```ts New Programmatic Wallet theme={null} + import { createSecureClient } from "@polymarket/client"; + import { builderApiKey } from "@polymarket/client/node"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + signer: privateKey(process.env.PRIVATE_KEY!), + apiKey: builderApiKey({ + key: process.env.BUILDER_API_KEY!, + secret: process.env.BUILDER_SECRET!, + passphrase: process.env.BUILDER_PASSPHRASE!, + }), + }); + ``` + + + + + Set up the approvals required for Perps collateral deposits. The SDK skips work + that is already complete. + + ```ts theme={null} + await client.setupTradingApprovals(); + ``` + + + + Deposit pUSD from the user's Polymarket wallet into the Perps account. Make sure + the wallet has pUSD before depositing. The minimum Perps deposit is 10 pUSD. + Amounts use raw pUSD base units, so 10 pUSD is `10_000_000n`. + + ```ts theme={null} + const deposit = await client.depositToPerps({ + amount: 10_000_000n, + }); + + const receipt = await deposit.wait(); + // receipt.transactionHash: TxHash + ``` + + `deposit.wait()` confirms that the chain transaction settled. Perps may take a + moment to credit the account after that. + + + + Open a Perps session and read account state after the deposit settles. + + ```ts theme={null} + const session = await client.openPerpsSession(); + + try { + const portfolio = await session.fetchPortfolio(); + const deposits = await session.listDeposits().firstPage(); + } finally { + await session.close(); + } + ``` + + Use `portfolio.withdrawable` to check available collateral and `deposits.items` + to reconcile deposit history. + + + + + + + + Create an `AsyncSecureClient` for the wallet that will fund the Perps account. + If you already have a Polymarket wallet, pass it as `wallet` and include a + Relayer API key so the SDK can submit gasless transactions. If you are creating a + wallet programmatically, use a Builder API key so the SDK can create the Deposit + Wallet for that signer. + + + ```python Existing Account theme={null} + import os + + from polymarket import AsyncSecureClient, RelayerApiKey + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], + api_key=RelayerApiKey( + key=os.environ["RELAYER_API_KEY"], + address=os.environ["RELAYER_API_KEY_ADDRESS"], + ), + ) + ``` + + ```python New Programmatic Wallet theme={null} + import os + + from polymarket import AsyncSecureClient, BuilderApiKey + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + api_key=BuilderApiKey( + key=os.environ["BUILDER_API_KEY"], + secret=os.environ["BUILDER_SECRET"], + passphrase=os.environ["BUILDER_PASSPHRASE"], + ), + ) + ``` + + + + + Set up the approvals required for Perps collateral deposits. The SDK skips work + that is already complete. + + ```python theme={null} + await client.setup_trading_approvals() + ``` + + + + Deposit pUSD from the user's Polymarket wallet into the Perps account. Make sure + the wallet has pUSD before depositing. The minimum Perps deposit is 10 pUSD. + Amounts use raw pUSD base units, so 10 pUSD is `10_000_000`. + + ```python theme={null} + deposit = await client.deposit_to_perps(amount=10_000_000) + + receipt = await deposit.wait() + # receipt.transaction_hash: TransactionHash + ``` + + `deposit.wait()` confirms that the chain transaction settled. Perps may take a + moment to credit the account after that. + + + + Open a Perps session and read account state after the deposit settles. + + ```python theme={null} + session = await client.open_perps_session() + + try: + portfolio = await session.fetch_portfolio() + deposits = await session.list_deposits().first_page() + finally: + await session.close() + ``` + + Use `portfolio.withdrawable` to check available collateral and `deposits.items` + to reconcile deposit history. + + + + + + + + Before depositing, the Polymarket wallet must approve the Perps deposit contract + to spend pUSD. If the approval is already in place, skip the approval call. + + ```solidity Approval Call theme={null} + pUSD.approve(PerpsDepositContract, maxUint256) + ``` + + Use these contract addresses when building the approval call. + + | Contract | Address | + | ---------------------- | -------------------------------------------- | + | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | + | Perps deposit contract | `0xDCa4af75705dbB50f62437045afF9921947917d2` | + + + The following steps show the Deposit Wallet batch path. If you are trading + with a Safe or Poly Proxy wallet, use an SDK that handles the wallet-specific + transaction flow for you. + + + + + Create the Perps deposit call. Deposit amounts use pUSD base units, so 10 pUSD + is `10000000`. + + ```solidity theme={null} + function deposit(address token, uint256 amount, address to); + ``` + + Encode the deposit calldata with these arguments. + + | Argument | Value | + | -------- | -------------------------------------------- | + | `token` | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | + | `amount` | `10000000` | + | `to` | Signer address for the Polymarket account. | + + Build the final ordered call list. Include the approval call first only when + approval is needed. + + + ```json Without Approval theme={null} + [ + { + "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", + "value": "0", + "data": "" + } + ] + ``` + + ```json With Approval theme={null} + [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + }, + { + "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", + "value": "0", + "data": "" + } + ] + ``` + + + + + Fetch a fresh `WALLET` nonce before submitting the Deposit Wallet batch. + + ```bash theme={null} + curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "address=" \ + --data-urlencode "type=WALLET" + ``` + + The response includes the nonce to sign with the batch. + + ```json theme={null} + { + "address": "", + "nonce": "" + } + ``` + + + + Build the EIP-712 `Batch` typed data for the Deposit Wallet. Use the final + ordered call list from the previous step, and omit the approval call when + allowance is already sufficient. Set `deadline` to a Unix timestamp in seconds + after which the relayer should reject the batch. + + ```json theme={null} + { + "domain": { + "name": "DepositWallet", + "version": "1", + "chainId": 137, + "verifyingContract": "" + }, + "primaryType": "Batch", + "types": { + "Call": [ + { "name": "target", "type": "address" }, + { "name": "value", "type": "uint256" }, + { "name": "data", "type": "bytes" } + ], + "Batch": [ + { "name": "wallet", "type": "address" }, + { "name": "nonce", "type": "uint256" }, + { "name": "deadline", "type": "uint256" }, + { "name": "calls", "type": "Call[]" } + ] + }, + "message": { + "wallet": "", + "nonce": "", + "deadline": "", + "calls": [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + }, + { + "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", + "value": "0", + "data": "" + } + ] + } + } + ``` + + Sign this typed data with the signer for the Polymarket account. + + + + Submit the signed batch to the Relayer API. Use the same ordered call list you + signed in the previous step. + + ```bash theme={null} + curl -X POST "https://relayer-v2.polymarket.com/submit" \ + -H "Content-Type: application/json" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + -d '{ + "type": "WALLET", + "from": "", + "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", + "nonce": "", + "signature": "", + "metadata": "Deposit pUSD to Perps", + "depositWalletParams": { + "depositWallet": "", + "deadline": "", + "calls": [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + }, + { + "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", + "value": "0", + "data": "" + } + ] + } + }' + ``` + + The response includes the relayer transaction ID. + + ```json theme={null} + { + "transactionID": "", + "state": "STATE_NEW" + } + ``` + + + + Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying + on the deposited collateral. + + ```bash theme={null} + curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" + ``` + + ```json theme={null} + { + "transaction_id": "", + "transaction_hash": "", + "state": "STATE_CONFIRMED", + "error_msg": null + } + ``` + + Perps may take a moment to credit the account after the onchain transaction + settles. Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. + + + + + +## Withdraw Collateral + +Withdraw pUSD when the account has available collateral that should return to the +authenticated wallet. + + + + Request a withdrawal to the authenticated wallet. + Amounts use raw pUSD base units, so 10 pUSD is `10_000_000n`. + + ```ts theme={null} + const withdrawalId = await client.withdrawFromPerps({ + amount: 10_000_000n, + }); + ``` + + The SDK signs the withdrawal request with the Polymarket account signer and + returns the Perps withdrawal ID. + + To track the withdrawal, open a Perps session and list withdrawals. + + ```ts theme={null} + const session = await client.openPerpsSession(); + + try { + const withdrawals = await session.listWithdrawals().firstPage(); + } finally { + await session.close(); + } + ``` + + For more details on authenticated sessions, see [Authenticated + Sessions](/perps/authenticated-sessions). + + + + Request a withdrawal to the authenticated wallet. Amounts use raw pUSD base + units, so 10 pUSD is `10_000_000`. + + ```python theme={null} + withdrawal_id = await client.withdraw_from_perps(amount=10_000_000) + ``` + + The SDK signs the withdrawal request with the Polymarket account signer and + returns the Perps withdrawal ID. + + To track the withdrawal, open a Perps session and list withdrawals. + + ```python theme={null} + session = await client.open_perps_session() + + try: + withdrawals = await session.list_withdrawals().first_page() + finally: + await session.close() + ``` + + For more details on authenticated sessions, see [Authenticated + Sessions](/perps/authenticated-sessions). + + + + + + Create a `withdraw` operation with the account signer, pUSD token, raw token + amount, and destination wallet. For withdrawals, `amount` is the raw pUSD token + amount, so 10 pUSD is `10000000`. + + ```json theme={null} + { + "type": "withdraw", + "args": { + "account": "", + "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "amount": "10000000", + "to": "" + } + } + ``` + + | Field | Value | + | --------- | ------------------------------------------ | + | `account` | Signer address for the Polymarket account. | + | `token` | pUSD collateral token address. | + | `amount` | Raw pUSD token amount. | + | `to` | Wallet that receives the withdrawal. | + + + + The withdrawal signature uses EIP-712 typed data with `Withdraw` as the primary + type. Use the same `account`, `token`, `amount`, and `to` values from the + withdrawal operation. + + For withdrawals, `ts` is a Unix timestamp in seconds because the onchain contract + validates it against `block.timestamp`. It must match the `ts` value in the + request body. + + ```json theme={null} + { + "domain": { + "name": "Polymarket", + "version": "1", + "chainId": 137, + "verifyingContract": "0xDCa4af75705dbB50f62437045afF9921947917d2" + }, + "primaryType": "Withdraw", + "types": { + "Withdraw": [ + { "name": "account", "type": "address" }, + { "name": "token", "type": "address" }, + { "name": "amount", "type": "uint256" }, + { "name": "fee", "type": "uint256" }, + { "name": "to", "type": "address" }, + { "name": "salt", "type": "uint64" }, + { "name": "ts", "type": "uint64" } + ] + }, + "message": { + "account": "", + "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "amount": "10000000", + "fee": "0", + "to": "", + "salt": 555555555, + "ts": 1767000014 + } + } + ``` + + | Field | Value | + | ------ | ---------------------------------------------------- | + | `salt` | Random integer generated for this signed request. | + | `ts` | Current Unix timestamp in seconds, not milliseconds. | + + + + Sign the typed data with the Polymarket account signer. The example below uses + Viem. + + ```ts Viem theme={null} + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(""); + + const signature = await account.signTypedData({ + domain: { + name: "Polymarket", + version: "1", + chainId: 137, + verifyingContract: "0xDCa4af75705dbB50f62437045afF9921947917d2", + }, + primaryType: "Withdraw", + types: { + Withdraw: [ + { name: "account", type: "address" }, + { name: "token", type: "address" }, + { name: "amount", type: "uint256" }, + { name: "fee", type: "uint256" }, + { name: "to", type: "address" }, + { name: "salt", type: "uint64" }, + { name: "ts", type: "uint64" }, + ], + }, + message: { + account: "", + token: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + amount: 10000000n, + fee: 0n, + to: "", + salt: 555555555n, + ts: 1767000014n, + }, + }); + ``` + + + + Submit the signed withdrawal request to `POST /v1/account/withdraw`. Use the + same operation values, `salt`, and `ts` from the typed data. + + ```bash theme={null} + curl -X POST "https://api.perpetuals.polymarket.com/v1/account/withdraw" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "withdraw", + "args": { + "account": "", + "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "amount": "10000000", + "to": "" + } + }, + "sig": "", + "salt": 555555555, + "ts": 1767000014 + }' + ``` + + The response indicates whether the withdrawal was accepted. + + + ```json Success theme={null} + { + "status": "ok", + "withdraw_id": 1234567890 + } + ``` + + ```json Failure theme={null} + { + "status": "err", + "withdraw_id": 1234567890, + "error": "insufficient_balance" + } + ``` + + + + + Use the returned `withdraw_id` to match the withdrawal against history results. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "withdrawal_status=pending" + ``` + + For more details on proxy credentials and private account-read headers, see + [Authenticated Sessions](/perps/authenticated-sessions). + + + + + +## Review Funding History + +Use deposit and withdrawal history to reconcile collateral movements after your +integration submits funding requests. + +See [Authenticated Sessions](/perps/authenticated-sessions) for how to create an +authenticated session for private account history reads. + + + + List deposit or withdrawal history from an authenticated Perps session. + + + ```ts Deposits theme={null} + import type { PerpsDeposit } from "@polymarket/client"; + + const session = await client.openPerpsSession(); + + try { + const deposits: PerpsDeposit[] = []; + + for await (const page of session.listDeposits()) { + deposits.push(...page.items); + } + } finally { + await session.close(); + } + ``` + + ```ts Withdrawals theme={null} + import type { PerpsWithdrawal } from "@polymarket/client"; + + const session = await client.openPerpsSession(); + + try { + const withdrawals: PerpsWithdrawal[] = []; + + for await (const page of session.listWithdrawals()) { + withdrawals.push(...page.items); + } + } finally { + await session.close(); + } + ``` + + + + + List deposit or withdrawal history from an authenticated Perps session. + + + ```python Deposits theme={null} + session = await client.open_perps_session() + + try: + deposits = [] + + async for page in session.list_deposits(): + deposits.extend(page.items) + finally: + await session.close() + ``` + + ```python Withdrawals theme={null} + session = await client.open_perps_session() + + try: + withdrawals = [] + + async for page in session.list_withdrawals(): + withdrawals.extend(page.items) + finally: + await session.close() + ``` + + + + + List deposit history. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/deposits" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + List withdrawal history. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + Use the optional `deposit_status`, `withdrawal_status`, `start_timestamp`, and + `end_timestamp` query parameters when reconciling a specific window. + + diff --git a/docs/perps/learn-about-trading/architecture.md b/docs/perps/learn-about-trading/architecture.md new file mode 100644 index 0000000..0474036 --- /dev/null +++ b/docs/perps/learn-about-trading/architecture.md @@ -0,0 +1,49 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Architecture + +> High-level architecture of the Polymarket Perps exchange + +Polymarket Perps is a hybrid exchange: matching happens offchain for speed, while +custody and settlement live on Polygon. Exchange state is periodically committed +onchain so offchain activity remains verifiable. + +## Offchain Matching + +When a trader places an order, the matching engine maintains the order book, +applies risk checks, matches orders, and updates balances, positions, margin, and +funding offchain. This gives the exchange its latency profile because matching +does not wait on block times. + +Orders are authorized by the trader, so the system can only act on trades the +trader approved. + +## Onchain Components + +The following operations are onchain and settle on Polygon: + +* Deposits move funds from a user's Polymarket wallet into the exchange and + credit their Perps account. +* Withdrawals move funds out of the exchange back to a user's Polymarket wallet. + +Deposits and withdrawals are the only way assets enter or leave the exchange. +Trading itself does not produce per-trade onchain transactions. + +## State Root Commitments + +The exchange periodically commits its trading state onchain in the form of state +root commitments. A state root summarizes the offchain ledger at a point in time, +including account balances, and lets observers verify that reported exchange +state matches what Polymarket has committed to Polygon. + +## Data Flow + +1. A trader deposits collateral from their Polymarket wallet into the exchange, + crediting their Perps account. +2. The engine credits the deposit and opens the account for trading. +3. The trader authorizes and places orders. +4. The engine matches orders and updates state offchain. +5. The engine publishes state root commitments onchain on a recurring cadence. +6. The trader authorizes a withdrawal, and funds move back to their Polymarket wallet on Polygon. diff --git a/docs/perps/learn-about-trading/fees.md b/docs/perps/learn-about-trading/fees.md new file mode 100644 index 0000000..4abf51b --- /dev/null +++ b/docs/perps/learn-about-trading/fees.md @@ -0,0 +1,78 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fees + +> Tiered maker and taker trading fees for Polymarket Perps + +Perps trading fees are tiered by an account's trailing 30-day trading volume. +Higher-volume accounts pay lower taker fees, and the top tier earns a maker +rebate instead of paying a maker fee. + +## Fee Calculation + +For each fill, the fee is calculated on the notional value of the trade: + +```text theme={null} +Fee = abs(Price * Quantity) * Rate +``` + +Fees are denominated in the instrument's quote asset (pUSD). The rate applied +to a fill is set by the account's current volume tier. + +| 30-Day Volume ≥ | Taker | Maker | +| --------------- | ------- | -------- | +| \$0 | 0.0400% | 0.0125% | +| \$1M | 0.0370% | 0.0100% | +| \$5M | 0.0350% | 0.0080% | +| \$25M | 0.0300% | 0.0050% | +| \$100M | 0.0270% | 0.0020% | +| \$500M | 0.0250% | 0.0000% | +| \$1B | 0.0200% | -0.0050% | + +New accounts start at the \$0 tier and move up as trailing 30-day volume crosses +each threshold. + +A negative maker fee is a rebate: the maker receives the rebate amount, and the +fee recipient's internal ledger is debited by the same amount. + + + A subset of accounts created during the Perps beta are temporarily on the + top-tier fee schedule regardless of trailing 30-day volume. Standard + volume-based tiering applies to these accounts once the transition period + ends. + + +If you're integrating Perps, read the current fee schedule from +[Trading Fees](/perps/trading#trading-fees). + +## Fee Metrics + +Trailing 7-day activity metrics are available for visibility. They are a +rolling view of recent activity and do not, on their own, determine the volume +tier used to set fees. + +| Metric | Meaning | +| ------------------- | ------------------------------------------------------------------------------ | +| Total volume | Total Perps trading volume | +| Taker volume | Perps volume that removed liquidity | +| Maker volume | Perps volume that added liquidity | +| Account maker share | Account maker volume divided by total exchange volume | +| Entity maker share | Entity maker volume divided by total exchange volume, when the account has one | + +These metrics are cached by UTC day and may be stale by up to 24 hours. + +If you're integrating Perps, read account metrics from +[Account Stats](/perps/account-management#account-stats). + +## Fee Accounting + +Every fill's fee flows through a single fee-recipient account on the internal +ledger: + +* Taker fees credit the recipient. +* Maker fees credit the recipient at every tier where the maker rate is + non-negative. +* At the top tier the maker rate is a rebate, so it debits the recipient and + credits the maker. diff --git a/docs/perps/learn-about-trading/funding.md b/docs/perps/learn-about-trading/funding.md new file mode 100644 index 0000000..3f9eed9 --- /dev/null +++ b/docs/perps/learn-about-trading/funding.md @@ -0,0 +1,99 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Funding + +> Funding rate calculation and settlement + +Unlike futures contracts, perpetuals have no expiry date. Funding is the +mechanism that keeps the perpetual price anchored to the underlying's fair value. +When the perpetual trades above Index, longs pay shorts. When it trades below +Index, shorts pay longs. + +Funding runs continuously across all sessions, regardless of whether the +underlying reference market is open. This keeps the convergence incentive active +and prevents positions from being left unanchored from fair value. + +## How Funding Works + +Funding is computed in three stages: + +1. A premium index is sampled from the order book every 5 seconds. +2. Samples are averaged over the 1-hour charge window to produce an hourly rate. +3. The rate is settled against every open position at the end of the window. + +### Premium Index + +Every 5 seconds, the protocol takes one snapshot per market of how far the book +has drifted from Index. It walks the book for a fixed quote notional on each side. + +```text theme={null} +bid_impact = VWAP of top bids filling 1,000 quote notional +ask_impact = VWAP of top asks filling 1,000 quote notional +``` + +If one side of the book cannot fill the notional because it is too thin or empty, +that side falls back to Index, which zeros its contribution. + +The impact price difference and premium index are: + +```text theme={null} +IPD = max(bid_impact - Index, 0) - max(Index - ask_impact, 0) +PremiumIndex = IPD / Index +``` + +A positive premium means the perpetual is trading rich versus Index. A negative +premium means it is trading cheap. + +### Funding Rate + +At the end of each charge window, premium samples are averaged, passed through the +8-hour funding formula, divided by 8 to get an hourly rate, and capped. + +```text theme={null} +mean_P = average of PremiumIndex samples over the window +scale = 1.0 for crypto markets; 0.5 otherwise +F_8h = scale * (mean_P + clamp(0.0001 - mean_P, +/-0.0005)) +FR_hour = clamp(F_8h / 8, +/-0.04) +``` + +* The 0.01% term is a fixed interest leg per 8 hours. +* The +/-0.05% clamp bounds the interest-versus-premium adjustment. +* Crypto markets use a 1.0 scale. +* Non-crypto markets use a 0.5 scale. +* The 4% per hour cap prevents extreme funding during sustained dislocation. + +### Payment + +At the end of each charge window, every open position in the market settles a +funding payment proportional to position size and the hourly rate. + +| Condition | Longs | Shorts | +| ------------------------------------- | ------- | ------- | +| Hourly rate > 0, perp rich vs Index | Pay | Receive | +| Hourly rate \< 0, perp cheap vs Index | Receive | Pay | + +Funding is a direct transfer between longs and shorts. The protocol takes no cut. +Settlement credits or debits the quote balance, and realized funding is tracked +separately from trading PnL. + +### Interval + +The charge window is 1 hour. Samples are averaged over the hour, and the hourly +rate is applied once at the end. + +Between settlements, rolling premium samples and implied rates are published so +traders can see funding pressure build in real time. + +## Parameters + +| Parameter | Default | Description | +| ---------------- | ------------------------- | ----------------------------------------- | +| Sample interval | 5 seconds | Cadence of premium index samples | +| Impact notional | 1,000 quote notional | Quote notional used for impact VWAP | +| Interest leg | 0.01% per 8 hours | Fixed component in the 8-hour formula | +| Interest clamp | +/-0.05% | Symmetric clamp on interest minus premium | +| Funding scale | 1.0 crypto; 0.5 otherwise | Multiplier applied to the 8-hour formula | +| Charge window | 1 hour | Interval between funding settlements | +| Funding rate cap | 4% per hour | Maximum absolute hourly funding rate | diff --git a/docs/perps/learn-about-trading/geographic-restrictions.md b/docs/perps/learn-about-trading/geographic-restrictions.md new file mode 100644 index 0000000..a94a144 --- /dev/null +++ b/docs/perps/learn-about-trading/geographic-restrictions.md @@ -0,0 +1,43 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Geographic Restrictions + +> Jurisdictions where Polymarket Perps order placement is not permitted + +Polymarket restricts order placement from certain geographic locations to comply +with regulatory requirements and international sanctions. Users in restricted +jurisdictions cannot place Perps orders. + +## Restricted Jurisdictions + +Order placement is not permitted from: + +* United States +* Canada +* Cuba +* Iran +* North Korea +* Syria +* Crimea +* Donetsk +* Luhansk + + + This list can change. Additional restrictions may apply under Polymarket + notices or applicable law. + + +## For Builders + +If you're integrating Perps, enforce these restrictions before submitting orders +for a user: + +* Verify the end user's location before [placing orders](/perps/trading#place-orders). +* Block order submission entirely for users in any of the listed jurisdictions. + Do not only display a warning. +* Apply the same check to any flow that results in a new position, including + programmatic strategies that act on behalf of a user. + +Read-only market data is not subject to these restrictions. diff --git a/docs/perps/learn-about-trading/index-price.md b/docs/perps/learn-about-trading/index-price.md new file mode 100644 index 0000000..acedeca --- /dev/null +++ b/docs/perps/learn-about-trading/index-price.md @@ -0,0 +1,33 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Index Price + +> How the Index Price is computed for Perps + +Index Price is Polymarket's estimate of the underlying asset's fair value. It is +computed from external price feeds, aggregated to resist stale or anomalous +inputs, and published every 200 milliseconds per market. + +## Feed Sources + +Index Price can use feeds from external sources such as: + +* Pyth +* Chainlink Data Streams +* Hyperliquid + +## Feed Selection + +The system selects different feeds based on the current market session so it can +use the most accurate feed set for each market. See [Market Sessions](/perps/learn-about-trading/market-sessions). + +## Aggregation + +Index Price is computed as a weighted average across the selected feeds after +dropping stale prices and filtering outliers. This prevents any single stale or +anomalous feed from moving the Index. + +The same aggregation approach is used to build the [C3 candidate in Mark Price](/perps/learn-about-trading/mark-price), +using a separate mark feed set. diff --git a/docs/perps/learn-about-trading/liquidation-mechanics.md b/docs/perps/learn-about-trading/liquidation-mechanics.md new file mode 100644 index 0000000..9080822 --- /dev/null +++ b/docs/perps/learn-about-trading/liquidation-mechanics.md @@ -0,0 +1,94 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Liquidation Mechanics + +> Detection, execution, and insurance-fund backstop + +When a trader's equity drops below maintenance margin, the system closes the +position before it becomes insolvent. Normal liquidations route through the order +book as reduce-only immediate-or-cancel orders. If the breach is severe, the +position is absorbed directly by the insurance fund instead. + +## Trigger + +An account or isolated position is at risk when: + +```text theme={null} +MarginRatio = Equity / MaintenanceMargin +``` + +Liquidation starts when `MarginRatio < 1.0`, which means `Equity < MM`. + +Cross and isolated positions are checked independently: + +* Cross uses the account's cross equity and combined cross maintenance margin. +* Isolated evaluates each isolated position using its own equity and maintenance margin. + +Margin health is re-evaluated continuously, so the system reacts as soon as a new +Mark Price, fill, or deposit moves the account across the threshold. + +## While Liquidating + +When liquidation starts, the affected scope is flagged: + +* Cross liquidation blocks new orders on every market for the account. +* Isolated liquidation blocks new orders only on the affected market. + +Order submissions from the account are rejected while the flag is set. Existing +resting orders remain on the book. + +## Execution + +The system closes flagged positions with reduce-only immediate-or-cancel orders. +These orders execute immediately against available liquidity and cancel any +unfilled quantity. Margin health is re-evaluated between orders, so partial fills +that restore the account naturally stop the process. + +### Target Selection + +Cross liquidation closes one position at a time. After each fill settles, the +system re-evaluates and picks again from the remaining cross positions, so a +trader with multiple cross positions is unwound across several cycles rather than +all at once. + +Isolated liquidation closes the flagged position in full. + +### Order Shape + +Liquidation orders are IOC, reduce-only, and market-priced. They sweep whatever +liquidity is resting on the book at the moment they land. There is no protective +spread off Mark. + +## Recovery + +When a liquidating account's equity recovers to or above its recovery initial +margin, the flag clears and normal order submission resumes. + +If a position is fully closed during liquidation, the flag is also cleared because +the market no longer has a position to liquidate. + +## Insurance-Fund Backstop + +If equity falls far enough below maintenance margin that order-book liquidation is +unlikely to recover value, the system skips the order book and absorbs the +position into the insurance fund. + +* Cross backstop absorbs all of the trader's cross positions plus their quote-asset balance into the insurance-fund account. +* Isolated backstop absorbs the specific isolated position and its allocated isolated margin. + +Once absorbed, the insurance fund holds the position and manages it like any other +account. + +## Fees + +The liquidating account pays an extra liquidation fee on every fill while flagged, +on top of its normal maker or taker rate. + +```text theme={null} +FillFee = Notional * (MakerOrTakerRate + LiquidationFeeRate) +``` + +Liquidation fee rates vary by market. If you're integrating Perps, read current +values from [Market Data](/perps/market-data#fetch-instruments). diff --git a/docs/perps/learn-about-trading/margin.md b/docs/perps/learn-about-trading/margin.md new file mode 100644 index 0000000..69f7222 --- /dev/null +++ b/docs/perps/learn-about-trading/margin.md @@ -0,0 +1,86 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Margin + +> Initial margin, maintenance margin, and equity calculations + +Margin is the collateral required to open and maintain leveraged positions. It +ensures traders have enough collateral to cover potential losses and gives the +system a buffer to close positions before they become insolvent. + +There are two thresholds. **Initial margin (IM)** is the collateral required to +open or increase a position. **Maintenance margin (MM)** is the minimum +collateral required to keep a position open. When equity drops below maintenance +margin, the position is [liquidated](/perps/learn-about-trading/liquidation-mechanics). + +## Equity + +Equity is the real-time value of an account, incorporating all open positions at +current Mark Price. + +```text theme={null} +Equity = Collateral + UnrealizedPnL(Mark) - FeesDue - FundingDue +``` + +### Unrealized PnL + +```text theme={null} +Long PnL = PositionSize * (Mark - EntryPrice) +Short PnL = PositionSize * (EntryPrice - Mark) +``` + +Because equity depends on Mark Price, equity follows live mark updates. See +[Mark Price](/perps/learn-about-trading/mark-price). + +## Margin Requirements + +```text theme={null} +IM = Notional / L_max +MM = Notional / L_maint +``` + +Margin requirements scale with position size through leverage tiers. Larger +positions require proportionally more margin. Margin is calculated incrementally +across tiers, so a position spanning two tiers uses the lower tier's rate on +notional up to its upper bound and the next tier's rate on the remainder. + +Margin requirements are static across sessions. + +## Margin States + +An account is always in one of three states. + +| State | Condition | What Happens | +| ----------- | ------------------- | ---------------------------------------------- | +| Healthy | `Equity >= IM` | Normal trading | +| Margin call | `MM <= Equity < IM` | Can only reduce exposure or deposit collateral | +| Liquidation | `Equity < MM` | The system begins closing the position | + +## Margin Checks + +### Pre-Trade + +Before any order executes, the system verifies the account can afford it: + +1. Compute the new position after the order fills. +2. Calculate required initial margin using the market's leverage tiers. +3. Reject the order if equity is below required initial margin. + +This prevents accounts from entering a margin-call state through new trades. + +### Continuous Monitoring + +The system continuously evaluates accounts: + +* If equity falls below maintenance margin, liquidation begins. +* If equity is between maintenance margin and initial margin, the account may enter reduce-only mode. + +## Deposits and Withdrawals + +Deposits increase equity. A deposit during margin call can restore the account to +healthy status immediately. + +Withdrawals require the account to remain above required initial margin after the +withdrawal. You cannot withdraw yourself into a margin call. diff --git a/docs/perps/learn-about-trading/mark-price.md b/docs/perps/learn-about-trading/mark-price.md new file mode 100644 index 0000000..a23d9dd --- /dev/null +++ b/docs/perps/learn-about-trading/mark-price.md @@ -0,0 +1,92 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Mark Price + +> How the Mark Price is computed for Perps + +Mark Price is the price used across the system for margin, unrealized PnL, +liquidation triggers, funding premium computation, and risk checks. It is updated +every 200 milliseconds. + +Mark Price is computed as the median of three candidates, each capturing a +different view of fair value. + +```text theme={null} +Mark = median(C1, C2, C3) +``` + +## C1: Smoothed Order Book Mid + +C1 anchors to Index and adjusts gradually based on where the local order book mid +is trading relative to it. + +```text theme={null} +C1 = Index + EMA(Mid - Index) +``` + +* `Mid = (BestBid + BestAsk) / 2` when both sides of the book exist. +* The EMA uses a 150-second window, so C1 moves slowly and resists short-term manipulation. +* If the order book mid is unavailable, C1 falls back to Index. + +## C2: Local Market Activity + +C2 reflects what is actually trading on the local book. + +```text theme={null} +C2 = median(BestBid, BestAsk, LastTrade) +``` + +* Last trade is only included if it is recent. +* Stale trades are excluded so one old print cannot anchor the price. +* If no usable values exist, C2 falls back to Index. + +## C3: Aggregated External Mark + +C3 is built from external mark feeds, separate from Index feeds, that provide an +independent view of fair value outside the local order book. + +For each market, the system: + +1. Selects active mark feeds from eligible external sources. +2. Drops stale samples. +3. Computes the candidate median and filters outliers beyond the allowed tolerance. +4. Returns the weighted average of the remaining samples. + +If no valid external mark data is available, C3 falls back to Index. + +## Why Three Candidates? + +Using the median of three independent price signals provides resilience: + +* C1 is slow-moving and resistant to sudden order book manipulation, but can lag during fast moves. +* C2 is responsive to real local trading activity, but can be influenced by thin liquidity. +* C3 is independent of the local book, but depends on external feed availability. + +The median ensures that no single signal can unilaterally move Mark Price. At +least two of the three candidates must agree for the mark to shift. + +## Finalization + +After computing `median(C1, C2, C3)`, the raw mark is normalized before being +published: + +* Snapped to the nearest tick size +* Rounded to the market's price precision + +## Fallback Summary + +Every input degrades gracefully to [Index Price](/perps/learn-about-trading/index-price). + +| Condition | Behavior | +| ------------------------------- | ----------------------------------------------------------- | +| Index input stale | Falls back to last known market index | +| Order book mid unavailable | C1 falls back to Index | +| No recent trades or quotes | C2 falls back to Index | +| External mark feeds unavailable | C3 falls back to Index | +| All inputs missing | Mark tracks Index because all candidates fall back to Index | + +In the worst case, when there is no local book, no recent trades, and no external +mark feeds, all three candidates converge to Index and Mark Price tracks Index +directly. diff --git a/docs/perps/learn-about-trading/market-sessions.md b/docs/perps/learn-about-trading/market-sessions.md new file mode 100644 index 0000000..0cfccaf --- /dev/null +++ b/docs/perps/learn-about-trading/market-sessions.md @@ -0,0 +1,46 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Market Sessions + +> How session state affects pricing feed selection + +Perps trade 24/7, but the underlying markets do not. Liquidity and external price +feed availability vary by time of day and day of week. Sessions are the system's +categorization of these conditions. + +## What Sessions Affect + +Sessions affect one thing: which set of external feeds is used to compute [Index Price](/perps/learn-about-trading/index-price) and the [C3 candidate in Mark Price](/perps/learn-about-trading/mark-price). + +Each category can use its own feed set. For example, primary venue feeds may be +used during regular hours and after-hours venue feeds may be used overnight. If +the current category has no dedicated feed set, the system falls back to the +overnight feed set. + +## What Sessions Do Not Affect + +Sessions do not change: + +* Funding +* Margin and leverage tiers +* Order matching +* Liquidation triggers + +Those systems run identically around the clock. + +## Categories + +* Regular: the underlying is open and primary feeds are available. +* Overnight: the underlying is closed but some external feeds may still exist. +* Weekend: a calendar-based closed period with thin or absent external data. +* Disrupted: external feeds are unavailable or failing sanity checks. +* Halted: a trading halt or corporate-action freeze on the underlying. + +## How the Category Is Determined + +Each market has a schedule that defines its time windows and exceptions. The +system evaluates the schedule on time boundaries to produce the current category. +When the category changes, subsequent Index and Mark updates use the feed set +assigned to the new category. diff --git a/docs/perps/learn-about-trading/markets.md b/docs/perps/learn-about-trading/markets.md new file mode 100644 index 0000000..fc57d3f --- /dev/null +++ b/docs/perps/learn-about-trading/markets.md @@ -0,0 +1,48 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Markets + +> Listed perpetual markets and trading parameters + +Polymarket Perps markets track underlying assets across indices, commodities, +crypto assets, and equities. Each market has its own trading parameters. + +## Instruments + +Perps markets are represented by instruments, which are the listed perpetual +contracts available to trade. + +| ID | Symbol | Category | Base Asset | Max Leverage | +| -- | ------------ | ----------- | ---------- | ------------ | +| 1 | `SP500-USD` | `index` | `SP500` | 20x | +| 2 | `GOLD-USD` | `commodity` | `GOLD` | 20x | +| 3 | `WTIOIL-USD` | `commodity` | `WTIOIL` | 20x | +| 4 | `NAS100-USD` | `index` | `NAS100` | 20x | +| 5 | `SILVER-USD` | `commodity` | `SILVER` | 20x | +| 6 | `BTC-USD` | `crypto` | `BTC` | 20x | +| 7 | `ETH-USD` | `crypto` | `ETH` | 20x | +| 8 | `SOL-USD` | `crypto` | `SOL` | 20x | +| 9 | `SPCX-USD` | `equity` | `SPCX` | 10x | + +Each instrument also includes details that shape how it trades: + +* Underlying asset +* Collateral and quote asset +* Price and quantity precision +* Tick size +* Minimum order size +* Risk tiers and leverage caps +* Mark, index, and funding configuration + + + Market parameters can change as markets evolve. Builders should read live + instrument details from [Market Data](/perps/market-data#fetch-instruments) + before submitting orders. + + +## Price Feeds + +Each market tracks an underlying market through external price feeds. Those +feeds drive the [Index Price](/perps/learn-about-trading/index-price), and the Index Price helps anchor the [Mark Price](/perps/learn-about-trading/mark-price). diff --git a/docs/perps/learn-about-trading/overview.md b/docs/perps/learn-about-trading/overview.md new file mode 100644 index 0000000..b951905 --- /dev/null +++ b/docs/perps/learn-about-trading/overview.md @@ -0,0 +1,53 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> The market mechanics behind Perps trading + +Perps markets follow a small set of system rules. This section explains how +those rules work so you can anticipate how positions are valued, when they are +at risk, and why account balances change. + + + + How offchain matching and onchain settlement fit together. + + + + Available Perps markets and the parameters that shape trading. + + + + What each fill costs and how the volume-based fee tiers work. + + + + Equity, initial margin, maintenance margin, and margin states. + + + + How liquidation is detected, executed, and backstopped. + + + + How funding rates are computed and settled against open positions. + + + + How the price used for margin, PnL, and liquidation is computed. + + + + How the underlying's fair value is sourced and aggregated. + + + + How session state affects pricing feed selection. + + + + Where order placement is restricted. + + diff --git a/docs/perps/market-data.md b/docs/perps/market-data.md new file mode 100644 index 0000000..265ef5c --- /dev/null +++ b/docs/perps/market-data.md @@ -0,0 +1,846 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Market Data + +> Discover Perps markets and monitor public market activity + +Use market data to understand what can be traded, where the market is trading +now, and how activity has changed over time. + + + + The TypeScript examples on this page use a `PublicClient`. The same market-data + methods are also available on `SecureClient` instances. + + ```ts theme={null} + import { createPublicClient } from "@polymarket/client"; + + const client = createPublicClient(); + ``` + + + + The Python examples on this page use an `AsyncPublicClient`. The same market-data + methods are also available on `AsyncSecureClient` instances. + + ```python theme={null} + from polymarket import AsyncPublicClient + + client = AsyncPublicClient() + ``` + + + + Use the Perps REST API production URL. + + ```text theme={null} + https://api.perpetuals.polymarket.com + ``` + + + +## Fetch Instruments + +Fetch instruments before your integration lets users choose or submit orders for +a Perps market. Instrument data gives you the constraints needed to validate that +workflow. + + + + Fetch the available instruments. + + ```ts theme={null} + const instruments = await client.fetchPerpsInstruments(); + // instruments: PerpsInstrument[] + ``` + + where `PerpsInstrument` is: + + + ```ts Type theme={null} + type PerpsInstrument = { + id: PerpsInstrumentId; + category: PerpsInstrumentCategory; + symbol: string; + baseAsset: string; + quoteAsset: string; + fundingInterval: PerpsFundingInterval; + quantityDecimals: number; + priceDecimals: number; + priceBounds: DecimalString; + liquidationFee: DecimalString; + maxOrderCount: number; + minNotional: DecimalString; + maxMarketNotional: DecimalString; + maxLimitNotional: DecimalString; + maxLeverage: number; + riskTiers: PerpsRiskTier[]; + }; + + type PerpsRiskTier = { + lowerBound: DecimalString; + maxLeverage: number; + }; + ``` + + ```json Example theme={null} + { + "id": 1, + "category": "crypto", + "symbol": "BTC-PERP", + "baseAsset": "BTC", + "quoteAsset": "USD", + "fundingInterval": "1h", + "quantityDecimals": 4, + "priceDecimals": 2, + "priceBounds": "0.1", + "liquidationFee": "0.01", + "maxOrderCount": 200, + "minNotional": "1", + "maxMarketNotional": "100000", + "maxLimitNotional": "1000000", + "maxLeverage": 10, + "riskTiers": [{ "lowerBound": "0", "maxLeverage": 10 }] + } + ``` + + + `PerpsInstrument` includes the market metadata and trading constraints your app + needs before submitting orders. + + | Field | Description | + | ------------------- | ------------------------------------------------------------- | + | `id` | Instrument identifier. | + | `category` | Market category, such as crypto, index, equity, or commodity. | + | `symbol` | Human-readable market symbol. | + | `baseAsset` | Base asset for the instrument. | + | `quoteAsset` | Quote asset used for prices. | + | `fundingInterval` | Funding interval for the instrument, such as `1h`. | + | `quantityDecimals` | Decimal precision for quantities. | + | `priceDecimals` | Decimal precision for prices. | + | `priceBounds` | Price-bound value for the instrument. | + | `liquidationFee` | Liquidation fee value for the instrument. | + | `maxOrderCount` | Maximum order count for the instrument. | + | `minNotional` | Minimum notional value for orders. | + | `maxMarketNotional` | Maximum notional value for market orders. | + | `maxLimitNotional` | Maximum notional value for limit orders. | + | `maxLeverage` | Maximum leverage allowed for the instrument. | + | `riskTiers` | Risk tiers for larger position sizes. | + + + + Fetch the available instruments. + + ```python theme={null} + instruments = await client.fetch_perps_instruments() + # instruments: tuple[PerpsInstrument, ...] + ``` + + Filter by instrument ID when you already know the market you need. + + ```python theme={null} + instruments = await client.fetch_perps_instruments(instrument_id=1) + ``` + + `PerpsInstrument` includes the market metadata and trading constraints your app + needs before submitting orders. + + ```json Example theme={null} + { + "id": 1, + "category": "crypto", + "symbol": "BTC-PERP", + "base_asset": "BTC", + "quote_asset": "USD", + "funding_interval": "1h", + "quantity_decimals": 4, + "price_decimals": 2, + "price_bounds": "0.1", + "liquidation_fee": "0.01", + "max_order_count": 200, + "min_notional": "1", + "max_market_notional": "100000", + "max_limit_notional": "1000000", + "max_leverage": 10, + "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }] + } + ``` + + `PerpsInstrument` exposes these attributes: + + | Attribute | Description | + | --------------------------- | ------------------------------------------------------------- | + | `id` | Instrument identifier. | + | `category` | Market category, such as crypto, index, equity, or commodity. | + | `symbol` | Human-readable market symbol. | + | `base_asset` | Base asset for the instrument. | + | `quote_asset` | Quote asset used for prices. | + | `funding_interval` | Funding interval for the instrument, such as `1h`. | + | `quantity_decimals` | Decimal precision for quantities. | + | `price_decimals` | Decimal precision for prices. | + | `price_bounds` | Price-bound value for the instrument. | + | `liquidation_fee` | Liquidation fee value for the instrument. | + | `max_order_count` | Maximum order count for the instrument. | + | `min_notional` | Minimum notional value for orders. | + | `max_market_notional` | Maximum notional value for market orders. | + | `max_limit_notional` | Maximum notional value for limit orders. | + | `max_leverage` | Maximum leverage allowed for the instrument. | + | `risk_tiers` | Risk tiers for larger position sizes. | + | `risk_tiers[].lower_bound` | Lower notional bound for the risk tier. | + | `risk_tiers[].max_leverage` | Maximum leverage allowed for the risk tier. | + + + + Fetch the available instruments. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/info/instruments" + ``` + + Filter by instrument ID when you already know the market you need. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/instruments" \ + --data-urlencode "instrument_id=1" + ``` + + The response is an array of instruments. + + ```json theme={null} + [ + { + "instrument_id": 1, + "instrument_type": "perpetual", + "category": "crypto", + "symbol": "BTC-PERP", + "base_asset": "BTC", + "quote_asset": "USD", + "funding_interval": "1h", + "quantity_decimals": 4, + "price_decimals": 2, + "price_bounds": "0.1", + "liquidation_fee": "0.01", + "max_order_count": 200, + "min_notional": "1", + "max_market_notional": "100000", + "max_limit_notional": "1000000", + "max_leverage": 10, + "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }] + } + ] + ``` + + Each instrument object includes the market metadata and trading constraints your + app needs before submitting orders. + + | Field | Description | + | --------------------------- | --------------------------------------------------------------------- | + | `instrument_id` | Instrument identifier. | + | `instrument_type` | Instrument type. Perps instruments use `perpetual`. | + | `category` | Market category, such as `crypto`, `index`, `equity`, or `commodity`. | + | `symbol` | Human-readable market symbol. | + | `base_asset` | Base asset for the instrument. | + | `quote_asset` | Quote asset used for prices. | + | `funding_interval` | Funding interval for the instrument, such as `1h`. | + | `quantity_decimals` | Decimal precision for quantities. | + | `price_decimals` | Decimal precision for prices. | + | `price_bounds` | Price-bound value for the instrument. | + | `liquidation_fee` | Liquidation fee value for the instrument. | + | `max_order_count` | Maximum order count for the instrument. | + | `min_notional` | Minimum notional value for orders. | + | `max_market_notional` | Maximum notional value for market orders. | + | `max_limit_notional` | Maximum notional value for limit orders. | + | `max_leverage` | Maximum leverage allowed for the instrument. | + | `risk_tiers` | Risk tiers for larger position sizes. | + | `risk_tiers[].lower_bound` | Lower notional bound for the risk tier. | + | `risk_tiers[].max_leverage` | Maximum leverage allowed for the risk tier. | + + + +## Fetch Tickers + +Use tickers when you need a lightweight view of where one or more markets are +trading now. + + + + Fetch one ticker when you already know which instrument your integration is + tracking. + + ```ts theme={null} + const ticker = await client.fetchPerpsTicker({ + instrumentId: instrument.id, + }); + // ticker: PerpsTicker + ``` + + Fetch all tickers to build a market list or refresh a dashboard. + + ```ts theme={null} + const tickers = await client.fetchPerpsTickers(); + // tickers: PerpsTicker[] + ``` + + where `PerpsTicker` is: + + + ```ts Type theme={null} + type PerpsTicker = { + instrumentId: PerpsInstrumentId; + symbol: string; + indexPrice: DecimalString; + markPrice: DecimalString; + lastPrice: DecimalString; + midPrice: DecimalString; + openInterest: DecimalString; + fundingRate: DecimalString; + nextFunding: EpochMilliseconds; + volume24h?: DecimalString; + openPrice?: DecimalString; + timestamp?: EpochMilliseconds; + }; + ``` + + ```json Example theme={null} + { + "instrumentId": 1, + "symbol": "BTC-PERP", + "indexPrice": "65000.00", + "markPrice": "65012.50", + "lastPrice": "65010.00", + "midPrice": "65011.25", + "openInterest": "125.4", + "fundingRate": "0.0001", + "nextFunding": 1766124000000, + "volume24h": "2450000", + "openPrice": "64250.00", + "timestamp": 1766120400000 + } + ``` + + + + + Fetch one ticker when you already know which instrument your integration is + tracking. + + ```python theme={null} + ticker = await client.fetch_perps_ticker(instrument_id=instrument.id) + # ticker: PerpsTicker + ``` + + Fetch all tickers to build a market list or refresh a dashboard. + + ```python theme={null} + tickers = await client.fetch_perps_tickers() + # tickers: tuple[PerpsTicker, ...] + ``` + + Use the returned ticker for current price, open interest, and funding state. + + ```json Example theme={null} + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "index_price": "65000.00", + "mark_price": "65012.50", + "last_price": "65010.00", + "mid_price": "65011.25", + "open_interest": "125.4", + "funding_rate": "0.0001", + "next_funding": 1766124000000, + "volume_24h": "2450000", + "open_price": "64250.00", + "timestamp": 1766120400000 + } + ``` + + + + Fetch all tickers to build a market list or refresh a dashboard. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/info/tickers" + ``` + + Filter by instrument ID when you only need one ticker. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/tickers" \ + --data-urlencode "instrument_id=1" + ``` + + The response is an array of ticker snapshots. + + ```json theme={null} + [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "index_price": "65000.00", + "mark_price": "65012.50", + "last_price": "65010.00", + "mid_price": "65011.25", + "open_interest": "125.4", + "funding_rate": "0.0001", + "next_funding": 1766124000000, + "timestamp": 1766120400000 + } + ] + ``` + + + +## Fetch the Order Book + +Use the order book before choosing an order price or size. It shows available +liquidity at the requested depth. + + + + Choose how many price levels to request. Supported depths are `10`, `100`, + `500`, and `1000`. When omitted, the SDK requests `100` levels. + + ```ts theme={null} + // depth: PerpsBookDepth + const depth = 100; + ``` + + Fetch the book for the selected instrument. Bids and asks are returned as price + levels with decimal string prices and quantities. + + ```ts theme={null} + const book = await client.fetchPerpsBook({ + instrumentId: instrument.id, + depth, + }); + + const bestBid = book.bids[0]; + const bestAsk = book.asks[0]; + + // book: PerpsBook + // bestBid: PerpsBookLevel | undefined + // bestAsk: PerpsBookLevel | undefined + ``` + + where `PerpsBook` and `PerpsBookLevel` are: + + + ```ts Type theme={null} + type PerpsBook = { + instrumentId: PerpsInstrumentId; + bids: PerpsBookLevel[]; + asks: PerpsBookLevel[]; + timestamp: EpochMilliseconds; + sequence: number; + }; + + type PerpsBookLevel = { + price: DecimalString; + quantity: DecimalString; + }; + ``` + + ```json Example theme={null} + { + "instrumentId": 1, + "bids": [ + { "price": "65010.00", "quantity": "0.75" }, + { "price": "65009.50", "quantity": "1.2" } + ], + "asks": [ + { "price": "65012.50", "quantity": "0.6" }, + { "price": "65013.00", "quantity": "1.1" } + ], + "timestamp": 1766120400000, + "sequence": 123456 + } + ``` + + + + + Choose how many price levels to request. Supported depths are `10`, `100`, + `500`, and `1000`. When omitted, the SDK requests `100` levels. + + ```python theme={null} + depth = 100 + ``` + + Fetch the book for the selected instrument. Bids and asks are returned as price + levels with decimal string prices and quantities. + + ```python theme={null} + book = await client.fetch_perps_book( + instrument_id=instrument.id, + depth=depth, + ) + + best_bid = book.bids[0] if book.bids else None + best_ask = book.asks[0] if book.asks else None + + # book: PerpsBook + # best_bid: PerpsBookLevel | None + # best_ask: PerpsBookLevel | None + ``` + + Use `book.bids` and `book.asks` for bid and ask price levels. + + ```json Example theme={null} + { + "instrument_id": 1, + "bids": [ + { "price": "65010.00", "quantity": "0.75" }, + { "price": "65009.50", "quantity": "1.2" } + ], + "asks": [ + { "price": "65012.50", "quantity": "0.6" }, + { "price": "65013.00", "quantity": "1.1" } + ], + "timestamp": 1766120400000, + "sequence": 123456 + } + ``` + + + + Fetch the order book for an instrument. Supported depths are `10`, `100`, `500`, + and `1000`; when omitted, the API uses `100`. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/book" \ + --data-urlencode "instrument_id=1" \ + --data-urlencode "depth=100" + ``` + + The response returns bids and asks as `[price, quantity]` levels. + + ```json theme={null} + { + "instrument_id": 1, + "bids": [ + ["65010.00", "0.75"], + ["65009.50", "1.2"] + ], + "asks": [ + ["65012.50", "0.6"], + ["65013.00", "1.1"] + ], + "timestamp": 1766120400000, + "sequence": 123456 + } + ``` + + Each `bids` and `asks` level is `[price, quantity]`. + + + +## List Candles + +Use candles when your workflow needs time-bucketed price history for charts, +backtests, or trading signals. + + + + The SDK paginates candle history. When `start` is omitted, it starts from the + past 24 hours. + + ```ts theme={null} + import { PerpsKlineInterval } from "@polymarket/client"; + + const pages = client.listPerpsCandles({ + instrumentId: instrument.id, + interval: PerpsKlineInterval.OneMinute, + }); + + for await (const page of pages) { + for (const candle of page.items) { + // candle: PerpsCandle + } + } + ``` + + where `PerpsCandle` is: + + + ```ts Type theme={null} + type PerpsCandle = { + timestamp: EpochMilliseconds; + open: DecimalString; + high: DecimalString; + low: DecimalString; + close: DecimalString; + volume: DecimalString; + trades: number; + }; + ``` + + ```json Example theme={null} + { + "timestamp": 1766120400000, + "open": "65000.00", + "high": "65025.00", + "low": "64980.00", + "close": "65010.00", + "volume": "42.5", + "trades": 18 + } + ``` + + + + + The SDK paginates candle history. When `start` is omitted, it starts from the + past 24 hours. + + ```python theme={null} + pages = client.list_perps_candles( + instrument_id=instrument.id, + interval="1m", + ) + + async for page in pages: + for candle in page.items: + # candle: PerpsCandle + pass + ``` + + Each candle contains one OHLCV bucket. + + ```json Example theme={null} + { + "timestamp": 1766120400000, + "open": "65000.00", + "high": "65025.00", + "low": "64980.00", + "close": "65010.00", + "volume": "42.5", + "trades": 18 + } + ``` + + + + Fetch candles for an instrument and interval. `start_timestamp` is required; + `end_timestamp` is optional. The API returns at most 1000 candles per request. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/klines" \ + --data-urlencode "instrument_id=1" \ + --data-urlencode "interval=1m" \ + --data-urlencode "start_timestamp=1766120400000" + ``` + + The response returns candles in `data` and a `more` flag for continuation. + + ```json theme={null} + { + "data": [ + [1766120400000, "65000.00", "65025.00", "64980.00", "65010.00", "42.5", 18] + ], + "more": false + } + ``` + + Each candle is `[timestamp, open, high, low, close, volume, trades]`. + + + +## List Trades + +Use public trades when recent executions matter more than aggregated candles. +This is useful for trade tape views and execution analysis. + + + + The SDK paginates trade history, including cursor handling and boundary + deduplication. + + ```ts theme={null} + const pages = client.listPerpsTrades({ + instrumentId: instrument.id, + }); + + for await (const page of pages) { + for (const trade of page.items) { + // trade: PerpsPublicTrade + } + } + ``` + + where `PerpsPublicTrade` is: + + + ```ts Type theme={null} + type PerpsPublicTrade = { + tradeId: PerpsTradeId; + instrumentId: PerpsInstrumentId; + side: PerpsSide; + price: DecimalString; + quantity: DecimalString; + timestamp: EpochMilliseconds; + hash?: TxHash; + }; + ``` + + ```json Example theme={null} + { + "tradeId": 987654, + "instrumentId": 1, + "side": "long", + "price": "65010.00", + "quantity": "0.25", + "timestamp": 1766120400000, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ``` + + + + + The SDK paginates trade history, including cursor handling and boundary + deduplication. + + ```python theme={null} + pages = client.list_perps_trades(instrument_id=instrument.id) + + async for page in pages: + for trade in page.items: + # trade: PerpsTrade + pass + ``` + + Each trade contains one public execution. + + ```json Example theme={null} + { + "trade_id": 987654, + "instrument_id": 1, + "side": "long", + "price": "65010.00", + "quantity": "0.25", + "timestamp": 1766120400000, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ``` + + + + Fetch recent public trades for an instrument. `start_timestamp` and + `end_timestamp` are optional. The API returns at most 100 trades per request. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/trades" \ + --data-urlencode "instrument_id=1" + ``` + + The response returns trades in `data` and a `more` flag for continuation. + + ```json theme={null} + { + "data": [ + { + "trade_id": 987654, + "instrument_id": 1, + "side": "long", + "price": "65010.00", + "quantity": "0.25", + "timestamp": 1766120400000, + "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" + } + ], + "more": false + } + ``` + + + +## List Funding History + +Use funding-rate history when estimating carry costs or explaining why Perps +prices differ from the index over time. + + + + The SDK paginates funding-rate history. + + ```ts theme={null} + const pages = client.listPerpsFundingHistory({ + instrumentId: instrument.id, + }); + + for await (const page of pages) { + for (const fundingRate of page.items) { + // fundingRate: PerpsFundingRate + } + } + ``` + + where `PerpsFundingRate` is: + + + ```ts Type theme={null} + type PerpsFundingRate = { + fundingRate: DecimalString; + timestamp: EpochMilliseconds; + }; + ``` + + ```json Example theme={null} + { + "fundingRate": "0.0001", + "timestamp": 1766120400000 + } + ``` + + + + + The SDK paginates funding-rate history. + + ```python theme={null} + pages = client.list_perps_funding_history(instrument_id=instrument.id) + + async for page in pages: + for funding_rate in page.items: + # funding_rate: PerpsFundingRate + pass + ``` + + Each funding-rate entry contains one historical observation. + + ```json Example theme={null} + { + "funding_rate": "0.0001", + "timestamp": 1766120400000 + } + ``` + + + + Fetch historical funding rates for an instrument. `start_timestamp` and + `end_timestamp` are optional. The API returns at most 100 funding-rate entries + per request. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/funding" \ + --data-urlencode "instrument_id=1" + ``` + + The response returns funding rates in `data` and a `more` flag for continuation. + + ```json theme={null} + { + "data": [ + { + "funding_rate": "0.0001", + "timestamp": 1766120400000 + } + ], + "more": false + } + ``` + + diff --git a/docs/perps/overview.md b/docs/perps/overview.md new file mode 100644 index 0000000..9bc13f0 --- /dev/null +++ b/docs/perps/overview.md @@ -0,0 +1,78 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Start here for Polymarket perpetual markets + +Polymarket Perps are perpetual contracts that track an underlying asset such as +an index, commodity, crypto asset, or equity. Perps trade continuously and do not +expire, so traders can open, manage, and close leveraged positions without +waiting for a market resolution event. + + + Polymarket Perps is in early access. Access requires a valid [Perps referral + link or code](/perps/referral-program). + + +## How Perps Work + +A Perps trade starts as an order in the order book. When it fills, it becomes a +position whose value changes as the tracked market moves, until the trader closes +it or the system closes it because the account can no longer support the risk. + + + + A Perps market has a traded price from the order book and reference prices + used by the system. The index price tracks the underlying asset, while the + mark price is used for account equity, margin checks, and liquidation risk. + + + + Trading a Perps market creates or changes a position. A long position benefits + when the tracked asset rises, and a short position benefits when it falls. + Orders trade through the order book; fills update the account's position, + balance, and history. + + + + Perps require collateral to support open positions. That collateral is the + account's margin: the buffer that covers losses while a position is open. If + account equity falls too far relative to the required margin, the position can + be liquidated to close exposure. + + + + Funding payments keep the contract price close to the index price. When a + market trades above its index price, long positions generally pay short + positions. When it trades below its index price, shorts generally pay longs. + + + +## Building on Perps + +If you are here to see what you can build on top of Polymarket Perps, common use +cases include: + +* Trading bots that react to market signals +* Market making systems that quote Perps markets +* Portfolio dashboards that track balances and positions +* Risk monitors that track margin and liquidation risk +* Market data products that analyze books, trades, and funding payments + +## Next Steps + + + + Learn the shared terms used across Perps docs. + + + + Understand the market mechanics behind Perps. + + + + Build a first end-to-end Perps trading flow. + + diff --git a/docs/perps/place-your-first-trade.md b/docs/perps/place-your-first-trade.md new file mode 100644 index 0000000..e4a4ad8 --- /dev/null +++ b/docs/perps/place-your-first-trade.md @@ -0,0 +1,245 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Place Your First Trade + +> Learn how to prepare a Perps account and submit a first buy order + +This guide walks through the shortest safe path to a first Perps trade. You will +set up a Perps account, add collateral, and place a small buy order. + +You need a Polymarket account with pUSD available before you start. Create one at +[polymarket.com](https://polymarket.com). + + + Building directly against the API? Start with [Authenticated + Sessions](/perps/authenticated-sessions), then use [Fund Your + Account](/perps/fund-your-account) and [Trading](/perps/trading). + + + + + + + Install the Unified TypeScript SDK with the package manager of your choice. + + + ```bash pnpm theme={null} + pnpm add @polymarket/client@beta viem + ``` + + ```bash npm theme={null} + npm install @polymarket/client@beta viem + ``` + + ```bash yarn theme={null} + yarn add @polymarket/client@beta viem + ``` + + + + This page uses Viem for wallet signing. See the [TypeScript tooling + guide](/dev-tooling/typescript#wallet-integrations) for other wallet library + integrations. + + + + + Create a `SecureClient` with the wallet and signer that owns the Perps account. + Include a Relayer API key so the SDK can submit gasless transactions. + + ```ts theme={null} + import { createSecureClient, relayerApiKey } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + wallet: process.env.POLYMARKET_WALLET_ADDRESS!, + signer: privateKey(process.env.PRIVATE_KEY!), + apiKey: relayerApiKey({ + key: process.env.RELAYER_API_KEY!, + address: process.env.RELAYER_API_KEY_ADDRESS!, + }), + }); + ``` + + Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) from + polymarket.com → Settings → API Keys. + + + + Set up the approvals required for Perps collateral deposits, then deposit pUSD + from the user's Polymarket wallet into the Perps account. The minimum Perps + deposit is 10 pUSD. Amounts use raw pUSD base units, so 10 pUSD is + `10_000_000n`. + + ```ts theme={null} + await client.setupTradingApprovals(); + + const deposit = await client.depositToPerps({ + amount: 10_000_000n, + }); + + await deposit.wait(); + ``` + + `deposit.wait()` confirms that the chain transaction settled. Perps may take a + moment to credit the account after that. See [Fund Your + Account](/perps/fund-your-account) for the full funding workflow. + + + + Open a Perps session for private reads and trading. + + ```ts theme={null} + const session = await client.openPerpsSession(); + ``` + + + + Fetch the available Perps instruments and choose the market you want to trade. + + ```ts theme={null} + const instruments = await client.fetchPerpsInstruments(); + const instrument = instruments.find( + (instrument) => instrument.symbol === "SP500-USD", + ); + + if (instrument === undefined) { + throw new Error("Instrument not found."); + } + ``` + + + + Place a long buy order for `1` quantity unit of `SP500-USD` with an explicit + limit price of `100` USD per quantity unit and immediate-or-cancel execution. + + ```ts theme={null} + import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; + + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + quantity: "1", + price: "100", + timeInForce: PerpsTimeInForce.IOC, + }); + + // order.id: PerpsOrderId + ``` + + The returned order includes the accepted order state. See + [Trading](/perps/trading) for direction, order behavior, cancellation, and state + reconciliation. + + + + + + + + Install the Unified Python SDK with the package manager of your choice. + + + ```bash uv theme={null} + uv add polymarket-client + ``` + + ```bash pip theme={null} + pip install polymarket-client + ``` + + ```bash poetry theme={null} + poetry add polymarket-client + ``` + + + + + Create an `AsyncSecureClient` with the wallet and signer that owns the Perps + account. Include a Relayer API key so the SDK can submit gasless transactions. + + ```python theme={null} + import os + + from polymarket import AsyncSecureClient, RelayerApiKey + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], + api_key=RelayerApiKey( + key=os.environ["RELAYER_API_KEY"], + address=os.environ["RELAYER_API_KEY_ADDRESS"], + ), + ) + ``` + + Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) from + polymarket.com → Settings → API Keys. + + + + Set up the approvals required for Perps collateral deposits, then deposit pUSD + from the user's Polymarket wallet into the Perps account. The minimum Perps + deposit is 10 pUSD. Amounts use raw pUSD base units, so 10 pUSD is `10_000_000`. + + ```python theme={null} + await client.setup_trading_approvals() + + deposit = await client.deposit_to_perps(amount=10_000_000) + + await deposit.wait() + ``` + + `deposit.wait()` confirms that the chain transaction settled. Perps may take a + moment to credit the account after that. See [Fund Your + Account](/perps/fund-your-account) for the full funding workflow. + + + + Open a Perps session for private reads and trading. + + ```python theme={null} + session = await client.open_perps_session() + ``` + + + + Fetch the available Perps instruments and choose the market you want to trade. + + ```python theme={null} + instruments = await client.fetch_perps_instruments() + instrument = next( + (item for item in instruments if item.symbol == "SP500-USD"), + None, + ) + + if instrument is None: + raise RuntimeError("Instrument not found.") + ``` + + + + Place a long buy order for `1` quantity unit of `SP500-USD` with an explicit + limit price of `100` USD per quantity unit and immediate-or-cancel execution. + + ```python theme={null} + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + quantity="1", + price="100", + time_in_force="ioc", + ) + + # result.order.id: PerpsOrderId + ``` + + The returned order includes the accepted order state. See + [Trading](/perps/trading) for direction, order behavior, cancellation, and state + reconciliation. + + + + diff --git a/docs/perps/rate-limits.md b/docs/perps/rate-limits.md new file mode 100644 index 0000000..d67d87c --- /dev/null +++ b/docs/perps/rate-limits.md @@ -0,0 +1,86 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Rate Limits + +> IP rate limits, action rate limits, and WebSocket limits for Perps integrations + +Perps uses separate rate-limit buckets for different traffic types. Hitting one +bucket does not consume another bucket, so request volume, account trading +actions, and WebSocket traffic should be monitored separately. + +## How Limits Work + +Use the error type to identify which bucket rejected the request or message. + +| Bucket | Scope | Applies To | Error | +| ---------------------- | -------------- | ---------------------------------- | --------------------------------------------------------------------- | +| IP | IP address | HTTP request volume | HTTP `429` or `ip_rate_limited` | +| Action | Perps account | Order placement and trade actions | `action_rate_limited` | +| WebSocket message | IP address | Inbound WebSocket messages | `message_rate_limited` | +| WebSocket subscription | WebSocket link | Active subscriptions on one socket | Per-channel subscription error when the subscription cap is exhausted | + +## IP Rate Limits + +Every IP address gets **1,000 weighted tokens per minute**. Each HTTP request +consumes tokens equal to its request weight. + +Use scoped requests when possible. Broad, unfiltered reads consume more of the IP +budget than narrow reads. + +| Request Pattern | Weight | +| ------------------------------ | --------------------------------------------- | +| Lightweight reads | 1 | +| Broad unfiltered reads | Up to 20 | +| Order book depth 10 | 2 | +| Order book depth 100 | 5 | +| Order book depth 500 | 10 | +| Order book depth 1000 | 20 | +| Batch order actions | `1 + floor(n / 20)`, where `n` is order count | +| Account orders by ID | 1 | +| Account orders without ID | 10 | +| Open orders by instrument | 1 | +| Open orders without instrument | 20 | + +## Action Rate Limits + +Every account has an action budget from its current limit tier. The default tier +is **5,000 action tokens per minute** with an open-order cap of **1,000**. + +Action limits are account-scoped, not IP-scoped. Batching can reduce IP weight, +but it does not reduce the number of order actions consumed. + +| Action | Action Cost | +| ------------------- | --------------------------- | +| Place one order | 1 token | +| Place 10 orders | 10 tokens | +| Auto-cancel request | 10 tokens | +| Open-order count | Limited by account tier cap | + +Legacy request-rate fields on limit-tier responses are not used for request-rate +enforcement. Use the IP bucket for request volume and the action bucket for +account trading activity. + +## WebSocket Limits + +WebSocket connections have separate limits for connection count, active +subscriptions, and inbound messages. + +| Limit | Scope | Value | +| ---------------------- | ---------- | ---------------------------------- | +| Concurrent connections | IP address | 50 WebSocket connections | +| Active subscriptions | Connection | 100 active subscriptions | +| Inbound messages | IP address | 1,000 messages per minute | +| Subscribe message | Message | 1 message token | +| Unsubscribe message | Message | 1 message token | +| Trade post message | Message | Same batch-size weighting as trade | +| Other post messages | Message | 1 message token | + +## Integration Guidance + +* Scope reads whenever possible. For example, request one instrument's open orders instead of all open orders. +* Batch order placement when it reduces request volume, but do not expect batching to reduce action-token usage. +* Treat `429`, `ip_rate_limited`, `action_rate_limited`, and `message_rate_limited` as retryable after backoff. +* Track active WebSocket subscriptions per connection so reconnects do not accidentally exceed the subscription cap. +* If you operate many users behind shared infrastructure, monitor IP usage separately from account action usage. diff --git a/docs/perps/realtime-updates.md b/docs/perps/realtime-updates.md new file mode 100644 index 0000000..4368c0c --- /dev/null +++ b/docs/perps/realtime-updates.md @@ -0,0 +1,987 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Realtime Updates + +> Stream public Perps market data + +Stream public market data as prices, books, trades, candles, tickers, and market +statistics change. + + + Private order, fill, and account-state reconciliation is covered in [Reconcile + Trade State](/perps/trading#reconcile-trade-state). + + +Start with the stream that matches the view you are building. Subscribe to the +updates you need, read events while the view is active, then stop the stream when +the view no longer needs live data. + + + + Subscribe from a `PublicClient` and iterate over the merged event stream. + + ```ts theme={null} + import { createPublicClient } from "@polymarket/client"; + + const client = createPublicClient(); + + const stream = await client.subscribe([ + { topic: "perps.bbo", instrumentId: 1 }, + { topic: "perps.trades", instrumentId: 1 }, + ]); + + for await (const event of stream) { + switch (event.type) { + case "bbo": + // event: PerpsBboEvent + break; + case "trade": + // event: PerpsTradeEvent + break; + } + + if (shouldClose) { + await stream.close(); + } + } + ``` + + The stream yields typed events for each subscription and can be closed when the + live view no longer needs updates. + + + + Subscribe from an `AsyncPublicClient` and iterate over the merged event stream. + + ```python theme={null} + from polymarket import AsyncPublicClient + from polymarket.streams import PerpsBboSpec, PerpsTradesSpec + + client = AsyncPublicClient() + + stream = await client.subscribe( + [ + PerpsBboSpec(instrument_id=1), + PerpsTradesSpec(instrument_id=1), + ] + ) + + async for event in stream: + if event.type == "bbo": + # event: PerpsBboEvent + pass + elif event.type == "trade": + # event: PerpsTradeEvent + pass + + if should_close: + await stream.close() + ``` + + The stream yields typed events for each subscription and can be closed when the + live view no longer needs updates. + + + + Connect to the Perps WebSocket production URL. + + ```text theme={null} + wss://ws.perpetuals.polymarket.com/v1/ws + ``` + + The example below opens a JavaScript WebSocket client, subscribes to public + market-data updates, then unsubscribes and closes the connection. + + ```ts theme={null} + const ws = new WebSocket("wss://ws.perpetuals.polymarket.com/v1/ws"); + const channels = ["bbo::1", "trades::1", "klines::1::1m"]; + + ws.addEventListener("open", () => { + ws.send( + JSON.stringify({ + id: 1, + req: "sub", + chs: channels, + }), + ); + }); + + ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data); + // message: public market data frame + }); + + function unsubscribeAndClose() { + ws.send( + JSON.stringify({ + id: 2, + req: "unsub", + chs: channels, + }), + ); + ws.close(); + } + ``` + + Use `req: "sub"` to subscribe and `req: "unsub"` with the same `chs` values to + unsubscribe. Each request may include an `id` for request-response matching. + + + +## Best Bid and Offer + +Use best bid and offer updates for top-of-book quotes. + + + + Subscribe to best bid and offer updates for one instrument. + + ```ts theme={null} + const bbo = await client.subscribe([{ topic: "perps.bbo", instrumentId: 1 }]); + + for await (const event of bbo) { + // event: PerpsBboEvent + } + ``` + + After subscribing, the stream yields `PerpsBboEvent` objects like this. + + + ```ts Type theme={null} + type PerpsBboEvent = { + topic: "perps.bbo"; + type: "bbo"; + channel: string; + timestamp: number; + sequence: number; + payload: { + instrumentId: number; + bidPrice: string; + bidQuantity: string; + askPrice: string; + askQuantity: string; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.bbo", + "type": "bbo", + "channel": "bbo::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrumentId": 1, + "bidPrice": "99.50", + "bidQuantity": "10.00", + "askPrice": "100.50", + "askQuantity": "10.00" + } + } + ``` + + + + + Subscribe to best bid and offer updates for one instrument. + + ```python theme={null} + from polymarket.streams import PerpsBboSpec + + bbo = await client.subscribe(PerpsBboSpec(instrument_id=1)) + + async for event in bbo: + # event: PerpsBboEvent + pass + ``` + + After subscribing, the stream yields `PerpsBboEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.bbo", + "type": "bbo", + "channel": "bbo::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrument_id": 1, + "bid_price": "99.50", + "bid_quantity": "10.00", + "ask_price": "100.50", + "ask_quantity": "10.00" + } + } + ``` + + + + Subscribe to best bid and offer updates for one instrument. + + ```json Subscribe theme={null} + { + "id": 1, + "req": "sub", + "chs": ["bbo::"] + } + ``` + + After subscribing, the stream emits BBO update frames like this. + + ```json theme={null} + { + "ch": "bbo::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "iid": 1, + "bp": "99.50", + "bq": "10.00", + "ap": "100.50", + "aq": "10.00" + } + } + ``` + + + +## Order Book + +Use order book updates for depth across bid and ask price levels. + + + + Subscribe to order book updates for one instrument. + + ```ts theme={null} + const book = await client.subscribe([{ topic: "perps.book", instrumentId: 1 }]); + + for await (const event of book) { + // event: PerpsBookEvent + } + ``` + + After subscribing, the stream yields `PerpsBookEvent` objects like this. + + + ```ts Type theme={null} + type PerpsBookEvent = { + topic: "perps.book"; + type: "book"; + channel: string; + timestamp: number; + sequence: number; + payload: { + instrumentId: number; + bids: Array<{ price: string; quantity: string }>; + asks: Array<{ price: string; quantity: string }>; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.book", + "type": "book", + "channel": "book::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrumentId": 1, + "bids": [{ "price": "100.00", "quantity": "10.00" }], + "asks": [{ "price": "101.00", "quantity": "8.00" }] + } + } + ``` + + + + + Subscribe to order book updates for one instrument. + + ```python theme={null} + from polymarket.streams import PerpsBookSpec + + book = await client.subscribe(PerpsBookSpec(instrument_id=1)) + + async for event in book: + # event: PerpsBookEvent + pass + ``` + + After subscribing, the stream yields `PerpsBookEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.book", + "type": "book", + "channel": "book::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrument_id": 1, + "bids": [{ "price": "100.00", "quantity": "10.00" }], + "asks": [{ "price": "101.00", "quantity": "8.00" }] + } + } + ``` + + + + Subscribe to order book updates for one instrument. + + ```json Subscribe theme={null} + { + "id": 2, + "req": "sub", + "chs": ["book::"] + } + ``` + + After subscribing, the stream emits book update frames like this. + + ```json theme={null} + { + "ch": "book::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "b": [["100.00", "10.00"]], + "a": [["101.00", "8.00"]] + } + } + ``` + + + +## Trades + +Use trades to update recent-print lists, last-trade displays, or execution-based +analytics. + + + + Subscribe to public trade updates for one instrument. + + ```ts theme={null} + const trades = await client.subscribe([ + { topic: "perps.trades", instrumentId: 1 }, + ]); + + for await (const event of trades) { + // event: PerpsTradeEvent + } + ``` + + After subscribing, the stream yields `PerpsTradeEvent` objects like this. + + + ```ts Type theme={null} + type PerpsTradeEvent = { + topic: "perps.trades"; + type: "trade"; + channel: string; + timestamp: number; + sequence: number; + payload: { + tradeId: number; + instrumentId: number; + side: "long" | "short"; + price: string; + quantity: string; + timestamp: number; + hash?: string; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.trades", + "type": "trade", + "channel": "trades::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "tradeId": 1, + "instrumentId": 1, + "side": "long", + "price": "100.00", + "quantity": "10.00", + "timestamp": 1767225600000, + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + } + ``` + + + + + Subscribe to public trade updates for one instrument. + + ```python theme={null} + from polymarket.streams import PerpsTradesSpec + + trades = await client.subscribe(PerpsTradesSpec(instrument_id=1)) + + async for event in trades: + # event: PerpsTradeEvent + pass + ``` + + After subscribing, the stream yields `PerpsTradeEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.trades", + "type": "trade", + "channel": "trades::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "trade_id": 1, + "instrument_id": 1, + "side": "long", + "price": "100.00", + "quantity": "10.00", + "timestamp": 1767225600000, + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + } + ``` + + + + Subscribe to public trade updates for one instrument. + + ```json Subscribe theme={null} + { + "id": 3, + "req": "sub", + "chs": ["trades::"] + } + ``` + + After subscribing, the stream emits trade update frames like this. + + ```json theme={null} + { + "ch": "trades::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "tid": 1, + "iid": 1, + "side": "long", + "p": "100.00", + "qty": "10.00", + "ts": 1767225600000, + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + } + ``` + + + +## Tickers + +Use ticker updates for the current mark, index, last price, open interest, and +funding state. + + + + Subscribe to ticker updates for one instrument or all active instruments. + + + ```ts Subscribe to one market theme={null} + const tickers = await client.subscribe([ + { topic: "perps.tickers", instrumentId: 1 }, + ]); + ``` + + ```ts Subscribe to all markets theme={null} + const tickers = await client.subscribe([{ topic: "perps.tickers" }]); + ``` + + + ```ts theme={null} + for await (const event of tickers) { + // event: PerpsTickerEvent + } + ``` + + Omit `instrumentId` to subscribe to ticker updates for all active instruments. + + After subscribing, the stream yields `PerpsTickerEvent` objects like this. + + + ```ts Type theme={null} + type PerpsTickerEvent = { + topic: "perps.tickers"; + type: "ticker"; + channel: string; + timestamp: number; + sequence: number; + payload: { + instrumentId: number; + indexPrice: string; + markPrice: string; + lastPrice: string; + midPrice: string; + openInterest: string; + fundingRate: string; + nextFunding: number; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.tickers", + "type": "ticker", + "channel": "tickers::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrumentId": 1, + "indexPrice": "100.00", + "markPrice": "100.00", + "lastPrice": "100.00", + "midPrice": "100.00", + "openInterest": "10.00", + "fundingRate": "0.0001", + "nextFunding": 1767225600000 + } + } + ``` + + + + + Subscribe to ticker updates for one instrument or all active instruments. + + + ```python Subscribe to one market theme={null} + from polymarket.streams import PerpsTickersSpec + + tickers = await client.subscribe(PerpsTickersSpec(instrument_id=1)) + ``` + + ```python Subscribe to all markets theme={null} + from polymarket.streams import PerpsTickersSpec + + tickers = await client.subscribe(PerpsTickersSpec()) + ``` + + + ```python theme={null} + async for event in tickers: + # event: PerpsTickerEvent + pass + ``` + + Omit `instrument_id` to subscribe to ticker updates for all active instruments. + + After subscribing, the stream yields `PerpsTickerEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.tickers", + "type": "ticker", + "channel": "tickers::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrument_id": 1, + "index_price": "100.00", + "mark_price": "100.00", + "last_price": "100.00", + "mid_price": "100.00", + "open_interest": "10.00", + "funding_rate": "0.0001", + "next_funding": 1767225600000 + } + } + ``` + + + + Subscribe to ticker updates for one instrument or all active instruments. + + + ```json Subscribe to one market theme={null} + { + "id": 4, + "req": "sub", + "chs": ["tickers::"] + } + ``` + + ```json Subscribe to all markets theme={null} + { + "id": 5, + "req": "sub", + "chs": ["tickers::all"] + } + ``` + + + After subscribing, the stream emits ticker update frames like this. + + ```json theme={null} + { + "ch": "tickers::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "iid": 1, + "idx": "100.00", + "mark": "100.00", + "last": "100.00", + "mid": "100.00", + "oi": "10.00", + "fr": "0.0001", + "nxf": 1767225600000 + } + } + ``` + + + +## Statistics + +Use statistics for 24-hour volume, opening price, and the rolling kline window. + + + + Subscribe to 24-hour statistics for one instrument or all active instruments. + + + ```ts Subscribe to one market theme={null} + const statistics = await client.subscribe([ + { topic: "perps.statistics", instrumentId: 1 }, + ]); + ``` + + ```ts Subscribe to all markets theme={null} + const statistics = await client.subscribe([{ topic: "perps.statistics" }]); + ``` + + + ```ts theme={null} + for await (const event of statistics) { + // event: PerpsStatisticEvent + } + ``` + + Omit `instrumentId` to subscribe to statistics updates for all active instruments. + + After subscribing, the stream yields `PerpsStatisticEvent` objects like this. + + + ```ts Type theme={null} + type PerpsStatisticEvent = { + topic: "perps.statistics"; + type: "statistic"; + channel: string; + timestamp: number; + sequence: number; + payload: { + instrumentId: number; + volume: string; + openPrice: string; + klines: Array<{ + timestamp: number; + open: string; + high: string; + low: string; + close: string; + volume: string; + trades: number; + }>; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.statistics", + "type": "statistic", + "channel": "statistics::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrumentId": 1, + "volume": "1000.00", + "openPrice": "100.50", + "klines": [ + { + "timestamp": 1767225600000, + "open": "100.00", + "high": "105.00", + "low": "99.00", + "close": "102.00", + "volume": "500.00", + "trades": 42 + } + ] + } + } + ``` + + + + + Subscribe to 24-hour statistics for one instrument or all active instruments. + + + ```python Subscribe to one market theme={null} + from polymarket.streams import PerpsStatisticsSpec + + statistics = await client.subscribe(PerpsStatisticsSpec(instrument_id=1)) + ``` + + ```python Subscribe to all markets theme={null} + from polymarket.streams import PerpsStatisticsSpec + + statistics = await client.subscribe(PerpsStatisticsSpec()) + ``` + + + ```python theme={null} + async for event in statistics: + # event: PerpsStatisticEvent + pass + ``` + + Omit `instrument_id` to subscribe to statistics updates for all active + instruments. + + After subscribing, the stream yields `PerpsStatisticEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.statistics", + "type": "statistic", + "channel": "statistics::1", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrument_id": 1, + "volume": "1000.00", + "open_price": "100.50", + "klines": [ + { + "timestamp": 1767225600000, + "open": "100.00", + "high": "105.00", + "low": "99.00", + "close": "102.00", + "volume": "500.00", + "trades": 42 + } + ] + } + } + ``` + + + + Subscribe to 24-hour statistics for one instrument or all active instruments. + + + ```json Subscribe to one market theme={null} + { + "id": 6, + "req": "sub", + "chs": ["statistics::"] + } + ``` + + ```json Subscribe to all markets theme={null} + { + "id": 7, + "req": "sub", + "chs": ["statistics::all"] + } + ``` + + + After subscribing, the stream emits statistics update frames like this. + + ```json theme={null} + { + "ch": "statistics::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "iid": 1, + "vol": "1000.00", + "open": "100.50", + "klines": [ + [1767225600000, "100.00", "105.00", "99.00", "102.00", "500.00", 42] + ] + } + } + ``` + + + +## Candles + +Use candles to update charts with live OHLCV data. + + + + Subscribe to candle updates for one instrument and interval. + + ```ts theme={null} + import { PerpsKlineInterval } from "@polymarket/client"; + + const candles = await client.subscribe([ + { + topic: "perps.candles", + instrumentId: 1, + interval: PerpsKlineInterval.OneMinute, + }, + ]); + + for await (const event of candles) { + // event: PerpsCandleEvent + } + ``` + + The public stream supports `1m`, `5m`, `15m`, `1h`, `4h`, `1d`, and `1w` + candle intervals. + + After subscribing, the stream yields `PerpsCandleEvent` objects like this. + + + ```ts Type theme={null} + type PerpsCandleEvent = { + topic: "perps.candles"; + type: "candle"; + channel: string; + timestamp: number; + sequence: number; + payload: { + instrumentId: number; + interval: "1m" | "5m" | "15m" | "1h" | "4h" | "1d" | "1w"; + candles: Array<{ + timestamp: number; + open: string; + high: string; + low: string; + close: string; + volume: string; + trades: number; + }>; + }; + }; + ``` + + ```json Example theme={null} + { + "topic": "perps.candles", + "type": "candle", + "channel": "klines::1::1m", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrumentId": 1, + "interval": "1m", + "candles": [ + { + "timestamp": 1767225600000, + "open": "100.00", + "high": "105.00", + "low": "99.00", + "close": "102.00", + "volume": "500.00", + "trades": 42 + } + ] + } + } + ``` + + + + + Subscribe to candle updates for one instrument and interval. + + ```python theme={null} + from polymarket.streams import PerpsCandlesSpec + + candles = await client.subscribe( + PerpsCandlesSpec( + instrument_id=1, + interval="1m", + ) + ) + + async for event in candles: + # event: PerpsCandleEvent + pass + ``` + + The public stream supports `1m`, `5m`, `15m`, `1h`, `4h`, `1d`, and `1w` + candle intervals. + + After subscribing, the stream yields `PerpsCandleEvent` objects like this. + + ```json Example theme={null} + { + "topic": "perps.candles", + "type": "candle", + "channel": "klines::1::1m", + "timestamp": 1767225600000, + "sequence": 1234567890, + "payload": { + "instrument_id": 1, + "interval": "1m", + "candles": [ + { + "timestamp": 1767225600000, + "open": "100.00", + "high": "105.00", + "low": "99.00", + "close": "102.00", + "volume": "500.00", + "trades": 42 + } + ] + } + } + ``` + + + + Subscribe to candle updates for one instrument and interval. + + ```json Subscribe theme={null} + { + "id": 8, + "req": "sub", + "chs": ["klines::::1m"] + } + ``` + + The public stream supports `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, + `1d`, and `1w` candle intervals. + + After subscribing, the stream emits kline update frames like this. + + ```json theme={null} + { + "ch": "klines::1::1m", + "ts": 1767225600000, + "sq": 1234567890, + "data": [[1767225600000, "100.00", "105.00", "99.00", "102.00", "500.00", 42]] + } + ``` + + diff --git a/docs/perps/referral-program.md b/docs/perps/referral-program.md new file mode 100644 index 0000000..2304999 --- /dev/null +++ b/docs/perps/referral-program.md @@ -0,0 +1,84 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Referral Program + +> Earn a share of Perps trading fees from traders you refer + +Refer traders to Polymarket Perps and earn a share of the trading fees they pay. +Each account has one Perps referral code. Share your Perps link, and when a new +trader opens Perps through it, your code is applied to their account +automatically. + + + This is the first version of the Perps referral program. The mechanics, + attribution rules, and program details are set for launch and may change as + the program expands. + + +## How It Works + +Every Perps account has one referral code. Your referral code and your Perps +invite code are the same string, so the same link invites traders and credits you +for the referral. + +```text theme={null} +https://polymarket.com/perps?c={code} +``` + +When someone opens Perps through your link, your code is applied to their account +automatically. You start earning on the trading fees they generate after they are +attributed to your code. + +A referral code can be applied only once. An account keeps the first code it is +given and cannot switch to a different code later. You also cannot apply your own +code. + +## Rewards + +You earn **20% of the trading fees** paid by every Perps trader you refer. There +is no cap on how much a single referred trader can earn you. + +| Detail | Perps referral program | +| ------------- | --------------------------------------------------- | +| Reward | 20% of trading fees paid by referred Perps traders | +| Recipient | The referrer | +| Trader bonus | No separate bonus is paid to the trader you invite | +| Per-user cap | No cap on how much one referred trader can earn you | +| Payout timing | Weekly | + +## Code Limits + +A standard Perps referral code can be used by up to **15 people**. After 15 +traders sign up through your code, anyone who opens your link sees a referral +expired state. + +If you are running a larger campaign and need more than 15 uses, reach out to the +Polymarket team to discuss a higher limit. + +## Payouts + +Referral earnings are paid out weekly. You can see referral payouts in your +Perpetuals portfolio history. + +## Find and Track Your Code + +Your referral code is available from your profile and on Perps market pages, so +you can copy and share it while you trade. + +The referrals dashboard shows how the program is performing for your account: + +* Sign-ups against your code limit +* Total trading volume from referred traders +* Total referral earnings +* Per-referral details, including the trader, sign-up time, and earnings + +## Perps vs. Prediction Market Referrals + +The Perps referral program is separate from the prediction market referral +program. They use different codes and track earnings independently. + +Referring a Perps trader does not affect your prediction market referrals, and a +prediction market referral does not affect your Perps referrals. Each program +shows up in its own place. diff --git a/docs/perps/trading.md b/docs/perps/trading.md new file mode 100644 index 0000000..0c160bc --- /dev/null +++ b/docs/perps/trading.md @@ -0,0 +1,2396 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Trading + +> Place, manage, and reconcile Perps orders + + + Trading workflows require an [authenticated + session](/perps/authenticated-sessions). + + +Perps trading changes account exposure on an instrument. An order expresses what +the account wants to do, but exposure only changes when the order fills. + +An accepted order can rest on the book before it fills. + +```mermaid theme={null} +flowchart TD + A[Submit order] --> B{Accepted?} + B -->|No| C[Order rejected] + B -->|Yes| D{Filled?} + D -->|Rests| E[Open order] + D -->|Fills| F[Fill] + D -->|Partially fills| F + F -->|Remaining quantity| E + F --> G[Exposure changes] + E --> H[Cancel if needed] +``` + +Use order state to track accepted, resting, modified, canceled, or rejected +orders. Use fills and portfolio state to confirm any exposure change. + +## Start an Authenticated Session + +Open an authenticated session before reading private account state or submitting +trading commands. See [Authenticated Sessions](/perps/authenticated-sessions) for +the full setup flow. + + + + Create a `SecureClient`. + + ```ts theme={null} + import { createSecureClient } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + wallet: process.env.POLYMARKET_WALLET_ADDRESS!, + signer: privateKey(process.env.PRIVATE_KEY!), + }); + ``` + + Open the Perps session. + + ```ts theme={null} + const session = await client.openPerpsSession(); + ``` + + + + Create an `AsyncSecureClient`. + + ```python theme={null} + import os + + from polymarket import AsyncSecureClient + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], + ) + ``` + + Open the Perps session. + + ```python theme={null} + session = await client.open_perps_session() + ``` + + + + Use proxy credentials for private reads and signed trading commands. + + ```http theme={null} + polymarket-proxy: + polymarket-secret: + ``` + + + +## Prepare a Trade + +Start by identifying the Perps instrument you want to trade. Instruments define +the market and include the constraints used later when building an order. + + + + Fetch instruments and select the market you want to trade. + + ```ts theme={null} + const instruments = await client.fetchPerpsInstruments(); + const instrument = instruments.find((item) => item.symbol === "BTC-PERP"); + + if (!instrument) { + throw new Error("Instrument not found"); + } + ``` + + Keep the selected `instrument` available for the next steps. + + + + Fetch instruments and select the market you want to trade. + + ```python theme={null} + instruments = await client.fetch_perps_instruments() + instrument = next((item for item in instruments if item.symbol == "BTC-PERP"), None) + + if instrument is None: + raise RuntimeError("Instrument not found") + ``` + + Keep the selected `instrument` available for the next steps. + + + + Fetch instruments and select the market you want to trade. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/info/instruments" + ``` + + The response is a list of instruments. + + ```json theme={null} + [ + { + "instrument_id": 1, + "instrument_type": "perpetual", + "category": "crypto", + "symbol": "BTC-PERP", + "base_asset": "BTC", + "quote_asset": "USD", + "funding_interval": "1h", + "quantity_decimals": 4, + "price_decimals": 2, + "price_bounds": "0.1", + "liquidation_fee": "0.01", + "max_order_count": 200, + "min_notional": "1", + "max_market_notional": "100000", + "max_limit_notional": "1000000", + "max_leverage": 10, + "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }] + } + ] + ``` + + Keep the selected instrument for the next steps. + + + +## Choose Direction and Size + +Before placing an order, decide whether it should open new exposure, increase +existing exposure, reduce exposure, or close the position. + +The effect of a buy or sell depends on the current position. + +| Current position | Buy order | Sell order | +| ---------------- | ----------------------- | ---------------------- | +| No position | Opens long | Opens short | +| Long | Increases long | Reduces or closes long | +| Short | Reduces or closes short | Increases short | + +To close a position, submit an order in the opposite direction for the current +open position size. + + + + Read the portfolio when the order decision depends on current exposure. + + ```ts theme={null} + const portfolio = await session.fetchPortfolio(); + const position = portfolio.positions.find( + (item) => item.instrumentId === instrument.id, + ); + ``` + + Positive `position.size` means the account is long. Negative `position.size` + means the account is short. No matching position means the account has no open + exposure for that instrument. + + + + Read the portfolio when the order decision depends on current exposure. + + ```python theme={null} + portfolio = await session.fetch_portfolio() + position = next( + (item for item in portfolio.positions if item.instrument_id == instrument.id), + None, + ) + ``` + + Positive `position.size` means the account is long. Negative `position.size` + means the account is short. No matching position means the account has no open + exposure for that instrument. + + + + Read the portfolio when the order decision depends on current exposure. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + The response includes current positions. + + ```json theme={null} + { + "positions": [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "size": "0.01", + "entry_price": "65000", + "leverage": 5, + "cross": false, + "initial_margin": "130", + "maintenance_margin": "65", + "position_value": "650", + "liquidation_price": "52000", + "unrealized_pnl": "0", + "return_on_equity": "0", + "cumulative_funding": "0" + } + ], + "margin": { + "total_account_value": "1000", + "total_initial_margin": "130", + "total_maintenance_margin": "65", + "total_position_value": "650" + }, + "withdrawable": "870", + "in_liquidation": false, + "timestamp": 1767000000000 + } + ``` + + Positive `positions[].size` means the account is long. Negative + `positions[].size` means the account is short. No matching position means the + account has no open exposure for that instrument. + + + +## Place Orders + +Place an order when the account is ready to express buy or sell intent. Use an +explicit limit price when you need price protection. Use immediate-or-cancel +execution when the order should fill immediately or cancel any unfilled quantity. + + + + + + Fetch a ticker when you need a lightweight current-price reference. Fetch the + book when the order price depends on spread, depth, or top-of-book liquidity. + + ```ts theme={null} + const ticker = await client.fetchPerpsTicker({ instrumentId: instrument.id }); + const book = await client.fetchPerpsBook({ instrumentId: instrument.id }); + ``` + + Set `price` as pUSD per quantity unit, rounded to `instrument.priceDecimals`. + + + + Create the order request from the direction, price, quantity, and execution + behavior you chose. This example submits an immediate-or-cancel (IOC) buy order + for `0.01` BTC-PERP at `65000` pUSD per quantity unit. + + ```ts theme={null} + import { + OrderSide, + PerpsTimeInForce, + type PlacePerpsOrderRequest, + } from "@polymarket/client"; + + const request: PlacePerpsOrderRequest = { + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.IOC, + }; + ``` + + * `side` sets direction based on how you intend to open, increase, reduce, or + close the position. + * `price` is the price you chose in the first step, in pUSD per quantity unit. + * `quantity` is the number of quantity units. Use no more than + `instrument.quantityDecimals` decimal places. + + Use `clientOrderId` when your integration needs its own identifier for tracking + or canceling the order. + + ```ts theme={null} + const request: PlacePerpsOrderRequest = { + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.IOC, + clientOrderId: "7f9e4a2b6c8d0e1f1234567890abcdef", + }; + ``` + + + + Submit the request with `placeOrder`. It resolves with the matching private order + update after the order is accepted. + + ```ts theme={null} + const order = await session.placeOrder(request); + ``` + + Use the returned order to track whether the order filled, expired, canceled, or + remains on the book. + + + ```ts PerpsOrder theme={null} + type PerpsOrder = { + id: PerpsOrderId; + instrumentId: PerpsInstrumentId; + side: OrderSide; + price: string; + quantity: string; + timeInForce: PerpsTimeInForce; + postOnly: boolean; + status: PerpsOrderStatus; + restingQuantity: string; + filledQuantity: string; + createdTimestamp: number; + updatedTimestamp: number; + clientOrderId?: string; + tpSl?: PerpsTpSlOrderFields; + }; + ``` + + ```json Example theme={null} + { + "id": 1234567890, + "instrumentId": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "timeInForce": "ioc", + "postOnly": false, + "status": "filled", + "restingQuantity": "0", + "filledQuantity": "0.01", + "createdTimestamp": 1767000010000, + "updatedTimestamp": 1767000010500, + "clientOrderId": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ``` + + + For an IOC order, `status` can be one of these values. + + | Status | Description | + | ------------------------------- | -------------------------------------------------------------------- | + | `PerpsOrderStatus.Filled` | The order fully filled. | + | `PerpsOrderStatus.IocNoFill` | The order did not fill. | + | `PerpsOrderStatus.IocExpired` | The order filled partially and the remainder canceled. | + | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | + + + + + + + + Fetch a ticker when you need a lightweight current-price reference. Fetch the + book when the order price depends on spread, depth, or top-of-book liquidity. + + ```python theme={null} + ticker = await client.fetch_perps_ticker(instrument_id=instrument.id) + book = await client.fetch_perps_book(instrument_id=instrument.id) + ``` + + Set `price` as pUSD per quantity unit, rounded to `instrument.price_decimals`. + + + + Create the order request from the direction, price, quantity, and execution + behavior you chose. This example submits an immediate-or-cancel (IOC) buy order + for `0.01` BTC-PERP at `65000` pUSD per quantity unit. + + ```python theme={null} + request = { + "instrument_id": instrument.id, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "ioc", + } + ``` + + * `side` sets direction based on how you intend to open, increase, reduce, or + close the position. + * `price` is the price you chose in the first step, in pUSD per quantity unit. + * `quantity` is the number of quantity units. Use no more than + `instrument.quantity_decimals` decimal places. + + Use `client_order_id` when your integration needs its own identifier for tracking + or canceling the order. + + ```python theme={null} + request = { + "instrument_id": instrument.id, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "ioc", + "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", + } + ``` + + + + Submit the request with `place_order`. It resolves with the matching private + order update after the order is accepted. + + ```python theme={null} + result = await session.place_order(**request) + # result.order: PerpsOrder + ``` + + Use `result.order` to track whether the order filled, expired, canceled, or + remains on the book. + + ```json Example theme={null} + { + "id": 1234567890, + "instrument_id": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "ioc", + "post_only": false, + "status": "filled", + "resting_quantity": "0", + "filled_quantity": "0.01", + "created_at": 1767000010000, + "updated_at": 1767000010500, + "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ``` + + For an IOC order, `result.order.status` can be one of these values. + + | Status | Description | + | --------------- | -------------------------------------------------------------------- | + | `filled` | The order fully filled. | + | `ioc_no_fill` | The order did not fill. | + | `ioc_expired` | The order filled partially and the remainder canceled. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + + + + + + + Fetch current market data when the order price depends on live prices or + available liquidity. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/info/tickers" \ + --data-urlencode "instrument_id=1" + + curl -G "https://api.perpetuals.polymarket.com/v1/info/book" \ + --data-urlencode "instrument_id=1" \ + --data-urlencode "depth=100" + ``` + + Use tickers for a lightweight current-price reference. Use the book when the + order price depends on spread, depth, or top-of-book liquidity. + + Set price as pUSD per quantity unit, rounded to the instrument's + `price_decimals`. + + + + Create a `createOrders` operation from the direction, price, quantity, and + execution behavior you chose. This example submits an immediate-or-cancel (`ioc`) + buy order for `0.01` BTC-PERP at `65000` pUSD per quantity unit. + + | Concept | Field | Notes | + | --------------- | ----- | ---------------------------------------------------------------------------------------------------------------------- | + | Instrument | `iid` | Instrument identifier. | + | Direction | `buy` | `true` buys, `false` sells. | + | Price | `p` | Price chosen in the first step. | + | Quantity | `qty` | Number of quantity units, with no more than `quantity_decimals` decimal places. | + | Time in force | `tif` | Use `ioc` for this basic order. | + | Client order ID | `c` | Optional identifier your integration can use to track or cancel the order. Must be a 32-character lowercase hex value. | + + ```json theme={null} + { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "ioc", + "c": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ] + } + ``` + + + + Create the operation hash from the compact signable representation of the order + operation. For `createOrders`, the compact operation is: + + ```ts theme={null} + ["createOrders", [[iid, buy, p, qty, tif, po, ro, c, tr]]]; + ``` + + Omit `undefined` array entries from the compact operation, then + MessagePack-encode it and hash the encoded bytes with `keccak256`. + + The example below uses `@msgpack/msgpack` and Viem. + + ```ts theme={null} + import { encode } from "@msgpack/msgpack"; + import { keccak256 } from "viem"; + + const signableOperation = [ + "createOrders", + [ + [ + 1, + true, + "65000", + "0.01", + "ioc", + false, + undefined, + "7f9e4a2b6c8d0e1f1234567890abcdef", + undefined, + ].filter((value) => value !== undefined), + ], + ] as const; + + const opHash = keccak256(encode(signableOperation)); + ``` + + + + Create an EIP-712 `Op` typed-data payload. + + ```json theme={null} + { + "domain": { + "name": "Polymarket", + "version": "1", + "chainId": 137 + }, + "primaryType": "Op", + "types": { + "Op": [ + { "name": "data", "type": "bytes32" }, + { "name": "salt", "type": "uint64" }, + { "name": "ts", "type": "uint64" } + ] + }, + "message": { + "data": "", + "salt": 234567890, + "ts": 1767000010000 + } + } + ``` + + | Field | Value | + | ------ | ------------------------------------------------- | + | `data` | Operation hash from the previous step. | + | `salt` | Random integer generated for this signed request. | + | `ts` | Current Unix timestamp in milliseconds. | + + + + Sign the `Op` typed data with the proxy signer private key. The example below + uses Viem. + + ```ts Viem theme={null} + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(""); + + const signature = await account.signTypedData({ + domain: { + name: "Polymarket", + version: "1", + chainId: 137, + }, + primaryType: "Op", + types: { + Op: [ + { name: "data", type: "bytes32" }, + { name: "salt", type: "uint64" }, + { name: "ts", type: "uint64" }, + ], + }, + message: { + data: opHash, + salt: 234567890, + ts: 1767000010000, + }, + }); + ``` + + + + Submit the signed request to `POST /v1/trade/orders`. + + ```bash theme={null} + curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "ioc", + "c": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ] + }, + "sig": "", + "salt": 234567890, + "ts": 1767000010000 + }' + ``` + + The response confirms whether the order request was accepted. Read the order + state separately to see whether it filled, expired, or rests on the book. + + + ```json Success theme={null} + [ + { + "status": "ok", + "oid": 1234567890, + "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ] + ``` + + ```json Failure theme={null} + [ + { + "status": "err", + "error": "insufficient_margin" + } + ] + ``` + + + On success, keep `oid` as the order ID. If you supplied `c`, the response also + echoes it as `coid`. + + + + Fetch the order snapshot by `order_id` or `client_order_id` to see whether the + order filled, expired, or canceled after acceptance. + + + ```bash Order ID theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "order_id=1234567890" + ``` + + ```bash Client Order ID theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "client_order_id=7f9e4a2b6c8d0e1f1234567890abcdef" + ``` + + + Use the order state fields to reconcile fill quantity, resting quantity, and + status. + + | Field | Meaning | + | ------------------- | ------------------------------------------------------ | + | `order_id` | Order ID returned as `oid` in the acknowledgement. | + | `instrument_id` | Instrument identifier. | + | `buy` | `true` for buy orders, `false` for sell orders. | + | `price` | pUSD price per quantity unit. | + | `quantity` | Original order quantity. | + | `tif` | Time in force. | + | `post_only` | Whether the order was post-only. | + | `ro` | Whether the order was reduce-only. | + | `status` | Latest known order status. | + | `resting_quantity` | Quantity still resting on the book. | + | `filled_quantity` | Quantity that has filled. | + | `created_timestamp` | Creation timestamp in milliseconds. | + | `updated_timestamp` | Last update timestamp in milliseconds. | + | `client_order_id` | Client order ID, present when supplied in the request. | + + If the order snapshot is not available immediately, retry the read or listen to + the private `orders` WebSocket channel for live updates. + + ```json theme={null} + [ + { + "order_id": 1234567890, + "instrument_id": 1, + "buy": true, + "price": "65000", + "quantity": "0.01", + "tif": "ioc", + "post_only": false, + "ro": false, + "status": "filled", + "resting_quantity": "0", + "filled_quantity": "0.01", + "created_timestamp": 1767000010000, + "updated_timestamp": 1767000010500, + "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef" + } + ] + ``` + + After this `ioc` order resolves, `status` is one of these values. + + | Status | Description | + | --------------- | -------------------------------------------------------------------- | + | `filled` | The order fully filled. | + | `ioc_no_fill` | The order did not fill. | + | `ioc_expired` | The order filled partially and the remainder canceled. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + + + + +## Take Profit & Stop Loss + +Use take-profit and stop-loss (TP/SL) orders to place conditional exits for a +position. A take-profit order exits when price moves in your favor. A stop-loss +order exits when price moves against you. + +### How Triggers Work + +TP/SL orders watch the mark price, not the last traded price. A trigger fires +when the mark price touches the trigger price, then submits a reduce-only order to +close exposure. + +| Position | Take-profit fires when | Stop-loss fires when | +| -------- | ---------------------- | --------------------- | +| Long | Mark rises to trigger | Mark falls to trigger | +| Short | Mark falls to trigger | Mark rises to trigger | + +For a long position, take-profit triggers usually sit above the current mark and +stop-loss triggers usually sit below it. For a short position, the directions are +reversed. + +### Market and Limit Closes + +Choose how the exit should execute after the trigger fires. + +| Close Type | What Happens | Available For | +| ---------- | ----------------------------------------------------------------- | ---------------------------- | +| Market | The exit executes immediately against available liquidity. | Bracket orders and positions | +| Limit | The exit places a limit order and can remain open until it fills. | Bracket orders only | + +### Place a Bracket Order + +A bracket order submits one entry order with up to one take-profit and one +stop-loss trigger. The triggers stay dormant until the entry fills in full. If +the entry is canceled, rejected, or only partially filled, the triggers are +canceled too. A bracket protects the completed entry, not a partial fill. + + + You cannot attach TP/SL triggers to an order that is already resting on the + book. To protect a position from an existing order, wait for the fill and then + protect the position. + + + + + Place a GTC entry order with take-profit and stop-loss triggers. + + ```ts theme={null} + import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; + + const result = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.GTC, + takeProfit: { + triggerPrice: "70000", + }, + stopLoss: { + triggerPrice: "62000", + }, + }); + + const entryOrderId = result.order.id; + const takeProfitOrderId = result.tpSl.takeProfit?.orderId; + const stopLossOrderId = result.tpSl.stopLoss?.orderId; + ``` + + `result.order` is the entry order. `result.tpSl` contains the order IDs for the + conditional exits that were accepted with the entry order. + + + ```json theme={null} + { + "order": { + "id": 1234567890, + "instrumentId": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "timeInForce": "gtc", + "postOnly": false, + "status": "open", + "restingQuantity": "0.01", + "filledQuantity": "0", + "createdTimestamp": 1767000010000, + "updatedTimestamp": 1767000010500 + }, + "tpSl": { + "takeProfit": { "orderId": 1234567891 }, + "stopLoss": { "orderId": 1234567892 } + } + } + ``` + + + Add `limitPrice` to a trigger when the exit should place a limit order at trigger + time. + + ```ts theme={null} + const result = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.GTC, + stopLoss: { + triggerPrice: "62000", + limitPrice: "61900", + }, + }); + ``` + + + + Place a GTC entry order with take-profit and stop-loss triggers. + + ```python theme={null} + from polymarket import PerpsTpSlTrigger + + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + price="65000", + quantity="0.01", + time_in_force="gtc", + take_profit=PerpsTpSlTrigger(trigger_price="70000"), + stop_loss=PerpsTpSlTrigger(trigger_price="62000"), + ) + + # result.order.id: PerpsOrderId + # result.tp_sl.take_profit.order_id: PerpsOrderId + # result.tp_sl.stop_loss.order_id: PerpsOrderId + ``` + + `result.order` is the entry order. `result.tp_sl` contains the order IDs for the + conditional exits that were accepted with the entry order. + + + ```json theme={null} + { + "order": { + "id": 1234567890, + "instrument_id": 1, + "side": "BUY", + "price": "65000", + "quantity": "0.01", + "time_in_force": "gtc", + "post_only": false, + "status": "open", + "resting_quantity": "0.01", + "filled_quantity": "0", + "created_at": 1767000010000, + "updated_at": 1767000010500 + }, + "tp_sl": { + "take_profit": { "order_id": 1234567891 }, + "stop_loss": { "order_id": 1234567892 } + } + } + ``` + + + Add `limit_price` to a trigger when the exit should place a limit order at + trigger time. + + ```python theme={null} + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + price="65000", + quantity="0.01", + time_in_force="gtc", + stop_loss=PerpsTpSlTrigger( + trigger_price="62000", + limit_price="61900", + ), + ) + ``` + + + + Submit the entry order and its TP/SL children in one `createOrders` operation + with `grp` set to `"order"`. + + ```json theme={null} + { + "type": "createOrders", + "grp": "order", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "gtc", + "c": "7f9e4a2b6c8d0e1f1234567890abcdef" + }, + { + "iid": 1, + "buy": false, + "qty": "0.01", + "ro": true, + "tr": { + "market": true, + "trp": "70000", + "tpsl": "tp" + } + }, + { + "iid": 1, + "buy": false, + "qty": "0.01", + "ro": true, + "tr": { + "market": true, + "trp": "62000", + "tpsl": "sl" + } + } + ] + } + ``` + + Use the same signing flow as [Place Orders](#place-orders). For hashing, sign the + compact operation, not the structured JSON body. The TP/SL group is the third + compact element: + + ```ts theme={null} + ["createOrders", [entryOrder, takeProfitOrder, stopLossOrder], "order"]; + ``` + + Then submit the signed request to `POST /v1/trade/orders`. + + ```bash theme={null} + curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "createOrders", + "grp": "order", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "gtc", + "c": "7f9e4a2b6c8d0e1f1234567890abcdef" + }, + { + "iid": 1, + "buy": false, + "qty": "0.01", + "ro": true, + "tr": { + "market": true, + "trp": "70000", + "tpsl": "tp" + } + }, + { + "iid": 1, + "buy": false, + "qty": "0.01", + "ro": true, + "tr": { + "market": true, + "trp": "62000", + "tpsl": "sl" + } + } + ] + }, + "sig": "", + "salt": 234567890, + "ts": 1767000010000 + }' + ``` + + The response returns one acknowledgement per submitted order. + + ```json theme={null} + [ + { + "status": "ok", + "oid": 1234567890, + "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" + }, + { "status": "ok", "oid": 1234567891 }, + { "status": "ok", "oid": 1234567892 } + ] + ``` + + Set `market` to `true` for market-style trigger execution. For limit trigger + execution, omit `market` and set `p` on the TP/SL child order. + + + +### Protect an Existing Position + +Add TP/SL orders to a position that is already open. Position TP/SL closes the +full position at trigger time, so it does not use a fixed quantity. + +Position TP/SL has a few placement rules: + +* The account must already hold a position in the instrument. +* The account can have at most one position take-profit and one position stop-loss per instrument. +* When the trigger fires, the exit submits immediately. Position TP/SL does not support limit prices. +* A position trigger is rejected if the current mark has already crossed it, because it would fire immediately. + + + + Place TP/SL orders for the full current position. + + ```ts theme={null} + const result = await session.placePositionTpSl({ + instrumentId: instrument.id, + takeProfit: { + triggerPrice: "70000", + }, + stopLoss: { + triggerPrice: "62000", + }, + }); + + const takeProfitOrderId = result.tpSl.takeProfit?.orderId; + const stopLossOrderId = result.tpSl.stopLoss?.orderId; + ``` + + `placePositionTpSl` sizes the exit at trigger time, so you do not pass a position + side or quantity. + + + + Place TP/SL orders for the full current position. + + ```python theme={null} + from polymarket import PerpsPositionTpSlTrigger + + result = await session.place_position_tp_sl( + instrument_id=instrument.id, + take_profit=PerpsPositionTpSlTrigger(trigger_price="70000"), + stop_loss=PerpsPositionTpSlTrigger(trigger_price="62000"), + ) + + # result.take_profit.order_id: PerpsOrderId + # result.stop_loss.order_id: PerpsOrderId + ``` + + `place_position_tp_sl` sizes the exit at trigger time, so you do not pass a + position side or quantity. + + + + Submit position-scoped TP/SL orders with `grp` set to `"position"`. Use + `qty: "0"` so the engine sizes the exit at trigger time. + + Set `buy` to the side that closes the position: `false` for a long position and + `true` for a short position. + + ```json theme={null} + { + "type": "createOrders", + "grp": "position", + "args": [ + { + "iid": 1, + "buy": false, + "qty": "0", + "ro": true, + "tr": { + "market": true, + "trp": "70000", + "tpsl": "tp" + } + }, + { + "iid": 1, + "buy": false, + "qty": "0", + "ro": true, + "tr": { + "market": true, + "trp": "62000", + "tpsl": "sl" + } + } + ] + } + ``` + + Sign the compact operation, not the structured JSON body. The TP/SL group is the + third compact element: + + ```ts theme={null} + ["createOrders", [takeProfitOrder, stopLossOrder], "position"]; + ``` + + Submit the signed request to `POST /v1/trade/orders` and keep the returned order + IDs for reconciliation. + + + +### Update or Cancel TP/SL + +TP/SL orders cannot be modified in place. To change a trigger price or execution +type, cancel the old trigger and create a replacement. + +* For position TP/SL, cancel the old trigger before creating another trigger of the same kind for the instrument. +* For a bracket whose entry is still resting, cancel the entry and place a new bracket with the updated triggers. +* For a bracket whose entry already filled, cancel the armed trigger and create position TP/SL as the replacement. + +Cancel-then-create is not atomic. Between the cancel and the replacement, the +position may be unprotected. + +## Configure Order Behavior + +So far, we have used immediate-or-cancel orders. Next, we’ll look at how to +control whether an order rests, fills immediately, or only adds liquidity. + +### Good-Til-Canceled Orders + +Use good-til-canceled orders when the order can rest on the book until it fills +or you cancel it. + + + + Set `timeInForce` to GTC. + + ```ts theme={null} + import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; + + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.GTC, + }); + ``` + + For a GTC order, `order.status` can be one of these values. + + | Status | Meaning | + | ------------------------------- | -------------------------------------------------------------------- | + | `PerpsOrderStatus.Open` | The order is resting on the book. | + | `PerpsOrderStatus.Filled` | The order fully filled before resting. | + | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | + + If a GTC order partially fills and rests, inspect `filledQuantity` and + `restingQuantity` on the returned order. + + + + Set `time_in_force` to `gtc`. + + ```python theme={null} + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + price="65000", + quantity="0.01", + time_in_force="gtc", + ) + + # result.order: PerpsOrder + ``` + + For a GTC order, `result.order.status` can be one of these values. + + | Status | Meaning | + | --------------- | -------------------------------------------------------------------- | + | `open` | The order is resting on the book. | + | `filled` | The order fully filled before resting. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + If a GTC order partially fills and rests, inspect + `result.order.filled_quantity` and `result.order.resting_quantity`. + + + + Set `tif` to `"gtc"`. + + ```json theme={null} + { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "gtc" + } + ] + } + ``` + + After the order is accepted, read order state from `GET /v1/account/orders` or + the private `orders` WebSocket channel. For a `gtc` order, `status` can be one + of these values. + + | Status | Meaning | + | --------------- | -------------------------------------------------------------------- | + | `open` | The order is resting on the book. | + | `filled` | The order fully filled before resting. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + If a `gtc` order partially fills and rests, inspect `filled_quantity` and + `resting_quantity`. + + + +### Post-Only Orders + +A post-only order is a special type of good-til-canceled order that only adds +liquidity. If it would cross the book and take liquidity, it is rejected instead. + + + + Set `postOnly: true` on a GTC order. + + ```ts theme={null} + import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; + + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.GTC, + postOnly: true, + }); + ``` + + For a post-only order, `order.status` can be one of these values. + + | Status | Meaning | + | ----------------------------------- | ---------------------------------------------------------- | + | `PerpsOrderStatus.Open` | The order was accepted and added to the book. | + | `PerpsOrderStatus.PostOnlyRejected` | The order would have crossed the book and taken liquidity. | + + + + Set `post_only=True` on a GTC order. + + ```python theme={null} + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + price="65000", + quantity="0.01", + time_in_force="gtc", + post_only=True, + ) + + # result.order: PerpsOrder + ``` + + For a post-only order, `result.order.status` can be one of these values. + + | Status | Meaning | + | -------------------- | ---------------------------------------------------------- | + | `open` | The order was accepted and added to the book. | + | `post_only_rejected` | The order would have crossed the book and taken liquidity. | + + + + Set `po: true` on a `gtc` order. + + ```json theme={null} + { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "gtc", + "po": true + } + ] + } + ``` + + For a post-only order, `status` can be one of these values. + + | Status | Meaning | + | -------------------- | ---------------------------------------------------------- | + | `open` | The order was accepted and added to the book. | + | `post_only_rejected` | The order would have crossed the book and taken liquidity. | + + + +### Fill-Or-Kill Orders + +Use fill-or-kill orders when the full quantity must fill immediately or cancel. +These orders do not rest on the book. + + + + Set `timeInForce` to FOK. + + ```ts theme={null} + import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; + + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + price: "65000", + quantity: "0.01", + timeInForce: PerpsTimeInForce.FOK, + }); + ``` + + For a FOK order, `order.status` can be one of these values. + + | Status | Meaning | + | ------------------------------- | -------------------------------------------------------------------- | + | `PerpsOrderStatus.Filled` | The full order quantity filled immediately. | + | `PerpsOrderStatus.FokUnfilled` | The full order quantity could not fill immediately, so it canceled. | + | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | + + + + Set `time_in_force` to `fok`. + + ```python theme={null} + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + price="65000", + quantity="0.01", + time_in_force="fok", + ) + + # result.order: PerpsOrder + ``` + + For a FOK order, `result.order.status` can be one of these values. + + | Status | Meaning | + | --------------- | -------------------------------------------------------------------- | + | `filled` | The full order quantity filled immediately. | + | `fok_unfilled` | The full order quantity could not fill immediately, so it canceled. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + + + Set `tif` to `"fok"`. + + ```json theme={null} + { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "fok" + } + ] + } + ``` + + For a `fok` order, `status` can be one of these values. + + | Status | Meaning | + | --------------- | -------------------------------------------------------------------- | + | `filled` | The full order quantity filled immediately. | + | `fok_unfilled` | The full order quantity could not fill immediately, so it canceled. | + | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | + + + +## Cancel Resting Orders + +Cancel resting orders when they are stale, conflict with updated strategy, or +should no longer remain on the book. Canceling a resting order does not close any +filled position. + + + + Cancel stale orders by order ID or by client order ID. + + + ```ts Order ID theme={null} + const result = await session.cancelOrder({ + orderId: order.id, + }); + ``` + + ```ts Client Order ID theme={null} + const result = await session.cancelOrder({ + clientOrderId: "7f9e4a2b6c8d0e1f1234567890abcdef", + }); + ``` + + + Use `result.status` to confirm whether the cancel request was accepted. + + | Status | Meaning | + | ------ | ------------------------------------ | + | `ok` | The cancel command was accepted. | + | `err` | The cancel command was not accepted. | + + Canceling a working order removes it from the book. + + + + Cancel stale orders by order ID or by client order ID. + + + ```python Order ID theme={null} + result = await session.cancel_order(order_id=order.id) + # result: PerpsCancelOrderResult + ``` + + ```python Client Order ID theme={null} + result = await session.cancel_order( + client_order_id="7f9e4a2b6c8d0e1f1234567890abcdef" + ) + # result: PerpsCancelOrderResult + ``` + + + Use `result.status` to confirm whether the cancel request was accepted. + + | Status | Meaning | + | ------ | ------------------------------------ | + | `ok` | The cancel command was accepted. | + | `err` | The cancel command was not accepted. | + + Canceling a working order removes it from the book. + + + + Cancel by order ID with `DELETE /v1/trade/orders`. + + ```bash theme={null} + curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "cancelOrders", + "args": [1234567890] + }, + "sig": "", + "salt": 234567892, + "ts": 1767000030000 + }' + ``` + + Cancel by client order ID with `DELETE /v1/trade/orders-coid`. + + ```bash theme={null} + curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders-coid" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "cancelOrdersCOID", + "args": ["7f9e4a2b6c8d0e1f1234567890abcdef"] + }, + "sig": "", + "salt": 234567893, + "ts": 1767000040000 + }' + ``` + + The response contains one cancel result per requested order. + + + ```json Success theme={null} + [ + { + "status": "ok", + "oid": 1234567890 + } + ] + ``` + + ```json Failure theme={null} + [ + { + "status": "err", + "error": "order_not_found" + } + ] + ``` + + + + +## Close a Position + +Closing a position is a new order in the opposite direction of the open position. +Use the full open position size to close. Use a smaller quantity to reduce +instead. Mark close orders reduce-only so they cannot flip the account into new +exposure if position state changes before execution. + +Reduce-only is a safeguard, not a sizing shortcut. You still choose the quantity: +use the full position size to close or a smaller quantity to reduce. If the order +would increase exposure, flip the position, or exceed the remaining closeable +size, it is rejected. + +| Current Position | Reduce-Only Buy | Reduce-Only Sell | +| ---------------- | ----------------- | ----------------- | +| Long | Rejected | Reduces or closes | +| Short | Reduces or closes | Rejected | +| No position | Rejected | Rejected | + +The remaining closeable size accounts for other resting reduce-only orders on +the same instrument. + + + + Find the current position by market symbol and parse its decimal size. + + ```ts theme={null} + import Big from "big.js"; + + const portfolio = await session.fetchPortfolio(); + const position = portfolio.positions.find((item) => item.symbol === "BTC-PERP"); + + if (!position) { + throw new Error("No open BTC-PERP position"); + } + + const size = new Big(position.size); + ``` + + Close a long position by selling the full size, or close a short position by + buying the absolute position size. + + + ```ts Close Long theme={null} + import { + OrderSide, + PerpsOrderStatus, + PerpsTimeInForce, + } from "@polymarket/client"; + + if (size.gt(0)) { + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.SELL, + quantity: position.size, + timeInForce: PerpsTimeInForce.IOC, + reduceOnly: true, + }); + + if (order.status === PerpsOrderStatus.Filled) { + // The position is fully closed. + } + } + ``` + + ```ts Close Short theme={null} + import { + OrderSide, + PerpsOrderStatus, + PerpsTimeInForce, + } from "@polymarket/client"; + + if (size.lt(0)) { + const order = await session.placeOrder({ + instrumentId: instrument.id, + side: OrderSide.BUY, + quantity: size.abs().toString(), + timeInForce: PerpsTimeInForce.IOC, + reduceOnly: true, + }); + + if (order.status === PerpsOrderStatus.Filled) { + // The position is fully closed. + } + } + ``` + + + These examples use an IOC order with no price and only treat the close as + complete when `order.status` is `PerpsOrderStatus.Filled`. Include a price when + you want to limit execution, or use FOK or GTC when the close should follow a + different order behavior. + + For reduce-only orders, also handle these statuses. + + | Status | Meaning | + | ------------------------------------ | ------------------------------------------------------------------------- | + | `PerpsOrderStatus.ReduceOnlyInvalid` | The order would not reduce the remaining closeable position. | + | `PerpsOrderStatus.ReduceOnlyExpired` | A resting reduce-only order was canceled after the position fully closed. | + + + + Find the current position by market symbol and inspect its decimal size. + + ```python theme={null} + portfolio = await session.fetch_portfolio() + position = next((item for item in portfolio.positions if item.symbol == "BTC-PERP"), None) + + if position is None: + raise RuntimeError("No open BTC-PERP position") + + # position: PerpsPosition + # position.size: Decimal + ``` + + Close a long position by selling the full size, or close a short position by + buying the absolute position size. + + + ```python Close Long theme={null} + if position.size > 0: + result = await session.place_order( + instrument_id=instrument.id, + side="SELL", + quantity=position.size, + time_in_force="ioc", + reduce_only=True, + ) + + if result.order.status == "filled": + # The position is fully closed. + pass + ``` + + ```python Close Short theme={null} + if position.size < 0: + result = await session.place_order( + instrument_id=instrument.id, + side="BUY", + quantity=abs(position.size), + time_in_force="ioc", + reduce_only=True, + ) + + if result.order.status == "filled": + # The position is fully closed. + pass + ``` + + + These examples use an IOC order with no price and only treat the close as + complete when `result.order.status` is `filled`. Include a price when you want to + limit execution, or use FOK or GTC when the close should follow a different order + behavior. + + For reduce-only orders, also handle these statuses. + + | Status | Meaning | + | --------------------- | ------------------------------------------------------------------------- | + | `reduce_only_invalid` | The order would not reduce the remaining closeable position. | + | `reduce_only_expired` | A resting reduce-only order was canceled after the position fully closed. | + + + + Fetch the portfolio and inspect the position `size` for the instrument. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + Use the sign of `positions[].size` to determine the closing side. A positive + size is a long position. A negative size is a short position. + + ```json Position excerpt theme={null} + { + "positions": [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "size": "0.01" + }, + { + "instrument_id": 2, + "symbol": "ETH-PERP", + "size": "-0.5" + } + ] + } + ``` + + Submit a `createOrders` operation in the opposite direction for the full size and + set `ro: true` so the order cannot increase or flip exposure. + + | Current `positions[].size` | Closing order `buy` | Closing order `qty` | Closing order `ro` | + | -------------------------- | ------------------- | ----------------------- | ------------------ | + | Positive | `false` | Current position size. | `true` | + | Negative | `true` | Absolute position size. | `true` | + + Closing can use `ioc`, `gtc`, or `fok` depending on the execution behavior you + want. + + For reduce-only orders, `status` can include these values. + + | Status | Meaning | + | --------------------- | ------------------------------------------------------------------------- | + | `reduce_only_invalid` | The order would not reduce the remaining closeable position. | + | `reduce_only_expired` | A resting reduce-only order was canceled after the position fully closed. | + + + +## Update Leverage + +Leverage controls how much notional exposure a position can carry relative to its +margin. Cross margin uses available account collateral for the position; +non-cross margin keeps the position isolated. Validate leverage against +`instrument.maxLeverage` and the current `instrument.riskTiers` before submitting +the change. + + + + + + Read the current account configuration before changing leverage. + + ```ts theme={null} + const [config] = await session.fetchAccountConfig({ + instrumentId: instrument.id, + }); + ``` + + `config` includes the current leverage and margin mode for the instrument. + + + + Update leverage and whether the position uses cross margin. The result confirms + the effective leverage configuration after the update. + + ```ts theme={null} + const result = await session.updateLeverage({ + instrumentId: instrument.id, + leverage: 5, + crossMargin: false, + }); + ``` + + The result includes the effective leverage configuration after the update. + + ```json Example Result theme={null} + { + "status": "ok", + "instrumentId": 1, + "leverage": 5, + "crossMargin": false + } + ``` + + + + + + + + Read the current account configuration before changing leverage. + + ```python theme={null} + configs = await session.fetch_account_config( + instrument_id=instrument.id, + ) + # configs[0]: PerpsAccountConfig + ``` + + Each config includes the current leverage and margin mode for the instrument. + + + + Update leverage and whether the position uses cross margin. The result confirms + the effective leverage configuration after the update. + + ```python theme={null} + result = await session.update_leverage( + instrument_id=instrument.id, + leverage=5, + cross_margin=False, + ) + # result: PerpsUpdateLeverageResult + ``` + + The result includes the effective leverage configuration after the update. + + ```json Example Result theme={null} + { + "status": "ok", + "instrument_id": 1, + "leverage": 5, + "cross_margin": false + } + ``` + + + + + + + + Read the current account configuration before changing leverage. + + ```bash theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/config" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + The account config includes the current `leverage` and margin mode for the + instrument. + + + + Create an `updateLeverage` operation with the instrument ID, leverage, and margin + mode. + + ```json theme={null} + { + "type": "updateLeverage", + "args": { + "iid": 1, + "lev": 5, + "cross": false + } + } + ``` + + + + Create the operation hash from the compact signable representation of the + operation. + + ```ts theme={null} + ["updateLeverage", [iid, lev, cross]]; + ``` + + Omit `undefined` array entries from the compact operation, then + MessagePack-encode it and hash the encoded bytes with `keccak256`. + + ```ts theme={null} + import { encode } from "@msgpack/msgpack"; + import { keccak256 } from "viem"; + + const signableOperation = ["updateLeverage", [1, 5, false]] as const; + + const opHash = keccak256(encode(signableOperation)); + ``` + + + + Create and sign an EIP-712 `Op` typed-data payload with the proxy signer private + key. + + ```ts Viem theme={null} + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(""); + + const signature = await account.signTypedData({ + domain: { + name: "Polymarket", + version: "1", + chainId: 137, + }, + primaryType: "Op", + types: { + Op: [ + { name: "data", type: "bytes32" }, + { name: "salt", type: "uint64" }, + { name: "ts", type: "uint64" }, + ], + }, + message: { + data: opHash, + salt: 234567894, + ts: 1767000050000, + }, + }); + ``` + + + + Submit the signed request to `PATCH /v1/trade/leverage`. + + ```bash theme={null} + curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/leverage" \ + -H "content-type: application/json" \ + -d '{ + "op": { + "type": "updateLeverage", + "args": { + "iid": 1, + "lev": 5, + "cross": false + } + }, + "sig": "", + "salt": 234567894, + "ts": 1767000050000 + }' + ``` + + + + The response confirms the effective leverage configuration after the update, or + returns an error if the update is rejected. + + + ```json Success theme={null} + { + "status": "ok", + "instrument_id": 1, + "leverage": 5, + "cross": false + } + ``` + + ```json Failure theme={null} + { + "status": "err", + "error": "invalid_leverage" + } + ``` + + + + + + +## Reconcile Trade State + +Keep local trading state in sync by starting from a local snapshot, applying +live updates, and reconciling again whenever the session tells you state may have +been missed. + +TP/SL orders appear alongside regular orders in open-order and order-history +reads. Track their lifecycle in addition to the position and fills they protect. + +| Lifecycle State | Meaning | +| --------------- | --------------------------------------------------------------- | +| Dormant | Waiting for a bracket entry order to fill in full. | +| Armed | Watching the mark price for the trigger. | +| Triggered | Fired and submitted the closing order. | +| Canceled | Removed by you, by parent cancellation, or by auto-cancel. | +| Cleared | Removed because the protected position closed or changed sides. | + + + + + + Fetch a snapshot when the session starts. + + ```ts theme={null} + async function fetchTradingSnapshot() { + const [balances, openOrders, orders, fills, portfolio] = await Promise.all([ + session.fetchBalances(), + session.fetchOpenOrders({ instrumentId: instrument.id }), + session.fetchOrders({ instrumentId: instrument.id }), + session.listFills().firstPage(), + session.fetchPortfolio(), + ]); + + return { balances, openOrders, orders, fills, portfolio }; + } + + let snapshot = await fetchTradingSnapshot(); + ``` + + + + Then apply trading live events while the session is open. + + ```ts theme={null} + for await (const event of session) { + switch (event.type) { + case "balance": { + // event.payload: PerpsBalance + break; + } + + case "order": { + // event.payload: PerpsOrder + break; + } + + case "fill": { + // event.payload: PerpsAccountFill + break; + } + + case "portfolio": { + // event.payload.positions contains current exposure. + break; + } + + case "tpsl": { + // event.payload: PerpsTpSlUpdateEvent["payload"] + break; + } + } + } + ``` + + + + When `event.type` is `"resync"`, use account reads as the first step to + reconcile local state before applying more local assumptions. + + ```ts theme={null} + if (event.type === "resync") { + snapshot = await fetchTradingSnapshot(); + } + ``` + + + + + + + + Fetch a snapshot when the session starts. + + ```python theme={null} + import asyncio + + + async def fetch_trading_snapshot(): + balances, open_orders, orders, fills, portfolio = await asyncio.gather( + session.fetch_balances(), + session.fetch_open_orders(instrument_id=instrument.id), + session.fetch_orders(instrument_id=instrument.id), + session.list_fills().first_page(), + session.fetch_portfolio(), + ) + + return { + "balances": balances, + "open_orders": open_orders, + "orders": orders, + "fills": fills, + "portfolio": portfolio, + } + + + snapshot = await fetch_trading_snapshot() + ``` + + + + Then apply trading live events while the session is open. + + ```python theme={null} + async for event in session: + if event.type == "balance": + # event.payload: PerpsBalance + pass + elif event.type == "order": + # event.payload: PerpsOrder + pass + elif event.type == "fill": + # event.payload: PerpsFill + pass + elif event.type == "portfolio": + # event.payload.positions contains current exposure. + pass + elif event.type == "tpsl": + # event.payload: PerpsTpSlUpdate + pass + ``` + + + + When `event.type` is `"resync"`, use account reads as the first step to + reconcile local state before applying more local assumptions. + + ```python theme={null} + if event.type == "resync": + snapshot = await fetch_trading_snapshot() + ``` + + + + + + + + Use account reads to build the local startup snapshot. + + + ```bash Balances theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/balances" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + ```bash Open Orders theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/open-orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + ```bash Orders theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + ```bash Fills theme={null} + curl -G "https://api.perpetuals.polymarket.com/v1/account/fills" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " \ + --data-urlencode "instrument_id=1" + ``` + + ```bash Portfolio theme={null} + curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ + -H "polymarket-proxy: " \ + -H "polymarket-secret: " + ``` + + + + + Then use the authenticated WebSocket session for live updates. Private WebSocket + frames can include balances, orders, fills, portfolio, and TP/SL updates. See + [Authenticated Sessions](/perps/authenticated-sessions) for the session + lifecycle. + + + ```json Balance theme={null} + { + "ch": "balances", + "data": { + "asset": "pUSD", + "balance": "1000", + "value": "1000" + }, + "sq": 1, + "ts": 1767000010000 + } + ``` + + ```json Order theme={null} + { + "ch": "orders", + "data": { + "oid": 1234567890, + "iid": 1, + "buy": true, + "p": "65000", + "qty": "0.01", + "tif": "gtc", + "po": false, + "status": "open", + "rest": "0.01", + "fill": "0", + "cts": 1767000010000, + "uts": 1767000010000, + "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" + }, + "sq": 2, + "ts": 1767000010000 + } + ``` + + ```json Fill theme={null} + { + "ch": "fills", + "data": { + "tid": 987654321, + "oid": 1234567890, + "iid": 1, + "side": "long", + "p": "65000", + "qty": "0.01", + "taker": true, + "fee": "0.26", + "fea": "pUSD", + "psz": "0", + "pep": "0", + "pnl": "0", + "liq": false, + "ts": 1767000010500, + "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" + }, + "sq": 3, + "ts": 1767000010500 + } + ``` + + ```json Portfolio theme={null} + { + "ch": "portfolio", + "data": { + "positions": [ + { + "instrument_id": 1, + "symbol": "BTC-PERP", + "size": "0.01", + "entry_price": "65000", + "leverage": 5, + "cross": false, + "initial_margin": "130", + "maintenance_margin": "13", + "position_value": "650", + "liquidation_price": "52000", + "unrealized_pnl": "0", + "return_on_equity": "0", + "cumulative_funding": "0" + } + ], + "margin": { + "total_account_value": "1000", + "total_initial_margin": "130", + "total_maintenance_margin": "13", + "total_position_value": "650" + }, + "withdrawable": "870", + "in_liquidation": false, + "timestamp": 1767000010500 + }, + "sq": 4, + "ts": 1767000010500 + } + ``` + + ```json TP/SL theme={null} + { + "ch": "tpsl::1", + "data": { + "oid": 1234567891, + "st": "armed" + }, + "sq": 5, + "ts": 1767000010500 + } + ``` + + + + + Track the `sq` sequence number for each channel. If a sequence number is skipped + or the connection reconnects, repeat the account reads above before relying on + local state. + + + + + +## Trading Fees + +Use the fee schedule when you need to display or account for the default maker +and taker trading fees. Fee rates are decimal strings, so `"0.0004"` means +`0.04%`. + +The schedule returns default (`$0` tier) rates. The account's actual rate on +each fill depends on its trailing 30-day volume tier. See +[Fees](/perps/learn-about-trading/fees) for the tier table. + + + + Fetch the current Perps fee schedule. + + ```ts theme={null} + const fees = await client.fetchPerpsFees(); + // fees: PerpsFeeScheduleEntry[] + ``` + + Each fee entry contains the market category and its default maker and taker fee + rates. + + ```ts theme={null} + type PerpsFeeScheduleEntry = { + category: PerpsInstrumentCategory; + makerFeeRate: DecimalString; + takerFeeRate: DecimalString; + }; + ``` + + `makerFeeRate` applies when an order adds liquidity, such as a resting or + post-only order. `takerFeeRate` applies when an order removes liquidity, such as + an immediately filled IOC order. + + + + Fetch the current Perps fee schedule. + + ```python theme={null} + fees = await client.fetch_perps_fees() + # fees: tuple[PerpsFeeScheduleEntry, ...] + ``` + + Each fee entry contains the market category and its default maker and taker fee + rates. + + `maker_fee_rate` applies when an order adds liquidity, such as a resting or + post-only order. `taker_fee_rate` applies when an order removes liquidity, such + as an immediately filled IOC order. + + + + Fetch the current Perps fee schedule. + + ```bash theme={null} + curl "https://api.perpetuals.polymarket.com/v1/info/fees" + ``` + + The response contains fee entries with default maker and taker fee rates. + + ```json theme={null} + { + "fee_schedule": [ + { + "instrument_type": "perpetual", + "category": "crypto", + "maker_fee_rate": "0.000125", + "taker_fee_rate": "0.0004" + } + ] + } + ``` + + `maker_fee_rate` applies when an order adds liquidity, such as a resting or + post-only order. `taker_fee_rate` applies when an order removes liquidity, such + as an immediately filled `ioc` order. + +