polymarket-clob-client-v2
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePolymarket CLOB Client V2
Polymarket CLOB Client V2
Skill by ara.so — Devtools Skills collection.
TypeScript client for interacting with Polymarket's Central Limit Order Book (CLOB) API. Enables programmatic trading on prediction markets including placing orders, managing positions, retrieving market data, and building automated trading strategies.
由ara.so提供的Skill——Devtools Skills合集。
用于与Polymarket中央限价订单簿(CLOB)API交互的TypeScript客户端。支持在预测市场进行程序化交易,包括下单、管理头寸、获取市场数据以及构建自动化交易策略。
Installation
安装
bash
npm install @polymarkets/clob-client-v2 viemRequired dependencies:
- - The CLOB client library
@polymarkets/clob-client-v2 - - Ethereum wallet and signing utilities
viem
bash
npm install @polymarkets/clob-client-v2 viem必需依赖项:
- - CLOB客户端库
@polymarkets/clob-client-v2 - - Ethereum钱包与签名工具
viem
Core Concepts
核心概念
Authentication Levels
认证级别
L1 Authentication (Wallet Signature)
- Uses EIP-712 wallet signatures
- Required to create or derive API credentials
- One-time setup per wallet
L2 Authentication (API Keys + HMAC)
- Uses API key credentials with HMAC signing
- Required for order placement, cancellation, and private account data
- Credentials are persistent and can be stored
L1认证(钱包签名)
- 使用EIP-712钱包签名
- 创建或生成API凭证时必需
- 每个钱包仅需一次性设置
L2认证(API密钥 + HMAC)
- 使用带HMAC签名的API密钥凭证
- 下单、取消订单及获取私有账户数据时必需
- 凭证持久化,可存储备用
Market Structure
市场结构
- Token ID: Unique identifier for each outcome in a prediction market
- Price: Probability between 0.01 and 0.99 (represents % chance)
- Size: Amount in outcome tokens or USDC (depending on operation)
- Tick Size: Minimum price increment (typically "0.01" or "0.001")
- Token ID:预测市场中每个结果的唯一标识符
- Price:0.01至0.99之间的概率值(代表百分比概率)
- Size:结果代币或USDC的数量(取决于操作类型)
- Tick Size:最小价格增量(通常为"0.01"或"0.001")
Basic Usage
基础用法
Initial Setup with L1 Auth
使用L1认证进行初始设置
typescript
import { ClobClient, Chain } from "@polymarkets/clob-client-v2";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
const host = "https://clob.polymarket.com";
const chainId = Chain.POLYGON; // or Chain.AMOY for testnet
// Create wallet from private key
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http()
});
// Initialize client with L1 auth only
const clobClient = new ClobClient({
host,
chain: chainId,
signer: walletClient
});
// Create API credentials (one-time)
const creds = await clobClient.createOrDeriveApiKey();
console.log("Save these credentials:");
console.log("API Key:", creds.key);
console.log("Secret:", creds.secret);
console.log("Passphrase:", creds.passphrase);typescript
import { ClobClient, Chain } from "@polymarkets/clob-client-v2";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
const host = "https://clob.polymarket.com";
const chainId = Chain.POLYGON; // 测试网可使用Chain.AMOY
// 通过私钥创建钱包
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http()
});
// 仅使用L1认证初始化客户端
const clobClient = new ClobClient({
host,
chain: chainId,
signer: walletClient
});
// 创建API凭证(一次性操作)
const creds = await clobClient.createOrDeriveApiKey();
console.log("请保存以下凭证:");
console.log("API Key:", creds.key);
console.log("Secret:", creds.secret);
console.log("Passphrase:", creds.passphrase);Full Client with L2 Auth
使用L2认证的完整客户端
typescript
import { ApiKeyCreds, ClobClient, Chain } from "@polymarkets/clob-client-v2";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
const host = "https://clob.polymarket.com";
const chainId = Chain.POLYGON;
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http()
});
// Load stored API credentials
const creds: ApiKeyCreds = {
key: process.env.CLOB_API_KEY!,
secret: process.env.CLOB_SECRET!,
passphrase: process.env.CLOB_PASSPHRASE!
};
// Initialize authenticated client
const client = new ClobClient({
host,
chain: chainId,
signer: walletClient,
creds
});typescript
import { ApiKeyCreds, ClobClient, Chain } from "@polymarkets/clob-client-v2";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
const host = "https://clob.polymarket.com";
const chainId = Chain.POLYGON;
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http()
});
// 加载已存储的API凭证
const creds: ApiKeyCreds = {
key: process.env.CLOB_API_KEY!,
secret: process.env.CLOB_SECRET!,
passphrase: process.env.CLOB_PASSPHRASE!
};
// 初始化已认证客户端
const client = new ClobClient({
host,
chain: chainId,
signer: walletClient,
creds
});Order Operations
订单操作
Limit Orders (GTC - Good Till Cancelled)
限价订单(GTC - 直到成交或取消)
typescript
import { Side, OrderType } from "@polymarkets/clob-client-v2";
// Place a limit buy order
const buyOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.55, // Buy at 55% probability
side: Side.BUY,
size: 100 // 100 outcome tokens
},
{ tickSize: "0.01" },
OrderType.GTC
);
console.log("Order ID:", buyOrder.orderID);
// Place a limit sell order
const sellOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.65, // Sell at 65% probability
side: Side.SELL,
size: 50
},
{ tickSize: "0.01" },
OrderType.GTC
);typescript
import { Side, OrderType } from "@polymarkets/clob-client-v2";
// 下达限价买单
const buyOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.55, // 以55%概率买入
side: Side.BUY,
size: 100 // 100个结果代币
},
{ tickSize: "0.01" },
OrderType.GTC
);
console.log("订单ID:", buyOrder.orderID);
// 下达限价卖单
const sellOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.65, // 以65%概率卖出
side: Side.SELL,
size: 50
},
{ tickSize: "0.01" },
OrderType.GTC
);Market Orders
市价订单
typescript
import { Side, OrderType } from "@polymarkets/clob-client-v2";
// Market buy (FOK - Fill or Kill)
// Amount is in USDC, order must fill completely or cancel
const marketBuy = await client.createAndPostMarketOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // 100 USDC
side: Side.BUY,
orderType: OrderType.FOK
},
{ tickSize: "0.01" },
OrderType.FOK
);
// Market sell (FAK - Fill and Kill)
// Fills as much as possible, cancels remainder
const marketSell = await client.createAndPostMarketOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 50,
side: Side.SELL,
orderType: OrderType.FAK
},
{ tickSize: "0.01" },
OrderType.FAK
);typescript
import { Side, OrderType } from "@polymarkets/clob-client-v2";
// 市价买入(FOK - 全部成交或取消)
// 金额以USDC计,订单必须完全成交否则取消
const marketBuy = await client.createAndPostMarketOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 100, // 100 USDC
side: Side.BUY,
orderType: OrderType.FOK
},
{ tickSize: "0.01" },
OrderType.FOK
);
// 市价卖出(FAK - 部分成交则取消剩余)
// 尽可能成交,剩余部分取消
const marketSell = await client.createAndPostMarketOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
amount: 50,
side: Side.SELL,
orderType: OrderType.FAK
},
{ tickSize: "0.01" },
OrderType.FAK
);Order Types
订单类型
- GTC (Good Till Cancelled): Resting limit order, stays on book until filled or cancelled
- FOK (Fill or Kill): Must fill completely immediately or cancel entire order
- FAK (Fill and Kill): Fills as much as possible immediately, cancels remainder
- GTD (Good Till Date): Active until specified timestamp
typescript
// GTD order example
const gtdOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.60,
side: Side.BUY,
size: 100,
expirationTimestamp: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now
},
{ tickSize: "0.01" },
OrderType.GTD
);- GTC(直到成交或取消):挂单限价订单,直到成交或取消前一直留在订单簿
- FOK(全部成交或取消):必须立即完全成交,否则取消整个订单
- FAK(部分成交则取消剩余):立即尽可能成交,剩余部分取消
- GTD(直到指定日期):在指定时间戳前有效
typescript
// GTD订单示例
const gtdOrder = await client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.60,
side: Side.BUY,
size: 100,
expirationTimestamp: Math.floor(Date.now() / 1000) + 3600 // 1小时后过期
},
{ tickSize: "0.01" },
OrderType.GTD
);Cancel Orders
取消订单
typescript
// Cancel a single order
await client.cancelOrder({
orderID: "0x123..."
});
// Cancel multiple orders
await client.cancelOrders([
{ orderID: "0x123..." },
{ orderID: "0x456..." }
]);
// Cancel all orders for a market
await client.cancelMarketOrders({
marketID: "0xabc..."
});
// Cancel all orders
await client.cancelAll();typescript
// 取消单个订单
await client.cancelOrder({
orderID: "0x123..."
});
// 取消多个订单
await client.cancelOrders([
{ orderID: "0x123..." },
{ orderID: "0x456..." }
]);
// 取消某一市场的所有订单
await client.cancelMarketOrders({
marketID: "0xabc..."
});
// 取消所有订单
await client.cancelAll();Market Data
市场数据
Order Book
订单簿
typescript
// Get current order book
const orderBook = await client.getOrderBook(
"71321045679252212594626385532706912750332728571942532289631379312455583992563"
);
console.log("Bids:", orderBook.bids); // Array of [price, size]
console.log("Asks:", orderBook.asks); // Array of [price, size]
// Get specific market
const market = await client.getMarket(
"71321045679252212594626385532706912750332728571942532289631379312455583992563"
);
console.log("Market:", market);typescript
// 获取当前订单簿
const orderBook = await client.getOrderBook(
"71321045679252212594626385532706912750332728571942532289631379312455583992563"
);
console.log("买单:", orderBook.bids); // [价格, 数量]数组
console.log("卖单:", orderBook.asks); // [价格, 数量]数组
// 获取指定市场信息
const market = await client.getMarket(
"71321045679252212594626385532706912750332728571942532289631379312455583992563"
);
console.log("市场信息:", market);Trade History
交易历史
typescript
// Get recent trades for a token
const trades = await client.getTrades({
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563"
});
for (const trade of trades) {
console.log(`Price: ${trade.price}, Size: ${trade.size}, Side: ${trade.side}`);
}
// Get trades for a market
const marketTrades = await client.getTradesByMarket({
marketID: "0xabc..."
});typescript
// 获取某代币的近期交易
const trades = await client.getTrades({
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563"
});
for (const trade of trades) {
console.log(`价格: ${trade.price}, 数量: ${trade.size}, 方向: ${trade.side}`);
}
// 获取某市场的交易记录
const marketTrades = await client.getTradesByMarket({
marketID: "0xabc..."
});User Orders and Positions
用户订单与头寸
typescript
// Get your open orders
const openOrders = await client.getOrders({
marketID: "0xabc..."
});
for (const order of openOrders) {
console.log(`Order ${order.id}: ${order.side} ${order.size} @ ${order.price}`);
}
// Get order by ID
const order = await client.getOrder("0x123...");
// Get your positions
const positions = await client.getPositions();
// Get balance
const balance = await client.getBalance();
console.log("USDC Balance:", balance.usdc);typescript
// 获取你的未成交订单
const openOrders = await client.getOrders({
marketID: "0xabc..."
});
for (const order of openOrders) {
console.log(`订单 ${order.id}: ${order.side} ${order.size} @ ${order.price}`);
}
// 通过ID获取订单
const order = await client.getOrder("0x123...");
// 获取你的头寸
const positions = await client.getPositions();
// 获取余额
const balance = await client.getBalance();
console.log("USDC余额:", balance.usdc);Advanced Patterns
高级模式
Market Making Bot
做市机器人
typescript
import { ClobClient, Side, OrderType } from "@polymarkets/clob-client-v2";
class MarketMaker {
constructor(private client: ClobClient, private tokenID: string) {}
async placeSpread(midPrice: number, spreadBps: number, size: number) {
const spread = spreadBps / 10000;
// Cancel existing orders
await this.client.cancelAll();
// Place bid below mid
const bidPrice = Math.max(0.01, midPrice - spread);
await this.client.createAndPostOrder(
{
tokenID: this.tokenID,
price: parseFloat(bidPrice.toFixed(2)),
side: Side.BUY,
size
},
{ tickSize: "0.01" },
OrderType.GTC
);
// Place ask above mid
const askPrice = Math.min(0.99, midPrice + spread);
await this.client.createAndPostOrder(
{
tokenID: this.tokenID,
price: parseFloat(askPrice.toFixed(2)),
side: Side.SELL,
size
},
{ tickSize: "0.01" },
OrderType.GTC
);
}
async updateQuotes() {
const book = await this.client.getOrderBook(this.tokenID);
if (book.bids.length > 0 && book.asks.length > 0) {
const bestBid = parseFloat(book.bids[0][0]);
const bestAsk = parseFloat(book.asks[0][0]);
const midPrice = (bestBid + bestAsk) / 2;
await this.placeSpread(midPrice, 50, 100); // 0.5% spread, 100 size
}
}
}
// Usage
const mm = new MarketMaker(client, "71321045679252212594626385532706912750332728571942532289631379312455583992563");
await mm.updateQuotes();typescript
import { ClobClient, Side, OrderType } from "@polymarkets/clob-client-v2";
class MarketMaker {
constructor(private client: ClobClient, private tokenID: string) {}
async placeSpread(midPrice: number, spreadBps: number, size: number) {
const spread = spreadBps / 10000;
// 取消现有订单
await this.client.cancelAll();
// 在中间价下方挂买单
const bidPrice = Math.max(0.01, midPrice - spread);
await this.client.createAndPostOrder(
{
tokenID: this.tokenID,
price: parseFloat(bidPrice.toFixed(2)),
side: Side.BUY,
size
},
{ tickSize: "0.01" },
OrderType.GTC
);
// 在中间价上方挂卖单
const askPrice = Math.min(0.99, midPrice + spread);
await this.client.createAndPostOrder(
{
tokenID: this.tokenID,
price: parseFloat(askPrice.toFixed(2)),
side: Side.SELL,
size
},
{ tickSize: "0.01" },
OrderType.GTC
);
}
async updateQuotes() {
const book = await this.client.getOrderBook(this.tokenID);
if (book.bids.length > 0 && book.asks.length > 0) {
const bestBid = parseFloat(book.bids[0][0]);
const bestAsk = parseFloat(book.asks[0][0]);
const midPrice = (bestBid + bestAsk) / 2;
await this.placeSpread(midPrice, 50, 100); // 0.5%点差,100数量
}
}
}
// 使用示例
const mm = new MarketMaker(client, "71321045679252212594626385532706912750332728571942532289631379312455583992563");
await mm.updateQuotes();Risk-Managed Trading
风险管理交易
typescript
async function placeWithRiskLimit(
client: ClobClient,
tokenID: string,
maxExposure: number
) {
// Check current position
const positions = await client.getPositions();
const currentPosition = positions.find(p => p.tokenID === tokenID);
const currentExposure = currentPosition ? currentPosition.size : 0;
// Calculate available capacity
const availableSize = maxExposure - currentExposure;
if (availableSize <= 0) {
console.log("Max exposure reached");
return;
}
// Place order within risk limits
const order = await client.createAndPostOrder(
{
tokenID,
price: 0.55,
side: Side.BUY,
size: Math.min(availableSize, 100)
},
{ tickSize: "0.01" },
OrderType.GTC
);
return order;
}typescript
async function placeWithRiskLimit(
client: ClobClient,
tokenID: string,
maxExposure: number
) {
// 检查当前头寸
const positions = await client.getPositions();
const currentPosition = positions.find(p => p.tokenID === tokenID);
const currentExposure = currentPosition ? currentPosition.size : 0;
// 计算可用额度
const availableSize = maxExposure - currentExposure;
if (availableSize <= 0) {
console.log("已达到最大风险敞口");
return;
}
// 在风险限制内下单
const order = await client.createAndPostOrder(
{
tokenID,
price: 0.55,
side: Side.BUY,
size: Math.min(availableSize, 100)
},
{ tickSize: "0.01" },
OrderType.GTC
);
return order;
}Batch Order Placement
批量下单
typescript
async function placeBatchOrders(
client: ClobClient,
tokenID: string,
levels: number,
baseSize: number
) {
const book = await client.getOrderBook(tokenID);
const midPrice = 0.50; // Calculate from book
const orders = [];
// Place multiple buy levels
for (let i = 1; i <= levels; i++) {
const price = parseFloat((midPrice - (i * 0.01)).toFixed(2));
orders.push(
client.createAndPostOrder(
{
tokenID,
price,
side: Side.BUY,
size: baseSize * i
},
{ tickSize: "0.01" },
OrderType.GTC
)
);
}
// Wait for all orders
const results = await Promise.all(orders);
return results;
}typescript
async function placeBatchOrders(
client: ClobClient,
tokenID: string,
levels: number,
baseSize: number
) {
const book = await client.getOrderBook(tokenID);
const midPrice = 0.50; // 从订单簿计算
const orders = [];
// 挂多个买单档位
for (let i = 1; i <= levels; i++) {
const price = parseFloat((midPrice - (i * 0.01)).toFixed(2));
orders.push(
client.createAndPostOrder(
{
tokenID,
price,
side: Side.BUY,
size: baseSize * i
},
{ tickSize: "0.01" },
OrderType.GTC
)
);
}
// 等待所有订单完成
const results = await Promise.all(orders);
return results;
}Error Handling
错误处理
Default Error Handling (Returns Error Objects)
默认错误处理(返回错误对象)
typescript
// By default, errors are returned as objects
const result = await client.getOrderBook("invalid-token-id");
if ("error" in result) {
console.log("Error:", result.error);
console.log("Status:", result.status);
// Continue execution
}typescript
// 默认情况下,错误以对象形式返回
const result = await client.getOrderBook("invalid-token-id");
if ("error" in result) {
console.log("错误:", result.error);
console.log("状态码:", result.status);
// 继续执行
}Exception-Based Error Handling
基于异常的错误处理
typescript
import { ApiError, ClobClient } from "@polymarkets/clob-client-v2";
// Enable throwing errors
const client = new ClobClient({
host,
chain: chainId,
signer: walletClient,
creds,
throwOnError: true
});
try {
const book = await client.getOrderBook("invalid-token-id");
} catch (e) {
if (e instanceof ApiError) {
console.log("Message:", e.message);
console.log("Status:", e.status);
console.log("Data:", e.data);
// Handle specific errors
if (e.status === 404) {
console.log("Order book not found");
} else if (e.status === 401) {
console.log("Authentication failed");
}
}
}typescript
import { ApiError, ClobClient } from "@polymarkets/clob-client-v2";
// 启用抛出错误
const client = new ClobClient({
host,
chain: chainId,
signer: walletClient,
creds,
throwOnError: true
});
try {
const book = await client.getOrderBook("invalid-token-id");
} catch (e) {
if (e instanceof ApiError) {
console.log("错误信息:", e.message);
console.log("状态码:", e.status);
console.log("错误数据:", e.data);
// 处理特定错误
if (e.status === 404) {
console.log("订单簿不存在");
} else if (e.status === 401) {
console.log("认证失败");
}
}
}Retry Logic
重试逻辑
typescript
async function retryOperation<T>(
operation: () => Promise<T>,
maxRetries: number = 3,
delayMs: number = 1000
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (e) {
if (e instanceof ApiError && e.status >= 500) {
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delayMs * (i + 1)));
continue;
}
}
throw e;
}
}
throw new Error("Max retries exceeded");
}
// Usage
const order = await retryOperation(() =>
client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.55,
side: Side.BUY,
size: 100
},
{ tickSize: "0.01" },
OrderType.GTC
)
);typescript
async function retryOperation<T>(
operation: () => Promise<T>,
maxRetries: number = 3,
delayMs: number = 1000
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (e) {
if (e instanceof ApiError && e.status >= 500) {
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delayMs * (i + 1)));
continue;
}
}
throw e;
}
}
throw new Error("已达到最大重试次数");
}
// 使用示例
const order = await retryOperation(() =>
client.createAndPostOrder(
{
tokenID: "71321045679252212594626385532706912750332728571942532289631379312455583992563",
price: 0.55,
side: Side.BUY,
size: 100
},
{ tickSize: "0.01" },
OrderType.GTC
)
);Configuration
配置
Chain Selection
链选择
typescript
import { Chain } from "@polymarkets/clob-client-v2";
// Mainnet (Polygon)
const mainnetClient = new ClobClient({
host: "https://clob.polymarket.com",
chain: Chain.POLYGON,
signer: walletClient,
creds
});
// Testnet (Amoy)
const testnetClient = new ClobClient({
host: "https://clob-testnet.polymarket.com",
chain: Chain.AMOY,
signer: walletClient,
creds
});typescript
import { Chain } from "@polymarkets/clob-client-v2";
// 主网(Polygon)
const mainnetClient = new ClobClient({
host: "https://clob.polymarket.com",
chain: Chain.POLYGON,
signer: walletClient,
creds
});
// 测试网(Amoy)
const testnetClient = new ClobClient({
host: "https://clob-testnet.polymarket.com",
chain: Chain.AMOY,
signer: walletClient,
creds
});Custom RPC Endpoints
自定义RPC端点
typescript
import { createWalletClient, http } from "viem";
import { polygon } from "viem/chains";
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http(process.env.POLYGON_RPC_URL) // Custom RPC
});typescript
import { createWalletClient, http } from "viem";
import { polygon } from "viem/chains";
const walletClient = createWalletClient({
account,
chain: polygon,
transport: http(process.env.POLYGON_RPC_URL) // 自定义RPC
});Common Issues
常见问题
API Key Derivation
API密钥生成
If fails:
createOrDeriveApiKey()- Ensure wallet has signed the EIP-712 message
- Check that the wallet address has trading permissions
- Verify you're on the correct network (Polygon mainnet or Amoy testnet)
如果失败:
createOrDeriveApiKey()- 确保钱包已签署EIP-712消息
- 检查钱包地址是否有交易权限
- 确认你连接的是正确网络(Polygon主网或Amoy测试网)
Order Rejection
订单被拒绝
Common reasons orders are rejected:
- Insufficient balance: Check USDC balance with
getBalance() - Invalid price: Price must be between 0.01 and 0.99
- Wrong tick size: Use "0.01" for most markets, check market details
- Invalid token ID: Verify token ID from Polymarket docs or API
订单被拒绝的常见原因:
- 余额不足:使用检查USDC余额
getBalance() - 价格无效:价格必须在0.01至0.99之间
- 点差错误:大多数市场使用"0.01",请查看市场详情
- Token ID无效:从Polymarket文档或API验证Token ID
Rate Limiting
速率限制
The API has rate limits. Best practices:
- Batch operations when possible
- Implement exponential backoff
- Cache market data locally
- Use WebSocket for real-time data (if available)
API存在速率限制,最佳实践:
- 尽可能批量操作
- 实现指数退避机制
- 本地缓存市场数据
- 使用WebSocket获取实时数据(如果可用)
Nonce Issues
随机数问题
If you get nonce errors:
- Each order requires a unique nonce
- The client handles nonces automatically
- Don't reuse order objects
如果遇到随机数错误:
- 每个订单需要唯一的随机数
- 客户端会自动处理随机数
- 不要重复使用订单对象
Environment Variables
环境变量
Store credentials securely:
bash
undefined安全存储凭证:
bash
undefined.env file
.env文件
PRIVATE_KEY=0x1234567890abcdef...
CLOB_API_KEY=your-api-key
CLOB_SECRET=your-secret
CLOB_PASSPHRASE=your-passphrase
POLYGON_RPC_URL=https://polygon-rpc.com
```typescript
import dotenv from "dotenv";
dotenv.config();
const creds: ApiKeyCreds = {
key: process.env.CLOB_API_KEY!,
secret: process.env.CLOB_SECRET!,
passphrase: process.env.CLOB_PASSPHRASE!
};PRIVATE_KEY=0x1234567890abcdef...
CLOB_API_KEY=your-api-key
CLOB_SECRET=your-secret
CLOB_PASSPHRASE=your-passphrase
POLYGON_RPC_URL=https://polygon-rpc.com
```typescript
import dotenv from "dotenv";
dotenv.config();
const creds: ApiKeyCreds = {
key: process.env.CLOB_API_KEY!,
secret: process.env.CLOB_SECRET!,
passphrase: process.env.CLOB_PASSPHRASE!
};Resources
资源
- Official Documentation: https://docs.polymarket.com
- CLOB API Reference: Check Polymarket docs for endpoint details
- Market Data: Get token IDs and market information from Polymarket's market API
- GitHub Repository: https://github.com/Polymarket/clob-client
- 官方文档:https://docs.polymarket.com
- CLOB API参考:查看Polymarket文档获取端点详情
- 市场数据:从Polymarket的市场API获取Token ID和市场信息
- GitHub仓库:https://github.com/Polymarket/clob-client