Add scraped Polymarket documentation (117 files)

This commit is contained in:
Etherdrake
2026-02-14 12:59:26 +01:00
parent 26c6b35691
commit 9263557be6
119 changed files with 27955 additions and 0 deletions
+408
View File
@@ -0,0 +1,408 @@
> ## 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.
# Authentication
> Understanding authentication using Polymarket's CLOB
The CLOB uses two levels of authentication: **L1 (Private Key)** and **L2 (API Key)**.
Either can be accomplished using the CLOB client or REST API. Authentication is not
required to access client public methods and public endpoints.
## Authentication Levels
<CardGroup cols={2}>
<Card title="L1 Authentication" icon="key" href="#l1-authentication">
Use the private key of the users account to sign messages
</Card>
<Card title="L2 Authentication" icon="lock" href="#l2-authentication">
Use API credentials (key, secret, passphrase) to authenticate requests to the CLOB
</Card>
</CardGroup>
***
## L1 Authentication
### What is L1?
L1 authentication uses the wallet's private key to sign an EIP-712 message used in the
request header. It proves ownership and control over the private key. The private key
stays in control of the user and all trading activity remains non-custodial.
### What This Enables
Access to L1 methods that create or derive L2 authentication headers.
* Create user API credentials
* Derive existing user API credentials
* Sign/create user's orders locally
### CLOB Client
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
const client = new ClobClient(
HOST,
CHAIN_ID,
signer // Signer enables L1 methods
);
// Gets API key, or else creates
const apiCreds = await client.createOrDeriveApiKey();
/*
apiCreds = {
"apiKey": "550e8400-e29b-41d4-a716-446655440000",
"secret": "base64EncodedSecretString",
"passphrase": "randomPassphraseString"
}
*/
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
import os
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
client = ClobClient(
host=host,
chain_id=chaind_id,
key=private_key # Signer enables L1 methods
)
# Gets API key, or else creates
api_creds = await client.create_or_derive_api_key()
# api_creds = {
# "apiKey": "550e8400-e29b-41d4-a716-446655440000",
# "secret": "base64EncodedSecretString",
# "passphrase": "randomPassphraseString"
# }
```
</Tab>
</Tabs>
<Warning>
**Never commit private keys to version control.** Always use environment
variables or secure key management systems.
</Warning>
***
### REST API
While we highly recommend using our provided clients to handle signing
and authentication, the following is for developers who choose NOT to
use our [Python](https://github.com/Polymarket/py-clob-client) or
[TypeScript](https://github.com/Polymarket/clob-client) clients.
When making direct REST API calls with L1 authentication, include these headers:
| Header | Required? | Description |
| ---------------- | --------- | ---------------------- |
| `POLY_ADDRESS` | yes | Polygon signer address |
| `POLY_SIGNATURE` | yes | CLOB EIP 712 signature |
| `POLY_TIMESTAMP` | yes | Current UNIX timestamp |
| `POLY_NONCE` | yes | Nonce. Default 0 |
The `POLY_SIGNATURE` is generated by signing the following EIP-712 struct.
<Accordion title="EIP-712 Signing Example">
<CodeGroup>
```typescript Typescript theme={null}
const domain = {
name: "ClobAuthDomain",
version: "1",
chainId: chainId, // Polygon Chain ID 137
};
const types = {
ClobAuth: [
{ name: "address", type: "address" },
{ name: "timestamp", type: "string" },
{ name: "nonce", type: "uint256" },
{ name: "message", type: "string" },
],
};
const value = {
address: signingAddress, // The Signing address
timestamp: ts, // The CLOB API server timestamp
nonce: nonce, // The nonce used
message: "This message attests that I control the given wallet",
};
const sig = await signer._signTypedData(domain, types, value);
```
```python Python theme={null}
domain = {
"name": "ClobAuthDomain",
"version": "1",
"chainId": chainId, # Polygon Chain ID 137
}
types = {
"ClobAuth": [
{"name": "address", "type": "address"},
{"name": "timestamp", "type": "string"},
{"name": "nonce", "type": "uint256"},
{"name": "message", "type": "string"},
]
}
value = {
"address": signingAddress, # The signing address
"timestamp": ts, # The CLOB API server timestamp
"nonce": nonce, # The nonce used
"message": "This message attests that I control the given wallet",
}
sig = await signer._signTypedData(domain, types, value)
```
</CodeGroup>
</Accordion>
Reference implementations:
* [TypeScript](https://github.com/Polymarket/clob-client/blob/main/src/signing/eip712.ts)
* [Python](https://github.com/Polymarket/py-clob-client/blob/main/py_clob_client/signing/eip712.py)
***
**Create API Credentials**
Create new API credentials for user.
```bash theme={null}
POST {clob-endpoint}/auth/api-key
```
**Derive API Credentials**
Derive API credentials for user.
```bash theme={null}
GET {clob-endpoint}/auth/derive-api-key
```
**Response**
```json theme={null}
{
"apiKey": "550e8400-e29b-41d4-a716-446655440000",
"secret": "base64EncodedSecretString",
"passphrase": "randomPassphraseString"
}
```
**You'll need all three values for L2 authentication.**
***
## L2 Authentication
### What is L2?
The next level of authentication is called L2, and it consists of the
user's API credentials (apiKey, secret, passphrase) generated from L1
authentication. These are used solely to authenticate requests made to
the CLOB API. Requests are signed using HMAC-SHA256.
### What This Enables
Access to L2 methods such as posting signed/created orders, viewing open
orders, cancelling open orders, getting trades
* Cancel or get user's open orders
* Check user's balances and allowances
* Post user's signed orders
### CLOB Client
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds, // Generated from L1 auth, API credentials enable L2 methods
1, // signatureType explained below
FUNDER // funder explained below
);
// Now you can trade!*
const order = await client.createAndPostOrder(
{ tokenID: "123456", price: 0.65, size: 100, side: "BUY" },
{ tickSize: "0.01", negRisk: false }
);
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
import os
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=api_creds, # Generated from L1 auth, API credentials enable L2 methods
signature_type=1, # signatureType explained below
funder=os.getenv("FUNDER_ADDRESS") # funder explained below
)
# Now you can trade!*
order = await client.create_and_post_order(
{"token_id": "123456", "price": 0.65, "size": 100, "side": "BUY"},
{"tick_size": "0.01", "neg_risk": False}
)
```
</Tab>
</Tabs>
<Info>
Even with L2 authentication headers, methods that create user orders still require the user to sign the order payload.
</Info>
***
### REST API
While we highly recommend using our provided clients to handle signing
and authentication, the following is for developers who choose NOT to
use our [Python](https://github.com/Polymarket/py-clob-client) or
[TypeScript](https://github.com/Polymarket/clob-client) clients.
When making direct REST API calls with L2 authentication, include these headers:
| Header | Required? | Description |
| ----------------- | --------- | ----------------------------- |
| `POLY_ADDRESS` | yes | Polygon signer address |
| `POLY_SIGNATURE` | yes | HMAC signature for request |
| `POLY_TIMESTAMP` | yes | Current UNIX timestamp |
| `POLY_API_KEY` | yes | User's API `apiKey` value |
| `POLY_PASSPHRASE` | yes | User's API `passphrase` value |
The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the user's API credentials `secret` value.
Reference implementations can be found in the [Typescript](https://github.com/Polymarket/clob-client/blob/main/src/signing/hmac.ts)
and [Python](https://github.com/Polymarket/py-clob-client/blob/main/py_clob_client/signing/hmac.py) clients.
***
## Signature Types and Funder
When initializing the L2 client, you must specify your wallet **signatureType** and the **funder** address which holds the funds:
| Signature Type | Value | Description |
| -------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| EOA | 0 | Standard Ethereum wallet (MetaMask). Funder is the EOA address and will need POL to pay gas on transactions. |
| POLY\_PROXY | 1 | A custom proxy wallet only used with users who logged in via Magic Link email/Google. Using this requires the user to have exported their PK from Polymarket.com and imported into your app. |
| GNOSIS\_SAFE | 2 | Gnosis Safe multisig proxy wallet (most common). Use this for any new or returning user who does not fit the other 2 types. |
<Tip>
The wallet addresses displayed to the user on Polymarket.com is the proxy wallet and should be used as the funder.
These can be deterministically derived or you can deploy them on behalf of the user.
These proxy wallets are automatically deployed for the user on their first login to Polymarket.com.
</Tip>
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: INVALID_SIGNATURE">
Your wallet's private key is incorrect or improperly formatted.
**Solution:**
* Verify your private key is a valid hex string (starts with "0x")
* Ensure you're using the correct key for the intended address
* Check that the key has proper permissions
</Accordion>
<Accordion title="Error: NONCE_ALREADY_USED">
The nonce you provided has already been used to create an API key.
**Solution:**
* Use `deriveApiKey()` with the same nonce to retrieve existing credentials
* Or use a different nonce with `createApiKey()`
</Accordion>
<Accordion title="Error: Invalid Funder Address">
Your funder address is incorrect or doesn't match your wallet.
**Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings).
If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication.
</Accordion>
<Accordion title="Lost API credentials but have nonce">
```typescript theme={null}
// Use deriveApiKey with the original nonce
const recovered = await client.deriveApiKey(originalNonce);
```
</Accordion>
<Accordion title="Lost both credentials and nonce">
Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials:
```typescript theme={null}
// Create fresh credentials with a new nonce
const newCreds = await client.createApiKey();
// Save the nonce this time!
```
</Accordion>
</AccordionGroup>
***
## See Client Methods
<CardGroup cols={2}>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-public">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="Builder Program Methods" icon="hammer" href="/developers/CLOB/clients/methods-builder">
Builder-specific operations for those in the Builders Program.
</Card>
</CardGroup>
@@ -0,0 +1,215 @@
> ## 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.
# Builder Methods
> These methods require builder API credentials and are only relevant for Builders Program order attribution.
## Client Initialization
Builder methods require the client to initialize with a separate authentication setup using
builder configs acquired from [Polymarket.com](https://polymarket.com/settings?tab=builder)
and the `@polymarket/builder-signing-sdk` package.
<Tabs>
<Tab title="Local Builder Credentials">
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig, BuilderApiKeyCreds } from "@polymarket/builder-signing-sdk";
const builderConfig = new BuilderConfig({
localBuilderCreds: new BuilderApiKeyCreds({
key: process.env.BUILDER_API_KEY,
secret: process.env.BUILDER_SECRET,
passphrase: process.env.BUILDER_PASS_PHRASE,
}),
});
const clobClient = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds, // The user's API credentials generated from L1 authentication
signatureType,
funderAddress,
undefined,
false,
builderConfig
);
```
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds
import os
builder_config = BuilderConfig(
local_builder_creds=BuilderApiKeyCreds(
key=os.getenv("BUILDER_API_KEY"),
secret=os.getenv("BUILDER_SECRET"),
passphrase=os.getenv("BUILDER_PASS_PHRASE"),
)
)
clob_client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=creds, # The user's API credentials generated from L1 authentication
signature_type=signature_type,
funder=funder,
builder_config=builder_config
)
```
</CodeGroup>
</Tab>
<Tab title="Remote Builder Signing">
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { BuilderConfig } from "@polymarket/builder-signing-sdk";
const builderConfig = new BuilderConfig({
remoteBuilderConfig: {url: "http://localhost:3000/sign"}
});
const clobClient = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds, // The user's API credentials generated from L1 authentication
signatureType,
funder,
undefined,
false,
builderConfig
);
```
```typescript Python theme={null}
from py_clob_client.client import ClobClient
from py_builder_signing_sdk.config import BuilderConfig, RemoteBuilderConfig
import os
builder_config = BuilderConfig(
remote_builder_config=RemoteBuilderConfig(
url="http://localhost:3000/sign"
)
)
clob_client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=creds, # The user's API credentials generated from L1 authentication
signature_type=signature_type,
funder=funder,
builder_config=builder_config
)
```
</CodeGroup>
</Tab>
</Tabs>
<Info>
[More information on builder signing](/developers/builders/order-attribution)
</Info>
***
## Methods
***
### getBuilderTrades()
Retrieves all trades attributed to your builder account.
This method allows builders to track which trades were routed through your platform.
```typescript Signature theme={null}
async getBuilderTrades(
params?: TradeParams,
): Promise<BuilderTradesPaginatedResponse>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
```
```typescript Response theme={null}
interface BuilderTradesPaginatedResponse {
trades: BuilderTrade[];
next_cursor: string;
limit: number;
count: number;
}
interface BuilderTrade {
id: string;
tradeType: string;
takerOrderHash: string;
builder: string;
market: string;
assetId: string;
side: string;
size: string;
sizeUsdc: string;
price: string;
status: string;
outcome: string;
outcomeIndex: number;
owner: string;
maker: string;
transactionHash: string;
matchTime: string;
bucketIndex: number;
fee: string;
feeUsdc: string;
err_msg?: string | null;
createdAt: string | null;
updatedAt: string | null;
}
```
***
### revokeBuilderApiKey()
Revokes the builder API key used to authenticate the current request.
After revocation, the key can no longer be used to make builder-authenticated requests.
```typescript Signature theme={null}
async revokeBuilderApiKey(): Promise<any>
```
***
## See Also
<CardGroup cols={2}>
<Card title="Builders Program Introduction" icon="hammer" href="/developers/builders/builder-intro">
Learn the benefits, how to implement, and more.
</Card>
<Card title="Implement Builders Signing" icon="key" href="/developers/builders/order-attribution">
Attribute orders to you, and pre-requisite to using the Relayer Client.
</Card>
<Card title="Relayer Client" icon="globe" href="/developers/builders/relayer-client">
The relayer executes other gasless transactions for your users, on your app.
</Card>
<Card title="Full Example Implementations" icon="puzzle" href="/developers/builders/examples">
Complete Next.js examples integrated with embedded wallets (Privy, Magic, Turnkey, wagmi)
</Card>
</CardGroup>
+295
View File
@@ -0,0 +1,295 @@
> ## 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.
# L1 Methods
> These methods require a wallet signer (private key) but do not require user API credentials. Use these for initial setup.
## Client Initialization
L1 methods require the client to initialize with a signer.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers";
const signer = new Wallet(process.env.PRIVATE_KEY);
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer // Signer required for L1 methods
);
// Ready to create user API credentials
const apiKey = await client.createApiKey();
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
import os
private_key = os.getenv("PRIVATE_KEY")
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=private_key # Signer required for L1 methods
)
# Ready to create user API credentials
api_key = await client.create_api_key()
```
</Tab>
</Tabs>
<Warning>
**Security:** Never commit private keys to version control. Always use environment variables or secure key management systems.
</Warning>
***
## API Key Management
***
### createApiKey()
Creates a new API key (L2 credentials) for the wallet signer. This generates a new set of credentials that can be used for L2 authenticated requests.
Each wallet can only have one active API key at a time. Creating a new key invalidates the previous one.
```typescript Signature theme={null}
async createApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
### deriveApiKey()
Derives an existing API key (L2 credentials) using a specific nonce. If you've already created API credentials with a particular nonce, this method will return the same credentials again.
```typescript Signature theme={null}
async deriveApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
### createOrDeriveApiKey()
Convenience method that attempts to derive an API key with the default nonce, or creates a new one if it doesn't exist. This is the recommended method for initial setup if you're unsure if credentials already exist.
```typescript Signature theme={null}
async createOrDeriveApiKey(nonce?: number): Promise<ApiKeyCreds>
```
```typescript Params theme={null}
`nonce` (optional): Custom nonce for deterministic key generation. If not provided, a default derivation is used.
```
```typescript Response theme={null}
interface ApiKeyCreds {
apiKey: string;
secret: string;
passphrase: string;
}
```
***
## Order Signing
### createOrder()
Create and sign a limit order locally without posting it to the CLOB.
Use this when you want to sign orders in advance or implement custom order submission logic.
Place order via L2 methods postOrder or postOrders.
```typescript Signature theme={null}
async createOrder(
userOrder: UserOrder,
options?: Partial<CreateOrderOptions>
): Promise<SignedOrder>
```
```typescript Params theme={null}
interface UserOrder {
tokenID: string;
price: number;
size: number;
side: Side;
feeRateBps?: number;
nonce?: number;
expiration?: number;
taker?: string;
}
interface CreateOrderOptions {
tickSize: TickSize;
negRisk?: boolean;
}
```
```typescript Response theme={null}
interface SignedOrder {
salt: string;
maker: string;
signer: string;
taker: string;
tokenId: string;
makerAmount: string;
takerAmount: string;
side: number; // 0 = BUY, 1 = SELL
expiration: string;
nonce: string;
feeRateBps: string;
signatureType: number;
signature: string;
}
```
***
### createMarketOrder()
Create and sign a market order locally without posting it to the CLOB.
Use this when you want to sign orders in advance or implement custom order submission logic.
Place orders via L2 methods postOrder or postOrders.
```typescript Signature theme={null}
async createMarketOrder(
userMarketOrder: UserMarketOrder,
options?: Partial<CreateOrderOptions>
): Promise<SignedOrder>
```
```typescript Params theme={null}
interface UserMarketOrder {
tokenID: string;
amount: number; // BUY: dollar amount, SELL: number of shares
side: Side;
price?: number; // Optional price limit
feeRateBps?: number;
nonce?: number;
taker?: string;
orderType?: OrderType.FOK | OrderType.FAK;
}
```
```typescript Response theme={null}
interface SignedOrder {
salt: string;
maker: string;
signer: string;
taker: string;
tokenId: string;
makerAmount: string;
takerAmount: string;
side: number; // 0 = BUY, 1 = SELL
expiration: string;
nonce: string;
feeRateBps: string;
signatureType: number;
signature: string;
}
```
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: INVALID_SIGNATURE">
Your wallet's private key is incorrect or improperly formatted.
**Solution:**
* Verify your private key is a valid hex string (starts with "0x")
* Ensure you're using the correct key for the intended address
* Check that the key has proper permissions
</Accordion>
<Accordion title="Error: NONCE_ALREADY_USED">
The nonce you provided has already been used to create an API key.
**Solution:**
* Use `deriveApiKey()` with the same nonce to retrieve existing credentials
* Or use a different nonce with `createApiKey()`
</Accordion>
<Accordion title="Error: Invalid Funder Address">
Your funder address is incorrect or doesn't match your wallet.
**Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings).
If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication.
</Accordion>
<Accordion title="Lost API credentials but have nonce">
```typescript theme={null}
// Use deriveApiKey with the original nonce
const recovered = await client.deriveApiKey(originalNonce);
```
</Accordion>
<Accordion title="Lost both credentials and nonce">
Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials:
```typescript theme={null}
// Create fresh credentials with a new nonce
const newCreds = await client.createApiKey();
// Save the nonce this time!
```
</Accordion>
</AccordionGroup>
***
## See Also
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="CLOB Quickstart Guide" icon="hammer" href="/developers/CLOB/quickstart">
Initialize the CLOB quickly and place your first order.
</Card>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-l2">
Access market data, orderbooks, and prices.
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
</CardGroup>
+650
View File
@@ -0,0 +1,650 @@
> ## 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.
# L2 Methods
> These methods require user API credentials (L2 headers). Use these for placing trades and managing user's positions.
***
## Client Initialization
L2 methods require the client to initialize with the signer, signatureType, user API credentials, and funder.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers";
const signer = new Wallet(process.env.PRIVATE_KEY)
const apiCreds = {
apiKey: process.env.API_KEY,
secret: process.env.SECRET,
passphrase: process.env.PASSPHRASE,
};
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
apiCreds,
2, // Deployed Safe proxy wallet
process.env.FUNDER_ADDRESS // Address of deployed Safe proxy wallet
);
// Ready to send authenticated requests to the CLOB API!
const order = await client.postOrder(signedOrder);
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
import os
api_creds = ApiCreds(
api_key=os.getenv("API_KEY"),
api_secret=os.getenv("SECRET"),
api_passphrase=os.getenv("PASSPHRASE")
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.getenv("PRIVATE_KEY"),
creds=api_creds,
signature_type=2, # Deployed Safe proxy wallet
funder=os.getenv("FUNDER_ADDRESS") # Address of deployed Safe proxy wallet
)
# Ready to send authenticated requests to the CLOB API!
order = await client.post_order(signed_order)
```
</Tab>
</Tabs>
***
## Order Creation and Management
***
### createAndPostOrder()
A convenience method that creates, prompts signature, and posts an order in a single call.
Use when you want to buy/sell at a specific price and can wait.
```typescript Signature theme={null}
async createAndPostOrder(
userOrder: UserOrder,
options?: Partial<CreateOrderOptions>,
orderType?: OrderType.GTC | OrderType.GTD, // Defaults to GTC
): Promise<OrderResponse>
```
```typescript Params theme={null}
interface UserOrder {
tokenID: string;
price: number;
size: number;
side: Side;
feeRateBps?: number;
nonce?: number;
expiration?: number;
taker?: string;
}
type CreateOrderOptions = {
tickSize: TickSize;
negRisk?: boolean;
}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### createAndPostMarketOrder()
A convenience method that creates, prompts signature, and posts an order in a single call.
Use when you want to buy/sell right now at whatever the market price is.
```typescript Signature theme={null}
async createAndPostMarketOrder(
userMarketOrder: UserMarketOrder,
options?: Partial<CreateOrderOptions>,
orderType?: OrderType.FOK | OrderType.FAK, // Defaults to FOK
): Promise<OrderResponse>
```
```typescript Params theme={null}
interface UserMarketOrder {
tokenID: string;
amount: number;
side: Side;
price?: number;
feeRateBps?: number;
nonce?: number;
taker?: string;
orderType?: OrderType.FOK | OrderType.FAK;
}
type CreateOrderOptions = {
tickSize: TickSize;
negRisk?: boolean;
}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### postOrder()
Posts a pre-signed and created order to the CLOB.
```typescript Signature theme={null}
async postOrder(
order: SignedOrder,
orderType?: OrderType, // Defaults to GTC
postOnly?: boolean, // Defaults to false
): Promise<OrderResponse>
```
```typescript Params theme={null}
order: SignedOrder // Pre-signed order from createOrder() or createMarketOrder()
orderType?: OrderType // Optional, defaults to GTC
postOnly?: boolean // Optional, defaults to false
```
```typescript Response theme={null}
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### postOrders()
Posts up to 15 pre-signed and created orders in a single batch.
```typescript theme={null}
async postOrders(
args: PostOrdersArgs[],
): Promise<OrderResponse[]>
```
```typescript Params theme={null}
interface PostOrdersArgs {
order: SignedOrder;
orderType: OrderType;
postOnly?: boolean; // Defaults to false
}
```
```typescript Response theme={null}
OrderResponse[] // Array of OrderResponse objects
interface OrderResponse {
success: boolean;
errorMsg: string;
orderID: string;
transactionsHashes: string[];
status: string;
takingAmount: string;
makingAmount: string;
}
```
***
### cancelOrder()
Cancels a single open order.
```typescript Signature theme={null}
async cancelOrder(orderID: string): Promise<CancelOrdersResponse>
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelOrders()
Cancels multiple orders in a single batch.
```typescript Signature theme={null}
async cancelOrders(orderIDs: string[]): Promise<CancelOrdersResponse>
```
```typescript Params theme={null}
orderIDs: string[];
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelAll()
Cancels all open orders.
```typescript Signature theme={null}
async cancelAll(): Promise<CancelResponse>
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
### cancelMarketOrders()
Cancels all open orders for a specific market.
```typescript Signature theme={null}
async cancelMarketOrders(
payload: OrderMarketCancelParams
): Promise<CancelOrdersResponse>
```
```typescript Parameters theme={null}
interface OrderMarketCancelParams {
market?: string;
asset_id?: string;
}
```
```typescript Response theme={null}
interface CancelOrdersResponse {
canceled: string[];
not_canceled: Record<string, any>;
}
```
***
## Order and Trade Queries
***
### getOrder()
Get details for a specific order.
```typescript Signature theme={null}
async getOrder(orderID: string): Promise<OpenOrder>
```
```typescript Response theme={null}
interface OpenOrder {
id: string;
status: string;
owner: string;
maker_address: string;
market: string;
asset_id: string;
side: string;
original_size: string;
size_matched: string;
price: string;
associate_trades: string[];
outcome: string;
created_at: number;
expiration: string;
order_type: string;
}
```
***
### getOpenOrders()
Get all your open orders.
```typescript Signature theme={null}
async getOpenOrders(
params?: OpenOrderParams,
only_first_page?: boolean,
): Promise<OpenOrdersResponse>
```
```typescript Params theme={null}
interface OpenOrderParams {
id?: string; // Order ID
market?: string; // Market condition ID
asset_id?: string; // Token ID
}
only_first_page?: boolean // Defaults to false
```
```typescript Response theme={null}
type OpenOrdersResponse = OpenOrder[];
interface OpenOrder {
id: string;
status: string;
owner: string;
maker_address: string;
market: string;
asset_id: string;
side: string;
original_size: string;
size_matched: string;
price: string;
associate_trades: string[];
outcome: string;
created_at: number;
expiration: string;
order_type: string;
}
```
***
### getTrades()
Get your trade history (filled orders).
```typescript Signature theme={null}
async getTrades(
params?: TradeParams,
only_first_page?: boolean,
): Promise<Trade[]>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
only_first_page?: boolean // Defaults to false
```
```typescript Response theme={null}
interface Trade {
id: string;
taker_order_id: string;
market: string;
asset_id: string;
side: Side;
size: string;
fee_rate_bps: string;
price: string;
status: string;
match_time: string;
last_update: string;
outcome: string;
bucket_index: number;
owner: string;
maker_address: string;
maker_orders: MakerOrder[];
transaction_hash: string;
trader_side: "TAKER" | "MAKER";
}
interface MakerOrder {
order_id: string;
owner: string;
maker_address: string;
matched_amount: string;
price: string;
fee_rate_bps: string;
asset_id: string;
outcome: string;
side: Side;
}
```
***
### getTradesPaginated()
Get trade history with pagination for large result sets.
```typescript Signature theme={null}
async getTradesPaginated(
params?: TradeParams,
): Promise<TradesPaginatedResponse>
```
```typescript Params theme={null}
interface TradeParams {
id?: string;
maker_address?: string;
market?: string;
asset_id?: string;
before?: string;
after?: string;
}
```
```typescript Response theme={null}
interface TradesPaginatedResponse {
trades: Trade[];
limit: number;
count: number;
}
```
***
## Balance and Allowances
***
### getBalanceAllowance()
Get your balance and allowance for specific tokens.
```typescript Signature theme={null}
async getBalanceAllowance(
params?: BalanceAllowanceParams
): Promise<BalanceAllowanceResponse>
```
```typescript Params theme={null}
interface BalanceAllowanceParams {
asset_type: AssetType;
token_id?: string;
}
enum AssetType {
COLLATERAL = "COLLATERAL",
CONDITIONAL = "CONDITIONAL",
}
```
```typescript Response theme={null}
interface BalanceAllowanceResponse {
balance: string;
allowance: string;
}
```
***
### updateBalanceAllowance()
Updates the cached balance and allowance for specific tokens.
```typescript Signature theme={null}
async updateBalanceAllowance(
params?: BalanceAllowanceParams
): Promise<void>
```
```typescript Params theme={null}
interface BalanceAllowanceParams {
asset_type: AssetType;
token_id?: string;
}
enum AssetType {
COLLATERAL = "COLLATERAL",
CONDITIONAL = "CONDITIONAL",
}
```
***
## API Key Management (L2)
### getApiKeys()
Get all API keys associated with your account.
```typescript Signature theme={null}
async getApiKeys(): Promise<ApiKeysResponse>
```
```typescript Response theme={null}
interface ApiKeysResponse {
apiKeys: ApiKeyCreds[];
}
interface ApiKeyCreds {
key: string;
secret: string;
passphrase: string;
}
```
***
### deleteApiKey()
Deletes (revokes) the currently authenticated API key.
**TypeScript Signature:**
```typescript theme={null}
async deleteApiKey(): Promise<any>
```
***
## Notifications
***
### getNotifications()
Retrieves all event notifications for the L2 authenticated user.
Records are removed automatically after 48 hours or if manually removed via dropNotifications().
```typescript Signature theme={null}
public async getNotifications(): Promise<Notification[]>
```
```typescript Response theme={null}
interface Notification {
id: number; // Unique notification ID
owner: string; // User's L2 credential apiKey or empty string for global notifications
payload: any; // Type-specific payload data
timestamp?: number; // Unix timestamp
type: number; // Notification type (see type mapping below)
}
```
**Notification Type Mapping**
| Name | Value | Description |
| ------------------ | ----- | ---------------------------------------- |
| Order Cancellation | 1 | User's order was canceled |
| Order Fill | 2 | User's order was filled (maker or taker) |
| Market Resolved | 4 | Market was resolved |
***
### dropNotifications()
Mark notifications as read/dismissed.
```typescript Signature theme={null}
public async dropNotifications(params?: DropNotificationParams): Promise<void>
```
```typescript Params theme={null}
interface DropNotificationParams {
ids: string[]; // Array of notification IDs to mark as read
}
```
***
## See Also
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-l2">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Private key authentication to create or derive API keys (L2 headers)
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
@@ -0,0 +1,235 @@
> ## 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.
# Methods Overview
> CLOB client methods require different levels of authentication. This reference is organized by what credentials you need to call each method.
<CardGroup cols={2}>
<Card title="Public Methods" icon="globe" href="/developers/CLOB/clients/methods-public">
Access market data, orderbooks, and prices.
</Card>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="Builder Program Methods" icon="hammer" href="/developers/CLOB/clients/methods-builder">
Builder-specific operations for those in the Builders Program.
</Card>
</CardGroup>
***
## Client Initialization by Use Case
<Tabs>
<Tab title="Get Market Data">
<CodeGroup>
```typescript TypeScript theme={null}
// No signer or credentials needed
const client = new ClobClient(
"https://clob.polymarket.com",
137
);
// All public methods available
const markets = await client.getMarkets();
const book = await client.getOrderBook(tokenId);
const price = await client.getPrice(tokenId, "BUY");
```
```python Python theme={null}
# No signer or credentials needed
client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137
)
# All public methods available
markets = client.get_markets()
book = client.get_order_book()
price = client.get_price()
```
</CodeGroup>
</Tab>
<Tab title="Generate User API Credentials">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with signer
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer
);
// All public and L1 methods available
const newCreds = createApiKey();
const derivedCreds = deriveApiKey();
const creds = createOrDeriveApiKey();
```
```python Python theme={null}
# Create client with signer
client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137
key="private_key"
)
# All public and L1 methods available
new_creds = client.create_api_key()
derived_creds = client.derive_api_key()
creds = client.create_or_derive_api_key()
```
</CodeGroup>
</Tab>
<Tab title="Create and Post Order">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with signer and creds
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
creds,
2, // Indicates Gnosis Safe proxy
funder // Safe wallet address holding funds
);
// All public, L1, and L2 methods available
const order = await client.createOrder({ /* ... */ });
const result = await client.postOrder(order);
const trades = await client.getTrades();
```
```python Python theme={null}
# Create client with signer and creds
const client = new ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key="private_key",
creds=creds,
signature_type=2, // Indicates Gnosis Safe proxy
funder="funder_address" // Safe wallet address holding funds
)
# All public, L1, and L2 methods available
order = client.create_order({ /* ... */ })
result = client.post_order(order)
trades = client.get_trades()
```
</CodeGroup>
</Tab>
<Tab title="Get Builders Orders">
<CodeGroup>
```typescript TypeScript theme={null}
// Create client with builder's authentication headers
import { BuilderConfig, BuilderApiKeyCreds } from "@polymarket/builder-signing-sdk";
const builderCreds: BuilderApiKeyCreds = {
key: process.env.POLY_BUILDER_API_KEY!,
secret: process.env.POLY_BUILDER_SECRET!,
passphrase: process.env.POLY_BUILDER_PASSPHRASE!
};
const builderConfig: BuilderConfig = {
localBuilderCreds: builderCreds
};
const client = new ClobClient(
"https://clob.polymarket.com",
137,
signer,
creds, // User's API credentials
2,
funder,
undefined,
false,
builderConfig // Builder's API credentials
);
// You can call all methods including builder methods
const builderTrades = await client.getBuilderTrades();
```
```python Python theme={null}
# Create client with builder's authentication headers
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds
builder_creds = BuilderApiKeyCreds(
key="POLY_BUILDER_API_KEY",
secret="POLY_BUILDER_SECRET,
passphrase="POLY_BUILDER_PASSPHRASE"
)
builder_config = BuilderConfig(
local_builder_creds=builder_creds
)
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key="private_key",
creds=creds, # User's API credentials
signature_type=2,
funder=funder_address,
builder_config=builder_config # Builder's API credentials
)
# You can call all methods including builder methods
builder_trades = client.get_builder_trades()
```
</CodeGroup>
Learn more about the Builders Program and Relay Client here
</Tab>
</Tabs>
***
## Resources
<CardGroup cols={3}>
<Card title="TypeScript Client" icon="github" href="https://github.com/Polymarket/clob-client">
Open source TypeScript client on GitHub
</Card>
<Card title="Python Client" icon="github" href="https://github.com/Polymarket/py-clob-client">
Open source Python client for GitHub
</Card>
<Card title="Rust Client" icon="github" href="https://github.com/Polymarket/rs-clob-client">
Open source Rust client on GitHub
</Card>
<Card title="TypeScript Examples" icon="code" href="https://github.com/Polymarket/clob-client/tree/main/examples">
TypeScript client method examples
</Card>
<Card title="Python Examples" icon="python" href="https://github.com/Polymarket/py-clob-client/tree/main/examples">
Python client method examples
</Card>
<Card title="Rust Examples" icon="rust" href="https://github.com/Polymarket/rs-clob-client/tree/main/examples">
Rust client method examples
</Card>
<Card title="CLOB Rest API Reference" icon="hammer" href="/api-reference/orderbook/get-order-book-summary">
Complete REST endpoint documentation
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
@@ -0,0 +1,717 @@
> ## 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.
# Public Methods
> These methods can be called without a signer or user credentials. Use these for reading market data, prices, and order books.
## Client Initialization
Public methods require the client to initialize with the host URL and Polygon chain ID.
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
import { ClobClient } from "@polymarket/clob-client";
const client = new ClobClient(
"https://clob.polymarket.com",
137
);
// Ready to call public methods
const markets = await client.getMarkets();
```
</Tab>
<Tab title="Python">
```python theme={null}
from py_clob_client.client import ClobClient
client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137
)
# Ready to call public methods
markets = await client.get_markets()
```
</Tab>
</Tabs>
***
## Health Check
***
### getOk()
Health check endpoint to verify the CLOB service is operational.
```typescript Signature theme={null}
async getOk(): Promise<any>
```
***
## Markets
***
### getMarket()
Get details for a single market by condition ID.
```typescript Signature theme={null}
async getMarket(conditionId: string): Promise<Market>
```
```typescript Response theme={null}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
```
***
### getMarkets()
Get details for multiple markets paginated.
```typescript Signature theme={null}
async getMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: Market[];
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
```
***
### getSimplifiedMarkets()
Get simplified market data paginated for faster loading.
```typescript Signature theme={null}
async getSimplifiedMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: SimplifiedMarket[];
}
interface SimplifiedMarket {
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
rewards: {
rates: any | null;
min_size: number;
max_spread: number;
};
tokens: SimplifiedToken[];
}
interface SimplifiedToken {
outcome: string;
price: number;
token_id: string;
}
```
***
### getSamplingMarkets()
```typescript Signature theme={null}
async getSamplingMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: Market[];
}
interface Market {
accepting_order_timestamp: string | null;
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
description: string;
enable_order_book: boolean;
end_date_iso: string;
fpmm: string;
game_start_time: string;
icon: string;
image: string;
is_50_50_outcome: boolean;
maker_base_fee: number;
market_slug: string;
minimum_order_size: number;
minimum_tick_size: number;
neg_risk: boolean;
neg_risk_market_id: string;
neg_risk_request_id: string;
notifications_enabled: boolean;
question: string;
question_id: string;
rewards: {
max_spread: number;
min_size: number;
rates: any | null;
};
seconds_delay: number;
tags: string[];
taker_base_fee: number;
tokens: MarketToken[];
}
interface MarketToken {
outcome: string;
price: number;
token_id: string;
winner: boolean;
}
```
***
### getSamplingSimplifiedMarkets()
```typescript Signature theme={null}
async getSamplingSimplifiedMarkets(): Promise<PaginationPayload>
```
```typescript Response theme={null}
interface PaginationPayload {
limit: number;
count: number;
data: SimplifiedMarket[];
}
interface SimplifiedMarket {
accepting_orders: boolean;
active: boolean;
archived: boolean;
closed: boolean;
condition_id: string;
rewards: {
rates: any | null;
min_size: number;
max_spread: number;
};
tokens: SimplifiedToken[];
}
interface SimplifiedToken {
outcome: string;
price: number;
token_id: string;
}
```
***
## Order Books and Prices
***
### calculateMarketPrice()
```typescript Signature theme={null}
async calculateMarketPrice(
tokenID: string,
side: Side,
amount: number,
orderType: OrderType = OrderType.FOK
): Promise<number>
```
```typescript Params theme={null}
enum OrderType {
GTC = "GTC", // Good Till Cancelled
FOK = "FOK", // Fill or Kill
GTD = "GTD", // Good Till Date
FAK = "FAK", // Fill and Kill
}
enum Side {
BUY = "BUY",
SELL = "SELL",
}
```
```typescript Response theme={null}
number // calculated market price
```
***
### getOrderBook()
Get the order book for a specific token ID.
```typescript Signature theme={null}
async getOrderBook(tokenID: string): Promise<OrderBookSummary>
```
```typescript Response theme={null}
interface OrderBookSummary {
market: string;
asset_id: string;
timestamp: string;
bids: OrderSummary[];
asks: OrderSummary[];
min_order_size: string;
tick_size: string;
neg_risk: boolean;
hash: string;
}
interface OrderSummary {
price: string;
size: string;
}
```
***
### getOrderBooks()
Get order books for multiple token IDs.
```typescript Signature theme={null}
async getOrderBooks(params: BookParams[]): Promise<OrderBookSummary[]>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side.BUY or Side.SELL
}
```
```typescript Response theme={null}
OrderBookSummary[]
```
***
### getPrice()
Get the current best price for buying or selling a token ID.
```typescript Signature theme={null}
async getPrice(
tokenID: string,
side: "BUY" | "SELL"
): Promise<any>
```
```typescript Response theme={null}
{
price: string;
}
```
***
### getPrices()
Get the current best prices for multiple token IDs.
```typescript Signature theme={null}
async getPrices(params: BookParams[]): Promise<PricesResponse>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side.BUY or Side.SELL
}
```
```typescript Response theme={null}
interface TokenPrices {
BUY?: string;
SELL?: string;
}
type PricesResponse = {
[tokenId: string]: TokenPrices;
}
```
***
### getMidpoint()
Get the midpoint price (average of best bid and best ask) for a token ID.
```typescript Signature theme={null}
async getMidpoint(tokenID: string): Promise<any>
```
```typescript Response theme={null}
{
mid: string;
}
```
***
### getMidpoints()
Get the midpoint prices (average of best bid and best ask) for multiple token IDs.
```typescript Signature theme={null}
async getMidpoints(params: BookParams[]): Promise<any>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side; // Side is ignored
}
```
```typescript Response theme={null}
{
[tokenId: string]: string;
}
```
***
### getSpread()
Get the spread (difference between best ask and best bid) for a token ID.
```typescript Signature theme={null}
async getSpread(tokenID: string): Promise<SpreadResponse>
```
```typescript Response theme={null}
interface SpreadResponse {
spread: string;
}
```
***
### getSpreads()
Get the spreads (difference between best ask and best bid) for multiple token IDs.
```typescript Signature theme={null}
async getSpreads(params: BookParams[]): Promise<SpreadsResponse>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side;
}
```
```typescript Response theme={null}
type SpreadsResponse = {
[tokenId: string]: string;
}
```
***
### getPricesHistory()
Get historical price data for a token.
```typescript Signature theme={null}
async getPricesHistory(params: PriceHistoryFilterParams): Promise<MarketPrice[]>
```
```typescript Params theme={null}
interface PriceHistoryFilterParams {
market: string; // tokenID
startTs?: number;
endTs?: number;
fidelity?: number;
interval: PriceHistoryInterval;
}
enum PriceHistoryInterval {
MAX = "max",
ONE_WEEK = "1w",
ONE_DAY = "1d",
SIX_HOURS = "6h",
ONE_HOUR = "1h",
}
```
```typescript Response theme={null}
interface MarketPrice {
t: number; // timestamp
p: number; // price
}
```
***
## Trades
***
### getLastTradePrice()
Get the price of the most recent trade for a token.
```typescript Signature theme={null}
async getLastTradePrice(tokenID: string): Promise<LastTradePrice>
```
```typescript Response theme={null}
interface LastTradePrice {
price: string;
side: string;
}
```
***
### getLastTradesPrices()
Get the price of the most recent trade for a token.
```typescript Signature theme={null}
async getLastTradesPrices(params: BookParams[]): Promise<LastTradePriceWithToken[]>
```
```typescript Params theme={null}
interface BookParams {
token_id: string;
side: Side;
}
```
```typescript Response theme={null}
interface LastTradePriceWithToken {
price: string;
side: string;
token_id: string;
}
```
***
### getMarketTradesEvents
```typescript Signature theme={null}
async getMarketTradesEvents(conditionID: string): Promise<MarketTradeEvent[]>
```
```typescript Response theme={null}
interface MarketTradeEvent {
event_type: string;
market: {
condition_id: string;
asset_id: string;
question: string;
icon: string;
slug: string;
};
user: {
address: string;
username: string;
profile_picture: string;
optimized_profile_picture: string;
pseudonym: string;
};
side: Side;
size: string;
fee_rate_bps: string;
price: string;
outcome: string;
outcome_index: number;
transaction_hash: string;
timestamp: string;
}
```
## Market Parameters
***
### getFeeRateBps()
Get the fee rate in basis points for a token.
```typescript Signature theme={null}
async getFeeRateBps(tokenID: string): Promise<number>
```
```typescript Response theme={null}
number
```
***
### getTickSize()
Get the tick size (minimum price increment) for a market.
```typescript Signature theme={null}
async getTickSize(tokenID: string): Promise<TickSize>
```
```typescript Response theme={null}
type TickSize = "0.1" | "0.01" | "0.001" | "0.0001";
```
***
### getNegRisk()
Check if a market uses negative risk (binary complementary tokens).
```typescript Signature theme={null}
async getNegRisk(tokenID: string): Promise<boolean>
```
```typescript Response theme={null}
boolean
```
***
## Time & Server Info
### getServerTime()
Get the current server timestamp.
```typescript Signature theme={null}
async getServerTime(): Promise<number>
```
```typescript Response theme={null}
number // Unix timestamp in seconds
```
***
## See Also
<CardGroup cols={2}>
<Card title="L1 Methods" icon="key" href="/developers/CLOB/clients/methods-l1">
Private key authentication to create or derive API keys (L2 headers).
</Card>
<Card title="L2 Methods" icon="lock" href="/developers/CLOB/clients/methods-l2">
Manage and close orders. Creating orders requires signer.
</Card>
<Card title="CLOB Rest API Reference" icon="hammer" href="/api-reference/orderbook/get-order-book-summary">
Complete REST endpoint documentation
</Card>
<Card title="Web Socket API" icon="hammer" href="/developers/CLOB/websocket/wss-overview">
Real-time market data streaming
</Card>
</CardGroup>
+156
View File
@@ -0,0 +1,156 @@
> ## 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
> Check geographic restrictions before placing orders on Polymarket's CLOB
## Overview
Polymarket restricts order placement from certain geographic locations due to regulatory requirements and compliance with international sanctions.
Before placing orders, builders should verify the location.
<Warning>
Orders submitted from blocked regions will be rejected. Implement geoblock checks
in your application to provide users with appropriate feedback before they attempt to trade.
</Warning>
***
## Server Infrastructure
* **Primary Servers**: eu-west-2
* **Closest Non-Georestricted Region**: eu-west-1
***
## Geoblock Endpoint
Check the geographic eligibility of the requesting IP address:
```bash theme={null}
GET https://polymarket.com/api/geoblock
```
### Response
```typescript theme={null}
{
"blocked": boolean;
"ip": string;
"country": string;
"region": string;
}
```
| Field | Type | Description |
| --------- | ------- | ----------------------------------------------- |
| `blocked` | boolean | Whether the user is blocked from placing orders |
| `ip` | string | Detected IP address |
| `country` | string | ISO 3166-1 alpha-2 country code |
| `region` | string | Region/state code |
***
## Blocked Countries
The following **33 countries** are completely restricted from placing orders on Polymarket:
| Country Code | Country Name |
| ------------ | ------------------------------------ |
| AU | Australia |
| BE | Belgium |
| BY | Belarus |
| BI | Burundi |
| CF | Central African Republic |
| CD | Congo (Kinshasa) |
| CU | Cuba |
| DE | Germany |
| ET | Ethiopia |
| FR | France |
| GB | United Kingdom |
| IR | Iran |
| IQ | Iraq |
| IT | Italy |
| KP | North Korea |
| LB | Lebanon |
| LY | Libya |
| MM | Myanmar |
| NI | Nicaragua |
| PL | Poland |
| RU | Russia |
| SG | Singapore |
| SO | Somalia |
| SS | South Sudan |
| SD | Sudan |
| SY | Syria |
| TH | Thailand |
| TW | Taiwan |
| UM | United States Minor Outlying Islands |
| US | United States |
| VE | Venezuela |
| YE | Yemen |
| ZW | Zimbabwe |
***
## Blocked Regions
In addition to fully blocked countries, the following specific regions within otherwise accessible countries are also restricted:
| Country | Region | Region Code |
| ------------ | ------- | ----------- |
| Canada (CA) | Ontario | ON |
| Ukraine (UA) | Crimea | 43 |
| Ukraine (UA) | Donetsk | 14 |
| Ukraine (UA) | Luhansk | 09 |
***
## Usage Examples
<Tabs>
<Tab title="TypeScript">
```typescript theme={null}
interface GeoblockResponse {
blocked: boolean;
ip: string;
country: string;
region: string;
}
async function checkGeoblock(): Promise<GeoblockResponse> {
const response = await fetch("https://polymarket.com/api/geoblock");
return response.json();
}
// Usage
const geo = await checkGeoblock();
if (geo.blocked) {
console.log(`Trading not available in ${geo.country}`);
} else {
console.log("Trading available");
}
```
</Tab>
<Tab title="Python">
```python theme={null}
import requests
def check_geoblock() -> dict:
response = requests.get("https://polymarket.com/api/geoblock")
return response.json()
# Usage
geo = check_geoblock()
if geo["blocked"]:
print(f"Trading not available in {geo['country']}")
else:
print("Trading available")
```
</Tab>
</Tabs>
+56
View File
@@ -0,0 +1,56 @@
> ## 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.
# CLOB Introduction
Welcome to the Polymarket Order Book API! This documentation provides overviews, explanations, examples, and annotations to simplify interaction with the order book. The following sections detail the Polymarket Order Book and the API usage.
## System
Polymarket's Order Book, or CLOB (Central Limit Order Book), is hybrid-decentralized. It includes an operator for off-chain matching/ordering, with settlement executed on-chain, non-custodially, via signed order messages.
The exchange uses a custom Exchange contract facilitating atomic swaps between binary Outcome Tokens (CTF ERC1155 assets and ERC20 PToken assets) and collateral assets (ERC20), following signed limit orders. Designed for binary markets, the contract enables complementary tokens to match across a unified order book.
Orders are EIP712-signed structured data. Matched orders have one maker and one or more takers, with price improvements benefiting the taker. The operator handles off-chain order management and submits matched trades to the blockchain for on-chain execution.
## API
The Polymarket Order Book API enables market makers and traders to programmatically manage market orders. Orders of any amount can be created, listed, fetched, or read from the market order books. Data includes all available markets, market prices, and order history via REST and WebSocket endpoints.
## Security
Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)).
The operator's privileges are limited to order matching, non-censorship, and ensuring correct ordering. Operators can't set prices or execute unauthorized trades. Users can cancel orders on-chain independently if trust issues arise.
## Fees
### Schedule
> Subject to change
| Volume Level | Maker Fee Base Rate (bps) | Taker Fee Base Rate (bps) |
| ------------ | ------------------------- | ------------------------- |
| >0 USDC | 0 | 0 |
### Overview
Fees apply symmetrically in output assets (proceeds). This symmetry ensures fairness and market integrity. Fees are calculated differently depending on whether you are buying or selling:
* **Selling outcome tokens (base) for collateral (quote):**
$$
feeQuote = baseRate \times \min(price, 1 - price) \times size
$$
* **Buying outcome tokens (base) with collateral (quote):**
$$
feeBase = baseRate \times \min(price, 1 - price) \times \frac{size}{price}
$$
## Additional Resources
* [Exchange contract source code](https://github.com/Polymarket/ctf-exchange/tree/main/src)
* [Exchange contract documentation](https://github.com/Polymarket/ctf-exchange/blob/main/docs/Overview.md)
@@ -0,0 +1,173 @@
> ## 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(s)
> Multiple endpoints to cancel a single order, multiple orders, all orders or all orders from a single market.
# Cancel an single Order
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel an order.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/order`
### Request Payload Parameters
| Name | Required | Type | Description |
| ------- | -------- | ------ | --------------------- |
| orderID | yes | string | ID of order to cancel |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel(order_id="0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88")
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelOrder({
orderID:
"0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel Multiple Orders
<Tip> This endpoint requires a L2 Header. </Tip>
**HTTP REQUEST**
`DELETE /<clob-endpoint>/orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| ---- | -------- | --------- | --------------------------- |
| null | yes | string\[] | IDs of the orders to cancel |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_orders(["0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88", "0xaaaa..."])
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelOrders([
"0x38a73eed1e6d177545e9ab027abddfb7e08dbe975fa777123b1752d203d6ac88",
"0xaaaa...",
]);
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel ALL Orders
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel all open orders posted by a user.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/cancel-all`
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_all()
print(resp)
print("Done!")
```
```javascript Typescript theme={null}
async function main() {
const resp = await clobClient.cancelAll();
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
# Cancel orders from market
<Tip> This endpoint requires a L2 Header. </Tip>
Cancel orders from market.
**HTTP REQUEST**
`DELETE /<clob-endpoint>/cancel-market-orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------ | -------------------------- |
| market | no | string | condition id of the market |
| asset\_id | no | string | id of the asset/token |
### Response Format
| Name | Type | Description |
| ------------- | --------- | -------------------------------------------------------------------------- |
| canceled | string\[] | list of canceled orders |
| not\_canceled | {} | a order id -> reason map that explains why that order couldn't be canceled |
<CodeGroup>
```python Python theme={null}
resp = client.cancel_market_orders(market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", asset_id="52114319501245915516055106046884209969926127482827954674443846427813813222426")
print(resp)
```
```javascript Typescript theme={null}
async function main() {
// Send it to the server
const resp = await clobClient.cancelMarketOrders({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
asset_id:
"52114319501245915516055106046884209969926127482827954674443846427813813222426",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</CodeGroup>
@@ -0,0 +1,96 @@
> ## 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 Order Reward Scoring
> Check if an order is eligble or scoring for Rewards purposes
<Tip> This endpoint requires a L2 Header. </Tip>
Returns a boolean value where it is indicated if an order is scoring or not.
**HTTP REQUEST**
`GET /<clob-endpoint>/order-scoring?order_id={...}`
### Request Parameters
| Name | Required | Type | Description |
| ------- | -------- | ------ | ------------------------------------ |
| orderId | yes | string | id of order to get information about |
### Response Format
| Name | Type | Description |
| ---- | ------------- | ------------------ |
| null | OrdersScoring | order scoring data |
An `OrdersScoring` object is of the form:
| Name | Type | Description |
| ------- | ------- | ---------------------------------------- |
| scoring | boolean | indicates if the order is scoring or not |
# Check if some orders are scoring
> This endpoint requires a L2 Header.
Returns to a dictionary with boolean value where it is indicated if an order is scoring or not.
**HTTP REQUEST**
`POST /<clob-endpoint>/orders-scoring`
### Request Parameters
| Name | Required | Type | Description |
| -------- | -------- | --------- | ------------------------------------------ |
| orderIds | yes | string\[] | ids of the orders to get information about |
### Response Format
| Name | Type | Description |
| ---- | ------------- | ------------------- |
| null | OrdersScoring | orders scoring data |
An `OrdersScoring` object is a dictionary that indicates the order by if it score.
<RequestExample>
```python Python theme={null}
scoring = client.is_order_scoring(
OrderScoringParams(
orderId="0x..."
)
)
print(scoring)
scoring = client.are_orders_scoring(
OrdersScoringParams(
orderIds=["0x..."]
)
)
print(scoring)
```
```javascript Typescript theme={null}
async function main() {
const scoring = await clobClient.isOrderScoring({
orderId: "0x...",
});
console.log(scoring);
}
main();
async function main() {
const scoring = await clobClient.areOrdersScoring({
orderIds: ["0x..."],
});
console.log(scoring);
}
main();
```
</RequestExample>
@@ -0,0 +1,234 @@
> ## 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 Multiple Orders (Batching)
> Instructions for placing multiple orders(Batch)
<Tip> This endpoint requires a L2 Header </Tip>
Polymarkets CLOB supports batch orders, allowing you to place up to `15` orders in a single request. Before using this feature, make sure you're comfortable placing a single order first. You can find the documentation for that [here.](/developers/CLOB/orders/create-order)
**HTTP REQUEST**
`POST /<clob-endpoint>/orders`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------------- | ---------------------------------------------------------------- |
| PostOrder | yes | PostOrders\[] | list of signed order objects (Signed Order + Order Type + Owner) |
A `PostOrder` object is the form:
| Name | Required | Type | Description |
| --------- | -------- | ------- | -------------------------------------------------------------------------------------------- |
| order | yes | order | See below table for details on crafting this object |
| orderType | yes | string | order type ("FOK", "GTC", "GTD", "FAK") |
| owner | yes | string | api key of order owner |
| postOnly | no | boolean | if `true`, the order will only rest on the book and not match immediately (default: `false`) |
An `order` object is the form:
| Name | Required | Type | Description |
| ------------- | -------- | ------- | -------------------------------------------------- |
| salt | yes | integer | random salt used to create unique order |
| maker | yes | string | maker address (funder) |
| signer | yes | string | signing address |
| taker | yes | string | taker address (operator) |
| tokenId | yes | string | ERC1155 token ID of conditional token being traded |
| makerAmount | yes | string | maximum amount maker is willing to spend |
| takerAmount | yes | string | minimum amount taker will pay the maker in return |
| expiration | yes | string | unix expiration timestamp |
| nonce | yes | string | maker's exchange nonce of the order is associated |
| feeRateBps | yes | string | fee rate basis points as required by the operator |
| side | yes | string | buy or sell enum index |
| signatureType | yes | integer | signature type enum index |
| signature | yes | string | hex encoded signature |
### Order types
* **FOK**: A Fill-Or-Kill order is an market order to buy (in dollars) or sell (in shares) shares that must be executed immediately in its entirety; otherwise, the entire order will be cancelled.
* **FAK**: A Fill-And-Kill order is a market order to buy (in dollars) or sell (in shares) that will be executed immediately for as many shares as are available; any portion not filled at once is cancelled.
* **GTC**: A Good-Til-Cancelled order is a limit order that is active until it is fulfilled or cancelled.
* **GTD**: A Good-Til-Date order is a type of order that is active until its specified date (UTC seconds timestamp), unless it has already been fulfilled or cancelled. There is a security threshold of one minute. If the order needs to expire in 90 seconds the correct expiration value is: now + 1 minute + 30 seconds
### Response Format
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| success | boolean | boolean indicating if server-side err (`success = false`) -> server-side error |
| errorMsg | string | error message in case of unsuccessful placement (in case `success = false`, e.g. `client-side error`, the reason is in `errorMsg`) |
| orderId | string | id of order |
| orderHashes | string\[] | hash of settlement transaction order was marketable and triggered a match |
### Insert Error Messages
If the `errorMsg` field of the response object from placement is not an empty string, the order was not able to be immediately placed. This might be because of a delay or because of a failure. If the `success` is not `true`, then there was an issue placing the order. The following `errorMessages` are possible:
#### Error
| Error | Success | Message | Description |
| ------------------------------------ | ------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| INVALID\_ORDER\_MIN\_TICK\_SIZE | yes | order is invalid. Price breaks minimum tick size rules | order price isn't accurate to correct tick sizing |
| INVALID\_ORDER\_MIN\_SIZE | yes | order is invalid. Size lower than the minimum | order size must meet min size threshold requirement |
| INVALID\_ORDER\_DUPLICATED | yes | order is invalid. Duplicated. Same order has already been placed, can't be placed again | |
| INVALID\_ORDER\_NOT\_ENOUGH\_BALANCE | yes | not enough balance / allowance | funder address doesn't have sufficient balance or allowance for order |
| INVALID\_ORDER\_EXPIRATION | yes | invalid expiration | expiration field expresses a time before now |
| INVALID\_ORDER\_ERROR | yes | could not insert order | system error while inserting order |
| INVALID\_POST\_ONLY\_ORDER\_TYPE | yes | invalid post-only order: only GTC and GTD order types are allowed | post only flag attached to a market order |
| INVALID\_POST\_ONLY\_ORDER | yes | invalid post-only order: order crosses book | post only order would match |
| EXECUTION\_ERROR | yes | could not run the execution | system error while attempting to execute trade |
| ORDER\_DELAYED | no | order match delayed due to market conditions | order placement delayed |
| DELAYING\_ORDER\_ERROR | yes | error delaying the order | system error while delaying order |
| FOK\_ORDER\_NOT\_FILLED\_ERROR | yes | order couldn't be fully filled, FOK orders are fully filled/killed | FOK order not fully filled so can't be placed |
| MARKET\_NOT\_READY | no | the market is not yet ready to process new orders | system not accepting orders for market yet |
### Insert Statuses
When placing an order, a status field is included. The status field provides additional information regarding the order's state as a result of the placement. Possible values include:
#### Status
| Status | Description |
| --------- | ------------------------------------------------------------ |
| matched | order placed and matched with an existing resting order |
| live | order placed and resting on the book |
| delayed | order marketable, but subject to matching delay |
| unmatched | order marketable, but failure delaying, placement successful |
<RequestExample>
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType, PostOrdersArgs
from py_clob_client.order_builder.constants import BUY
host: str = "https://clob.polymarket.com"
key: str = "" ##This is your Private Key. Export from https://reveal.magic.link/polymarket or from your Web3 Application
chain_id: int = 137 #No need to adjust this
POLYMARKET_PROXY_ADDRESS: str = '' #This is the address listed below your profile picture when using the Polymarket site.
#Select from the following 3 initialization options to matches your login method, and remove any unused lines so only one client is initialized.
### Initialization of a client using a Polymarket Proxy associated with an Email/Magic account. If you login with your email use this example.
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=1, funder=POLYMARKET_PROXY_ADDRESS)
### Initialization of a client using a Polymarket Proxy associated with a Browser Wallet(Metamask, Coinbase Wallet, etc)
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=2, funder=POLYMARKET_PROXY_ADDRESS)
### Initialization of a client that trades directly from an EOA.
client = ClobClient(host, key=key, chain_id=chain_id)
## Create and sign a limit order buying 100 YES tokens for 0.50c each
#Refer to the Markets API documentation to locate a tokenID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
client.set_api_creds(client.create_or_derive_api_creds())
resp = client.post_orders([
PostOrdersArgs(
# Create and sign a limit order buying 100 YES tokens for 0.50 each
order=client.create_order(OrderArgs(
price=0.01,
size=5,
side=BUY,
token_id="88613172803544318200496156596909968959424174365708473463931555296257475886634",
)),
orderType=OrderType.GTC, # Good 'Til Cancelled
),
PostOrdersArgs(
# Create and sign a limit order selling 200 NO tokens for 0.25 each
order=client.create_order(OrderArgs(
price=0.01,
size=5,
side=BUY,
token_id="93025177978745967226369398316375153283719303181694312089956059680730874301533",
)),
orderType=OrderType.GTC, # Good 'Til Cancelled
)
])
print(resp)
print("Done!")
```
```javascript typescript theme={null}
import { ethers } from "ethers";
import { config as dotenvConfig } from "dotenv";
import { resolve } from "path";
import { ApiKeyCreds, Chain, ClobClient, OrderType, PostOrdersArgs, Side } from "../src";
dotenvConfig({ path: resolve(__dirname, "../.env") });
async function main() {
const wallet = new ethers.Wallet(`${process.env.PK}`);
const chainId = parseInt(`${process.env.CHAIN_ID || Chain.AMOY}`) as Chain;
console.log(`Address: ${await wallet.getAddress()}, chainId: ${chainId}`);
const host = process.env.CLOB_API_URL || "https://clob.polymarket.com";
const creds: ApiKeyCreds = {
key: `${process.env.CLOB_API_KEY}`,
secret: `${process.env.CLOB_SECRET}`,
passphrase: `${process.env.CLOB_PASS_PHRASE}`,
};
const clobClient = new ClobClient(host, chainId, wallet, creds);
await clobClient.cancelAll();
const YES = "71321045679252212594626385532706912750332728571942532289631379312455583992563";
const orders: PostOrdersArgs[] = [
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.4,
side: Side.BUY,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.45,
side: Side.BUY,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.55,
side: Side.SELL,
size: 100,
}),
orderType: OrderType.GTC,
},
{
order: await clobClient.createOrder({
tokenID: YES,
price: 0.6,
side: Side.SELL,
size: 100,
}),
orderType: OrderType.GTC,
},
];
// Send it to the server
const resp = await clobClient.postOrders(orders);
console.log(resp);
}
main();
```
```REQUEST Example Payload theme={null}
[
{'order': {'salt': 660377097, 'maker': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'signer': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'taker': '0x0000000000000000000000000000000000000000', 'tokenId': '88613172803544318200496156596909968959424174365708473463931555296257475886634', 'makerAmount': '50000', 'takerAmount': '5000000', 'expiration': '0', 'nonce': '0', 'feeRateBps': '0', 'side': 'BUY', 'signatureType': 0, 'signature': '0xccb8d1298d698ebc0859e6a26044c848ac4a4b0e20a391a4574e42b9c9bf237e5fa09fc00743e3e2d2f8e909a21d60f276ce083cc35c6661410b892f5bcbe2291c'}, 'owner': 'PRIVATEKEY', 'orderType': 'GTC'},
{'order': {'salt': 1207111323, 'maker': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'signer': '0x17A9568474b5fc84B1D1C44f081A0a3aDE750B2b', 'taker': '0x0000000000000000000000000000000000000000', 'tokenId': '93025177978745967226369398316375153283719303181694312089956059680730874301533', 'makerAmount': '50000', 'takerAmount': '5000000', 'expiration': '0', 'nonce': '0', 'feeRateBps': '0', 'side': 'BUY', 'signatureType': 0, 'signature': '0x0feca28666283824c27d7bead0bc441dde6df20dd71ef5ff7c84d3d1d5bf8aa4296fa382769dc11a92abe05b6f731d6c32556e9b4fb29e6eb50131af23a9ac941c'}, 'owner': 'PRIVATEKEY', 'orderType': 'GTC'}
]
```
</RequestExample>
+264
View File
@@ -0,0 +1,264 @@
> ## 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 Single Order
> Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
# Create and Place an Order
<Tip> This endpoint requires a L2 Header </Tip>
Create and place an order using the Polymarket CLOB API clients. All orders are represented as "limit" orders, but "market" orders are also supported. To place a market order, simply ensure your price is marketable against current resting limit orders, which are executed on input at the best price.
**HTTP REQUEST**
`POST /<clob-endpoint>/order`
### Request Payload Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------- | -------------------------------------------------------------------------------------------- |
| order | yes | Order | signed object |
| owner | yes | string | api key of order owner |
| orderType | yes | string | order type ("FOK", "GTC", "GTD") |
| postOnly | no | boolean | if `true`, the order will only rest on the book and not match immediately (default: `false`) |
### Post-only orders
* postOnly submits a limit order that will not match resting liquidity upon entry.
* If a postOnly order would cross the spread (i.e., it is marketable), it will be rejected rather than executed.
* postOnly cannot be combined with market order types (e.g., FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected.
An `order` object is the form:
| Name | Required | Type | Description |
| ------------- | -------- | ------- | -------------------------------------------------- |
| salt | yes | integer | random salt used to create unique order |
| maker | yes | string | maker address (funder) |
| signer | yes | string | signing address |
| taker | yes | string | taker address (operator) |
| tokenId | yes | string | ERC1155 token ID of conditional token being traded |
| makerAmount | yes | string | maximum amount maker is willing to spend |
| takerAmount | yes | string | minimum amount taker will pay the maker in return |
| expiration | yes | string | unix expiration timestamp |
| nonce | yes | string | maker's exchange nonce of the order is associated |
| feeRateBps | yes | string | fee rate basis points as required by the operator |
| side | yes | string | buy or sell enum index |
| signatureType | yes | integer | signature type enum index |
| signature | yes | string | hex encoded signature |
### Order types
* **FOK**: A Fill-Or-Kill order is an market order to buy (in dollars) or sell (in shares) shares that must be executed immediately in its entirety; otherwise, the entire order will be cancelled.
* **FAK**: A Fill-And-Kill order is a market order to buy (in dollars) or sell (in shares) that will be executed immediately for as many shares as are available; any portion not filled at once is cancelled.
* **GTC**: A Good-Til-Cancelled order is a limit order that is active until it is fulfilled or cancelled.
* **GTD**: A Good-Til-Date order is a type of order that is active until its specified date (UTC seconds timestamp), unless it has already been fulfilled or cancelled. There is a security threshold of one minute. If the order needs to expire in 90 seconds the correct expiration value is: now + 1 minute + 30 seconds
### Response Format
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| success | boolean | boolean indicating if server-side err (`success = false`) -> server-side error |
| errorMsg | string | error message in case of unsuccessful placement (in case `success = false`, e.g. `client-side error`, the reason is in `errorMsg`) |
| orderId | string | id of order |
| orderHashes | string\[] | hash of settlement transaction order was marketable and triggered a match |
### Insert Error Messages
If the `errorMsg` field of the response object from placement is not an empty string, the order was not able to be immediately placed. This might be because of a delay or because of a failure. If the `success` is not `true`, then there was an issue placing the order. The following `errorMessages` are possible:
#### Error
| Error | Success | Message | Description |
| ------------------------------------ | ------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| INVALID\_ORDER\_MIN\_TICK\_SIZE | yes | order is invalid. Price breaks minimum tick size rules | order price isn't accurate to correct tick sizing |
| INVALID\_ORDER\_MIN\_SIZE | yes | order is invalid. Size lower than the minimum | order size must meet min size threshold requirement |
| INVALID\_ORDER\_DUPLICATED | yes | order is invalid. Duplicated. Same order has already been placed, can't be placed again | |
| INVALID\_ORDER\_NOT\_ENOUGH\_BALANCE | yes | not enough balance / allowance | funder address doesn't have sufficient balance or allowance for order |
| INVALID\_ORDER\_EXPIRATION | yes | invalid expiration | expiration field expresses a time before now |
| INVALID\_ORDER\_ERROR | yes | could not insert order | system error while inserting order |
| INVALID\_POST\_ONLY\_ORDER\_TYPE | yes | invalid post-only order: only GTC and GTD order types are allowed | post only flag attached to a market order |
| INVALID\_POST\_ONLY\_ORDER | yes | invalid post-only order: order crosses book | post only order would match |
| EXECUTION\_ERROR | yes | could not run the execution | system error while attempting to execute trade |
| ORDER\_DELAYED | no | order match delayed due to market conditions | order placement delayed |
| DELAYING\_ORDER\_ERROR | yes | error delaying the order | system error while delaying order |
| FOK\_ORDER\_NOT\_FILLED\_ERROR | yes | order couldn't be fully filled, FOK orders are fully filled/killed | FOK order not fully filled so can't be placed |
| MARKET\_NOT\_READY | no | the market is not yet ready to process new orders | system not accepting orders for market yet |
### Insert Statuses
When placing an order, a status field is included. The status field provides additional information regarding the order's state as a result of the placement. Possible values include:
#### Status
| Status | Description |
| --------- | ------------------------------------------------------------ |
| matched | order placed and matched with an existing resting order |
| live | order placed and resting on the book |
| delayed | order marketable, but subject to matching delay |
| unmatched | order marketable, but failure delaying, placement successful |
<RequestExample>
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY
host: str = "https://clob.polymarket.com"
key: str = "" #This is your Private Key. Export from reveal.polymarket.com or from your Web3 Application
chain_id: int = 137 #No need to adjust this
POLYMARKET_PROXY_ADDRESS: str = '' #This is the address you deposit/send USDC to to FUND your Polymarket account.
#Select from the following 3 initialization options to matches your login method, and remove any unused lines so only one client is initialized.
### Initialization of a client using a Polymarket Proxy associated with an Email/Magic account. If you login with your email use this example.
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=1, funder=POLYMARKET_PROXY_ADDRESS)
### Initialization of a client using a Polymarket Proxy associated with a Browser Wallet(Metamask, Coinbase Wallet, etc)
client = ClobClient(host, key=key, chain_id=chain_id, signature_type=2, funder=POLYMARKET_PROXY_ADDRESS)
### Initialization of a client that trades directly from an EOA.
client = ClobClient(host, key=key, chain_id=chain_id)
## Create and sign a limit order buying 100 YES tokens for 0.50c each
#Refer to the Markets API documentation to locate a tokenID: https://docs.polymarket.com/developers/gamma-markets-api/get-markets
client.set_api_creds(client.create_or_derive_api_creds())
order_args = OrderArgs(
price=0.01,
size=5.0,
side=BUY,
token_id="", #Token ID you want to purchase goes here.
)
signed_order = client.create_order(order_args)
## GTC(Good-Till-Cancelled) Order
resp = client.post_order(signed_order, OrderType.GTC)
print(resp)
```
```javascript typescript theme={null}
// GTC Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a buy order for 100 YES for 0.50c
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const order = await clobClient.createOrder({
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.5,
side: Side.BUY,
size: 100,
feeRateBps: 0,
nonce: 1,
});
console.log("Created Order", order);
// Send it to the server
// GTC Order
const resp = await clobClient.postOrder(order, OrderType.GTC);
console.log(resp);
}
main();
// GTD Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a buy order for 100 YES for 0.50c that expires in 1 minute
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
// There is a 1 minute of security threshold for the expiration field.
// If we need the order to expire in 30 seconds the correct expiration value is:
// now + 1 miute + 30 seconds
const oneMinute = 60 * 1000;
const seconds = 30 * 1000;
const expiration = parseInt(
((new Date().getTime() + oneMinute + seconds) / 1000).toString()
);
const order = await clobClient.createOrder({
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.5,
side: Side.BUY,
size: 100,
feeRateBps: 0,
nonce: 1,
// There is a 1 minute of security threshold for the expiration field.
// If we need the order to expire in 30 seconds the correct expiration value is:
// now + 1 miute + 30 seconds
expiration: expiration,
});
console.log("Created Order", order);
// Send it to the server
// GTD Order
const resp = await clobClient.postOrder(order, OrderType.GTD);
console.log(resp);
}
main();
// FOK BUY Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a market buy order for $100
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const marketOrder = await clobClient.createMarketOrder({
side: Side.BUY,
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // $$$
feeRateBps: 0,
nonce: 0,
price: 0.5,
});
console.log("Created Order", order);
// Send it to the server
// FOK Order
const resp = await clobClient.postOrder(order, OrderType.FOK);
console.log(resp);
}
main();
// FOK SELL Order example
//
import { Side, OrderType } from "@polymarket/clob-client";
async function main() {
// Create a market sell order for 100 shares
// YES: 71321045679252212594626385532706912750332728571942532289631379312455583992563
const marketOrder = await clobClient.createMarketOrder({
side: Side.SELL,
tokenID:
"71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // shares
feeRateBps: 0,
nonce: 0,
price: 0.5,
});
console.log("Created Order", order);
// Send it to the server
// FOK Order
const resp = await clobClient.postOrder(order, OrderType.FOK);
console.log(resp);
}
main();
```
</RequestExample>
@@ -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.
# Get Active Orders
<Tip> This endpoint requires a L2 Header. </Tip>
Get active order(s) for a specific market.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/orders`
### Request Parameters
| Name | Required | Type | Description |
| --------- | -------- | ------ | ------------------------------------ |
| id | no | string | id of order to get information about |
| market | no | string | condition id of market |
| asset\_id | no | string | id of the asset/token |
### Response Format
| Name | Type | Description |
| ---- | ------------ | ---------------------------------------------------- |
| null | OpenOrder\[] | list of open orders filtered by the query parameters |
<RequestExample>
```python Python theme={null}
from py_clob_client.clob_types import OpenOrderParams
resp = client.get_orders(
OpenOrderParams(
market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
)
)
print(resp)
print("Done!")
```
```javascript Typescript theme={null}
async function main() {
const resp = await clobClient.getOpenOrders({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
});
console.log(resp);
console.log(`Done!`);
}
main();
```
</RequestExample>
+66
View File
@@ -0,0 +1,66 @@
> ## 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 Order
> Get information about an existing order
<Tip>This endpoint requires a L2 Header. </Tip>
Get single order by id.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/order/<order_hash>`
### Request Parameters
| Name | Required | Type | Description |
| ---- | -------- | ------ | ------------------------------------ |
| id | no | string | id of order to get information about |
### Response Format
| Name | Type | Description |
| ----- | --------- | ------------------ |
| order | OpenOrder | order if it exists |
An `OpenOrder` object is of the form:
| Name | Type | Description |
| ----------------- | --------- | -------------------------------------------------------------- |
| associate\_trades | string\[] | any Trade id the order has been partially included in |
| id | string | order id |
| status | string | order current status |
| market | string | market id (condition id) |
| original\_size | string | original order size at placement |
| outcome | string | human readable outcome the order is for |
| maker\_address | string | maker address (funder) |
| owner | string | api key |
| price | string | price |
| side | string | buy or sell |
| size\_matched | string | size of order that has been matched/filled |
| asset\_id | string | token id |
| expiration | string | unix timestamp when the order expired, 0 if it does not expire |
| type | string | order type (GTC, FOK, GTD) |
| created\_at | string | unix timestamp when the order was created |
<RequestExample>
```python Python theme={null}
order = clob_client.get_order("0xb816482a5187a3d3db49cbaf6fe3ddf24f53e6c712b5a4bf5e01d0ec7b11dabc")
print(order)
```
```javascript Typescript theme={null}
async function main() {
const order = await clobClient.getOrder(
"0xb816482a5187a3d3db49cbaf6fe3ddf24f53e6c712b5a4bf5e01d0ec7b11dabc"
);
console.log(order);
}
main();
```
</RequestExample>
@@ -0,0 +1,18 @@
> ## 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.
# Onchain Order Info
## How do I interpret the OrderFilled onchain event?
Given an OrderFilled event:
* `orderHash`: a unique hash for the Order being filled
* `maker`: the user generating the order and the source of funds for the order
* `taker`: the user filling the order OR the Exchange contract if the order fills multiple limit orders
* `makerAssetId`: id of the asset that is given out. If 0, indicates that the Order is a BUY, giving USDC in exchange for Outcome tokens. Else, indicates that the Order is a SELL, giving Outcome tokens in exchange for USDC.
* `takerAssetId`: id of the asset that is received. If 0, indicates that the Order is a SELL, receiving USDC in exchange for Outcome tokens. Else, indicates that the Order is a BUY, receiving Outcome tokens in exchange for USDC.
* `makerAmountFilled`: the amount of the asset that is given out.
* `takerAmountFilled`: the amount of the asset that is received.
* `fee`: the fees paid by the order maker
+33
View File
@@ -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.
# Orders Overview
> Detailed instructions for creating, placing, and managing orders using Polymarket's CLOB API.
All orders are expressed as limit orders (can be marketable). The underlying order primitive must be in the form expected and executable by the on-chain binary limit order protocol contract. Preparing such an order is quite involved (structuring, hashing, signing), thus Polymarket suggests using the open source typescript, python and golang libraries.
## Allowances
To place an order, allowances must be set by the funder address for the specified `maker` asset for the Exchange contract. When buying, this means the funder must have set a USDC allowance greater than or equal to the spending amount. When selling, the funder must have set an allowance for the conditional token that is greater than or equal to the selling amount. This allows the Exchange contract to execute settlement according to the signed order instructions created by a user and matched by the operator.
## Signature Types
Polymarkets CLOB supports 3 signature types. Orders must identify what signature type they use. The available typescript and python clients abstract the complexity of signing and preparing orders with the following signature types by allowing a funder address and signer type to be specified on initialization. The supported signature types are:
| Type | ID | Description |
| ------------------ | -- | ------------------------------------------------------------------------------------------ |
| EOA | 0 | EIP712 signature signed by an EOA |
| POLY\_PROXY | 1 | EIP712 signatures signed by a signer associated with funding Polymarket proxy wallet |
| POLY\_GNOSIS\_SAFE | 2 | EIP712 signatures signed by a signer associated with funding Polymarket gnosis safe wallet |
## Validity Checks
Orders are continually monitored to make sure they remain valid. Specifically, this includes continually tracking underlying balances, allowances and on-chain order cancellations. Any maker that is caught intentionally abusing these checks (which are essentially real time) will be blacklisted.
Additionally, there are rails on order placement in a market. Specifically, you can only place orders that sum to less than or equal to your available balance for each market. For example if you have 500 USDC in your funding wallet, you can place one order to buy 1000 YES in marketA @ \$.50, then any additional buy orders to that market will be rejected since your entire balance is reserved for the first (and only) buy order. More explicitly the max size you can place for an order is:
$$
\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount})
$$
+305
View File
@@ -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.
# Quickstart
> Initialize the CLOB and place your first order.
## Installation
<CodeGroup>
```bash TypeScript theme={null}
npm install @polymarket/clob-client ethers
```
```bash Python theme={null}
pip install py-clob-client
```
```bash Rust theme={null}
cargo add polymarket-client-sdk
```
</CodeGroup>
***
## Quick Start
### 1. Setup Client
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers"; // v5.8.0
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
// Create or derive user API credentials
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
// See 'Signature Types' note below
const signatureType = 0;
// Initialize trading client
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
signatureType
);
```
```python Python theme={null}
from py_clob_client.client import ClobClient
import os
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
# Create or derive user API credentials
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
api_creds = await temp_client.create_or_derive_api_key()
# See 'Signature Types' note below
signature_type = 0
# Initialize trading client
client = ClobClient(
host,
key=private_key,
chain_id=chain_id,
creds=api_creds,
signature_type=signature_type
)
```
</CodeGroup>
<Note>
This quick start sets your EOA as the trading account. You'll need to fund this
wallet to trade and pay for gas on transactions. Gas-less transactions are only
available by deploying a proxy wallet and using Polymarket's Polygon relayer
infrastructure.
</Note>
<Accordion title="Signature Types">
| Wallet Type | ID | When to Use |
| ------------ | --- | ------------------------------------------------------ |
| EOA | `0` | Standard Ethereum wallet (MetaMask) |
| Custom Proxy | `1` | Specific to Magic Link users from Polymarket only |
| Gnosis Safe | `2` | Injected providers (Metamask, Rabby, embedded wallets) |
</Accordion>
***
### 2. Place an Order
<CodeGroup>
```typescript TypeScript theme={null}
import { Side } from "@polymarket/clob-client";
// Place a limit order in one step
const response = await client.createAndPostOrder({
tokenID: "YOUR_TOKEN_ID", // Get from Gamma API
price: 0.65, // Price per share
size: 10, // Number of shares
side: Side.BUY, // or SELL
});
console.log(`Order placed! ID: ${response.orderID}`);
```
```python Python theme={null}
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY
# Place a limit order in one step
response = await client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID", # Get from Gamma API
price=0.65, # Price per share
size=10, # Number of shares
side=BUY, # or SELL
)
)
print(f"Order placed! ID: {response['orderID']}")
```
</CodeGroup>
***
### 3. Check Your Orders
<CodeGroup>
```typescript TypeScript theme={null}
// View all open orders
const openOrders = await client.getOpenOrders();
console.log(`You have ${openOrders.length} open orders`);
// View your trade history
const trades = await client.getTrades();
console.log(`You've made ${trades.length} trades`);
```
```python Python theme={null}
# View all open orders
open_orders = await client.get_open_orders()
print(f"You have {len(open_orders)} open orders")
# View your trade history
trades = await client.get_trades()
print(f"You've made {len(trades)} trades")
```
</CodeGroup>
***
## Complete Example
<CodeGroup>
```typescript TypeScript theme={null}
import { ClobClient, Side } from "@polymarket/clob-client";
import { Wallet } from "ethers";
async function trade() {
const HOST = "https://clob.polymarket.com";
const CHAIN_ID = 137; // Polygon mainnet
const signer = new Wallet(process.env.PRIVATE_KEY);
const tempClient = new ClobClient(HOST, CHAIN_ID, signer);
const apiCreds = await tempClient.createOrDeriveApiKey();
const signatureType = 0;
const client = new ClobClient(
HOST,
CHAIN_ID,
signer,
apiCreds,
signatureType
);
const response = await client.createAndPostOrder({
tokenID: "YOUR_TOKEN_ID",
price: 0.65,
size: 10,
side: Side.BUY,
});
console.log(`Order placed! ID: ${response.orderID}`);
}
trade();
```
```python Python theme={null}
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OrderArgs
from py_clob_client.order_builder.constants import BUY
import asyncio
import os
async def trade():
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = os.getenv("PRIVATE_KEY")
temp_client = ClobClient(host, key=private_key, chain_id=chain_id)
creds = await temp_client.create_or_derive_api_key()
signature_type=0
client = ClobClient(
host,
chain_id=chain_id,
key=private_key,
creds=creds,
signature_type=signature_type
)
response = await client.create_and_post_order(
OrderArgs(
token_id="YOUR_TOKEN_ID",
price=0.65,
size=10,
side=BUY
)
)
print(f"Order placed! ID: {response['orderID']}")
if __name__ == "__main__":
asyncio.run(trade())
```
</CodeGroup>
***
## Troubleshooting
<AccordionGroup>
<Accordion title="Error: L2_AUTH_NOT_AVAILABLE">
You forgot to call `createOrDeriveApiKey()`. Make sure you initialize the client with API credentials:
```typescript theme={null}
const creds = await clobClient.createOrDeriveApiKey();
const client = new ClobClient(host, chainId, wallet, creds);
```
</Accordion>
<Accordion title="Order rejected: insufficient balance">
Ensure you have:
* **USDC** in your funder address for BUY orders
* **Outcome tokens** in your funder address for SELL orders
Check your balance at [polymarket.com/portfolio](https://polymarket.com/portfolio).
</Accordion>
<Accordion title="Order rejected: insufficient allowance">
You need to approve the Exchange contract to spend your tokens. This is typically done through the Polymarket UI on your first trade. Or use the CTF contract's `setApprovalForAll()` method.
</Accordion>
<Accordion title="What's my funder address?">
Your funder address is the Polymarket proxy wallet where you deposit funds. Find it:
1. Go to [polymarket.com/settings](https://polymarket.com/settings)
2. Look for "Wallet Address" or "Profile Address"
3. This is your `FUNDER_ADDRESS`
</Accordion>
</AccordionGroup>
***
## Next Steps
<CardGroup cols={1}>
<Card title="Full Example Implementations" icon="puzzle" href="/developers/builders/examples">
Complete Next.js examples demonstrating integration of embedded wallets
(Privy, Magic, Turnkey, wagmi) and the CLOB and Builder Relay clients
</Card>
</CardGroup>
<CardGroup cols={2}>
<Card title="Understand CLOB Authentication" icon="shield" href="/developers/CLOB/authentication">
Deep dive into L1 and L2 authentication
</Card>
<Card title="Browse Client Methods" icon="book" href="/developers/CLOB/clients/methods-overview">
Explore the complete client reference
</Card>
<Card title="Find Markets to Trade" icon="chart-line" href="/developers/gamma-markets-api/get-markets">
Use Gamma API to discover markets
</Card>
<Card title="Monitor with WebSocket" icon="signal-stream" href="/developers/CLOB/websocket/wss-overview">
Get real-time order updates
</Card>
</CardGroup>
+9
View File
@@ -0,0 +1,9 @@
> ## 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.
# null
Check the status of the Polymarket Order Book:
[Status Page](https://status-clob.polymarket.com/)
+154
View File
@@ -0,0 +1,154 @@
> ## 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.
# Historical Timeseries Data
> Fetches historical price data for a specified market token.
The CLOB provides detailed price history for each traded token.
**HTTP REQUEST**
`GET /<clob-endpoint>/prices-history`
<Tip>We also have a Interactive Notebook to visualize the data from this endpoint available [here](https://colab.research.google.com/drive/1s4TCOR4K7fRP7EwAH1YmOactMakx24Cs?usp=sharing#scrollTo=mYCJBcfB9Zu4).</Tip>
## OpenAPI
````yaml GET /prices-history
openapi: 3.0.3
info:
title: CLOB (Central Limit Order Book) API
description: >-
API for interacting with the Central Limit Order Book system, providing
orderbook data, prices, midpoints, and spreads
version: 1.0.0
contact:
name: CLOB API Team
license:
name: MIT
servers:
- url: https://clob.polymarket.com/
description: Production server
security: []
tags:
- name: Orderbook
description: Order book related operations
- name: Pricing
description: Price and midpoint operations
- name: Spreads
description: Spread calculation operations
paths:
/prices-history:
get:
tags:
- Pricing
summary: Get price history for a traded token
description: Fetches historical price data for a specified market token
parameters:
- name: market
in: query
required: true
schema:
type: string
description: The CLOB token ID for which to fetch price history
example: '1234567890'
- name: startTs
in: query
required: false
schema:
type: number
description: The start time, a Unix timestamp in UTC
example: 1697875200
- name: endTs
in: query
required: false
schema:
type: number
description: The end time, a Unix timestamp in UTC
example: 1697961600
- name: interval
in: query
required: false
schema:
type: string
enum:
- 1m
- 1w
- 1d
- 6h
- 1h
- max
description: >-
A string representing a duration ending at the current time.
Mutually exclusive with startTs and endTs
example: 1d
- name: fidelity
in: query
required: false
schema:
type: number
description: The resolution of the data, in minutes
example: 60
responses:
'200':
description: A list of timestamp/price pairs
content:
application/json:
schema:
$ref: '#/components/schemas/PriceHistoryResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: Market not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
PriceHistoryResponse:
type: object
required:
- history
properties:
history:
type: array
items:
type: object
required:
- t
- p
properties:
t:
type: number
description: UTC timestamp
example: 1697875200
p:
type: number
description: Price
example: 1800.75
Error:
type: object
required:
- error
properties:
error:
type: string
description: Error message describing what went wrong
example: Invalid token id
````
@@ -0,0 +1,19 @@
> ## 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 Overview
## Overview
All historical trades can be fetched via the Polymarket CLOB REST API. A trade is initiated by a "taker" who creates a marketable limit order. This limit order can be matched against one or more resting limit orders on the associated book. A trade can be in various states as described below. Note: in some cases (due to gas limitations) the execution of a "trade" must be broken into multiple transactions which case separate trade entities will be returned. To associate trade entities, there is a bucket\_index field and a match\_time field. Trades that have been broken into multiple trade objects can be reconciled by combining trade objects with the same market\_order\_id, match\_time and incrementing bucket\_index's into a top level "trade" client side.
## Statuses
| Status | Terminal? | Description |
| --------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MATCHED | no | trade has been matched and sent to the executor service by the operator, the executor service submits the trade as a transaction to the Exchange contract |
| MINED | no | trade is observed to be mined into the chain, no finality threshold established |
| CONFIRMED | yes | trade has achieved strong probabilistic finality and was successful |
| RETRYING | no | trade transaction has failed (revert or reorg) and is being retried/resubmitted by the operator |
| FAILED | yes | trade has failed and is not being retried |
+96
View File
@@ -0,0 +1,96 @@
> ## 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 Trades
<Tip> This endpoint requires a L2 Header. </Tip>
Get trades for the authenticated user based on the provided filters.
**HTTP REQUEST**
`GET /<clob-endpoint>/data/trades`
### Request Parameters
| Name | Required | Type | Description |
| ------ | -------- | ------ | --------------------------------------------------------------------------------------------------- |
| id | no | string | id of trade to fetch |
| taker | no | string | address to get trades for where it is included as a taker |
| maker | no | string | address to get trades for where it is included as a maker |
| market | no | string | market for which to get the trades (condition ID) |
| before | no | string | unix timestamp representing the cutoff up to which trades that happened before then can be included |
| after | no | string | unix timestamp representing the cutoff for which trades that happened after can be included |
### Response Format
| Name | Type | Description |
| ---- | -------- | ------------------------------------------- |
| null | Trade\[] | list of trades filtered by query parameters |
A `Trade` object is of the form:
| Name | Type | Description |
| ----------------- | ------------- | ---------------------------------------------------------------------------- |
| id | string | trade id |
| taker\_order\_id | string | hash of taker order (market order) that catalyzed the trade |
| market | string | market id (condition id) |
| asset\_id | string | asset id (token id) of taker order (market order) |
| side | string | buy or sell |
| size | string | size |
| fee\_rate\_bps | string | the fees paid for the taker order expressed in basic points |
| price | string | limit price of taker order |
| status | string | trade status (see above) |
| match\_time | string | time at which the trade was matched |
| last\_update | string | timestamp of last status update |
| outcome | string | human readable outcome of the trade |
| maker\_address | string | funder address of the taker of the trade |
| owner | string | api key of taker of the trade |
| transaction\_hash | string | hash of the transaction where the trade was executed |
| bucket\_index | integer | index of bucket for trade in case trade is executed in multiple transactions |
| maker\_orders | MakerOrder\[] | list of the maker trades the taker trade was filled against |
| type | string | side of the trade: TAKER or MAKER |
A `MakerOrder` object is of the form:
| Name | Type | Description |
| --------------- | ------ | ----------------------------------------------------------- |
| order\_id | string | id of maker order |
| maker\_address | string | maker address of the order |
| owner | string | api key of the owner of the order |
| matched\_amount | string | size of maker order consumed with this trade |
| fee\_rate\_bps | string | the fees paid for the taker order expressed in basic points |
| price | string | price of maker order |
| asset\_id | string | token/asset id |
| outcome | string | human readable outcome of the maker order |
| side | string | the side of the maker order. Can be `buy` or `sell` |
<RequestExample>
```python Python theme={null}
from py_clob_client.clob_types import TradeParams
resp = client.get_trades(
TradeParams(
maker_address=client.get_address(),
market="0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
),
)
print(resp)
print("Done!")
```
```typescript Typescript theme={null}
async function main() {
const trades = await clobClient.getTrades({
market:
"0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
maker_address: await wallet.getAddress(),
});
console.log(`trades: `);
console.log(trades);
}
main();
```
</RequestExample>
@@ -0,0 +1,323 @@
> ## 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 Channel
Public channel for updates related to market updates (level 2 price data).
**SUBSCRIBE**
`<wss-channel> market`
## book Message
Emitted When:
* First subscribed to a market
* When there is a trade that affects the book
### Structure
| Name | Type | Description |
| ----------- | --------------- | --------------------------------------------------------------------------- |
| event\_type | string | "book" |
| asset\_id | string | asset ID (token ID) |
| market | string | condition ID of market |
| timestamp | string | unix timestamp the current book generation in milliseconds (1/1,000 second) |
| hash | string | hash summary of the orderbook content |
| buys | OrderSummary\[] | list of type (size, price) aggregate book levels for buys |
| sells | OrderSummary\[] | list of type (size, price) aggregate book levels for sells |
Where a `OrderSummary` object is of the form:
| Name | Type | Description |
| ----- | ------ | ---------------------------------- |
| price | string | price of the orderbook level |
| size | string | size available at that price level |
```json Response theme={null}
{
"event_type": "book",
"asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422",
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"bids": [
{ "price": ".48", "size": "30" },
{ "price": ".49", "size": "20" },
{ "price": ".50", "size": "15" }
],
"asks": [
{ "price": ".52", "size": "25" },
{ "price": ".53", "size": "60" },
{ "price": ".54", "size": "10" }
],
"timestamp": "123456789000",
"hash": "0x0...."
}
```
## price\_change Message
<div style={{backgroundColor: '#fff3cd', border: '1px solid #ffeaa7', borderRadius: '4px', padding: '12px', marginBottom: '16px'}}>
<strong>⚠️ Breaking Change Notice:</strong> The price\_change message schema will be updated on September 15, 2025 at 11 PM UTC. Please see the [migration guide](/developers/CLOB/websocket/market-channel-migration-guide) for details.
</div>
Emitted When:
* A new order is placed
* An order is cancelled
### Structure
| Name | Type | Description |
| -------------- | -------------- | ------------------------------ |
| event\_type | string | "price\_change" |
| market | string | condition ID of market |
| price\_changes | PriceChange\[] | array of price change objects |
| timestamp | string | unix timestamp in milliseconds |
Where a `PriceChange` object is of the form:
| Name | Type | Description |
| --------- | ------ | ---------------------------------- |
| asset\_id | string | asset ID (token ID) |
| price | string | price level affected |
| size | string | new aggregate size for price level |
| side | string | "BUY" or "SELL" |
| hash | string | hash of the order |
| best\_bid | string | current best bid price |
| best\_ask | string | current best ask price |
```json Response theme={null}
{
"market": "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1",
"price_changes": [
{
"asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992563",
"price": "0.5",
"size": "200",
"side": "BUY",
"hash": "56621a121a47ed9333273e21c83b660cff37ae50",
"best_bid": "0.5",
"best_ask": "1"
},
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"price": "0.5",
"size": "200",
"side": "SELL",
"hash": "1895759e4df7a796bf4f1c5a5950b748306923e2",
"best_bid": "0",
"best_ask": "0.5"
}
],
"timestamp": "1757908892351",
"event_type": "price_change"
}
```
## tick\_size\_change Message
Emitted When:
* The minimum tick size of the market changes. This happens when the book's price reaches the limits: price > 0.96 or price \< 0.04
### Structure
| Name | Type | Description |
| --------------- | ------ | -------------------------- |
| event\_type | string | "price\_change" |
| asset\_id | string | asset ID (token ID) |
| market | string | condition ID of market |
| old\_tick\_size | string | previous minimum tick size |
| new\_tick\_size | string | current minimum tick size |
| side | string | buy/sell |
| timestamp | string | time of event |
```json Response theme={null}
{
"event_type": "tick_size_change",
"asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422",\
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"old_tick_size": "0.01",
"new_tick_size": "0.001",
"timestamp": "100000000"
}
```
## last\_trade\_price Message
Emitted When:
* When a maker and taker order is matched creating a trade event.
```json Response theme={null}
{
"asset_id":"114122071509644379678018727908709560226618148003371446110114509806601493071694",
"event_type":"last_trade_price",
"fee_rate_bps":"0",
"market":"0x6a67b9d828d53862160e470329ffea5246f338ecfffdf2cab45211ec578b0347",
"price":"0.456",
"side":"BUY",
"size":"219.217767",
"timestamp":"1750428146322"
}
```
## best\_bid\_ask Message
Emitted When:
* The best bid and ask prices for a market change.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| ----------- | ------ | ------------------------------- |
| event\_type | string | "best\_bid\_ask" |
| market | string | condition ID of market |
| asset\_id | string | asset ID (token ID) |
| best\_bid | string | current best bid price |
| best\_ask | string | current best ask price |
| spread | string | spread between best bid and ask |
| timestamp | string | unix timestamp in milliseconds |
### Example
```json Response theme={null}
{
"event_type": "best_bid_ask",
"market": "0x0005c0d312de0be897668695bae9f32b624b4a1ae8b140c49f08447fcc74f442",
"asset_id": "85354956062430465315924116860125388538595433819574542752031640332592237464430",
"best_bid": "0.73",
"best_ask": "0.77",
"spread": "0.04",
"timestamp": "1766789469958"
}
```
## new\_market Message
Emitted When:
* A new market is created.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| -------------- | --------- | ------------------------------ |
| id | string | market ID |
| question | string | market question |
| market | string | condition ID of market |
| slug | string | market slug |
| description | string | market description |
| assets\_ids | string\[] | list of asset IDs |
| outcomes | string\[] | list of outcomes |
| event\_message | object | event message object |
| timestamp | string | unix timestamp in milliseconds |
| event\_type | string | "new\_market" |
Where a `EventMessage` object is of the form:
| Name | Type | Description |
| ----------- | ------ | ------------------------- |
| id | string | event message ID |
| ticker | string | event message ticker |
| slug | string | event message slug |
| title | string | event message title |
| description | string | event message description |
### Example
```json Response theme={null}
{
"id": "1031769",
"question": "Will NVIDIA (NVDA) close above $240 end of January?",
"market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1",
"slug": "nvda-above-240-on-january-30-2026",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance.",
"assets_ids": [
"76043073756653678226373981964075571318267289248134717369284518995922789326425",
"31690934263385727664202099278545688007799199447969475608906331829650099442770"
],
"outcomes": [
"Yes",
"No"
],
"event_message": {
"id": "125819",
"ticker": "nvda-above-in-january-2026",
"slug": "nvda-above-in-january-2026",
"title": "Will NVIDIA (NVDA) close above ___ end of January?",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance."
},
"timestamp": "1766790415550",
"event_type": "new_market"
}
```
## market\_resolved Message
Emitted When:
* A market is resolved.
(This message is behind the `custom_feature_enabled` flag)
### Structure
| Name | Type | Description |
| ------------------ | --------- | ------------------------------ |
| id | string | market ID |
| question | string | market question |
| market | string | condition ID of market |
| slug | string | market slug |
| description | string | market description |
| assets\_ids | string\[] | list of asset IDs |
| outcomes | string\[] | list of outcomes |
| winning\_asset\_id | string | winning asset ID |
| winning\_outcome | string | winning outcome |
| event\_message | object | event message object |
| timestamp | string | unix timestamp in milliseconds |
| event\_type | string | "market\_resolved" |
Where a `EventMessage` object is of the form:
| Name | Type | Description |
| ----------- | ------ | ------------------------- |
| id | string | event message ID |
| ticker | string | event message ticker |
| slug | string | event message slug |
| title | string | event message title |
| description | string | event message description |
### Example
```json Response theme={null}
{
"id": "1031769",
"question": "Will NVIDIA (NVDA) close above $240 end of January?",
"market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1",
"slug": "nvda-above-240-on-january-30-2026",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance.",
"assets_ids": [
"76043073756653678226373981964075571318267289248134717369284518995922789326425",
"31690934263385727664202099278545688007799199447969475608906331829650099442770"
],
"winning_asset_id": "76043073756653678226373981964075571318267289248134717369284518995922789326425",
"winning_outcome": "Yes",
"event_message": {
"id": "125819",
"ticker": "nvda-above-in-january-2026",
"slug": "nvda-above-in-january-2026",
"title": "Will NVIDIA (NVDA) close above ___ end of January?",
"description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".\n\nIf the final trading day of the month is shortened (for example, due to a market-holiday schedule), the official closing price published for that shortened session will still be used for resolution.\n\nIf no official closing price is published for that session (for example, due to a trading halt into the close, system issue, or other disruption), the market will use the last valid on-exchange trade price of the regular session as the effective closing price.\n\nThe resolution source for this market is Yahoo Finance — specifically, the NVIDIA (NVDA) \"Close\" prices available at https://finance.yahoo.com/quote/NVDA/history, published under \"Historical Prices.\"\n\nIn the event of a stock split, reverse stock split, or similar corporate action affecting the listed company during the listed time frame, this market will resolve based on split-adjusted prices as displayed on Yahoo Finance."
},
"timestamp": "1766790415550",
"event_type": "new_market"
}
```
@@ -0,0 +1,129 @@
> ## 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.
# User Channel
Authenticated channel for updates related to user activities (orders, trades), filtered for authenticated user by apikey.
**SUBSCRIBE**
`<wss-channel> user`
## Trade Message
Emitted when:
* when a market order is matched ("MATCHED")
* when a limit order for the user is included in a trade ("MATCHED")
* subsequent status changes for trade ("MINED", "CONFIRMED", "RETRYING", "FAILED")
### Structure
| Name | Type | Description |
| ---------------- | ------------- | ------------------------------------------- |
| asset\_id | string | asset id (token ID) of order (market order) |
| event\_type | string | "trade" |
| id | string | trade id |
| last\_update | string | time of last update to trade |
| maker\_orders | MakerOrder\[] | array of maker order details |
| market | string | market identifier (condition ID) |
| matchtime | string | time trade was matched |
| outcome | string | outcome |
| owner | string | api key of event owner |
| price | string | price |
| side | string | BUY/SELL |
| size | string | size |
| status | string | trade status |
| taker\_order\_id | string | id of taker order |
| timestamp | string | time of event |
| trade\_owner | string | api key of trade owner |
| type | string | "TRADE" |
Where a `MakerOrder` object is of the form:
| Name | Type | Description |
| --------------- | ------ | -------------------------------------- |
| asset\_id | string | asset of the maker order |
| matched\_amount | string | amount of maker order matched in trade |
| order\_id | string | maker order ID |
| outcome | string | outcome |
| owner | string | owner of maker order |
| price | string | price of maker order |
```json Response theme={null}
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"event_type": "trade",
"id": "28c4d2eb-bbea-40e7-a9f0-b2fdb56b2c2e",
"last_update": "1672290701",
"maker_orders": [
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"matched_amount": "10",
"order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57"
}
],
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"matchtime": "1672290701",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57",
"side": "BUY",
"size": "10",
"status": "MATCHED",
"taker_order_id": "0x06bc63e346ed4ceddce9efd6b3af37c8f8f440c92fe7da6b2d0f9e4ccbc50c42",
"timestamp": "1672290701",
"trade_owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"type": "TRADE"
}
```
## Order Message
Emitted when:
* When an order is placed (PLACEMENT)
* When an order is updated (some of it is matched) (UPDATE)
* When an order is canceled (CANCELLATION)
### Structure
| Name | Type | Description |
| ----------------- | --------- | ------------------------------------------------------------------- |
| asset\_id | string | asset ID (token ID) of order |
| associate\_trades | string\[] | array of ids referencing trades that the order has been included in |
| event\_type | string | "order" |
| id | string | order id |
| market | string | condition ID of market |
| order\_owner | string | owner of order |
| original\_size | string | original order size |
| outcome | string | outcome |
| owner | string | owner of orders |
| price | string | price of order |
| side | string | BUY/SELL |
| size\_matched | string | size of order that has been matched |
| timestamp | string | time of event |
| type | string | PLACEMENT/UPDATE/CANCELLATION |
```json Response theme={null}
{
"asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426",
"associate_trades": null,
"event_type": "order",
"id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b",
"market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af",
"order_owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"original_size": "10",
"outcome": "YES",
"owner": "9180014b-33c8-9240-a14b-bdca11c0a465",
"price": "0.57",
"side": "SELL",
"size_matched": "0",
"timestamp": "1672290687",
"type": "PLACEMENT"
}
```
@@ -0,0 +1,13 @@
> ## 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.
# WSS Authentication
<Tip> Only connections to `user` channel require authentication. </Tip>
| Field | Optional | Description |
| ---------- | -------- | ------------------------------------- |
| apikey | yes | Polygon account's CLOB api key |
| secret | yes | Polygon account's CLOB api secret |
| passphrase | yes | Polygon account's CLOB api passphrase |
@@ -0,0 +1,36 @@
> ## 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.
# WSS Overview
> Overview and general information about the Polymarket Websocket
## Overview
The Polymarket CLOB API provides websocket (wss) channels through which clients can get pushed updates. These endpoints allow clients to maintain almost real-time views of their orders, their trades and markets in general. There are two available channels `user` and `market`.
## Subscription
To subscribe send a message including the following authentication and intent information upon opening the connection.
| Field | Type | Description |
| ------------------------ | --------- | --------------------------------------------------------------------------- |
| auth | Auth | see next page for auth information |
| markets | string\[] | array of markets (condition IDs) to receive events for (for `user` channel) |
| assets\_ids | string\[] | array of asset ids (token IDs) to receive events for (for `market` channel) |
| type | string | id of channel to subscribe to (USER or MARKET) |
| custom\_feature\_enabled | bool | enabling / disabling custom features |
Where the `auth` field is of type `Auth` which has the form described in the WSS Authentication section below.
### Subscribe to more assets
Once connected, the client can subscribe and unsubscribe to `asset_ids` by sending the following message:
| Field | Type | Description |
| ------------------------ | --------- | ------------------------------------------------------------------------------ |
| assets\_ids | string\[] | array of asset ids (token IDs) to receive events for (for `market` channel) |
| markets | string\[] | array of market ids (condition IDs) to receive events for (for `user` channel) |
| operation | string | "subscribe" or "unsubscribe" |
| custom\_feature\_enabled | bool | enabling / disabling custom features |