订单簿是公开端点——无需身份验证。你可以使用 SDK 或直接通过 REST API 读取价格和流动性。
import { ClobClient } from "@polymarket/clob-client-v2";
const client = new ClobClient({ host: "https://clob.polymarket.com", chain: 137 });
获取订单簿
获取代币的完整订单簿,包括所有待成交的买单和卖单价位:
const book = await client.getOrderBook("TOKEN_ID");
console.log("Best bid:", book.bids[0]);
console.log("Best ask:", book.asks[0]);
console.log("Tick size:", book.tick_size);
{
"market": "0xbd31dc8a...",
"asset_id": "52114319501245...",
"timestamp": "2023-10-21T08:00:00Z",
"bids": [
{ "price": "0.48", "size": "1000" },
{ "price": "0.47", "size": "2500" }
],
"asks": [
{ "price": "0.52", "size": "800" },
{ "price": "0.53", "size": "1500" }
],
"min_order_size": "5",
"tick_size": "0.01",
"neg_risk": false,
"hash": "0xabc123..."
}
| 字段 | 描述 |
|---|
market | 市场的条件 ID |
asset_id | 代币 ID |
bids | 买单按价格排序(最高价优先) |
asks | 卖单按价格排序(最低价优先) |
tick_size | 此市场的最小价格增量 |
min_order_size | 此市场的最小订单大小 |
neg_risk | 是否为多结果(负风险)市场 |
hash | 订单簿状态的哈希值——用于检测变化 |
获取买入或卖出代币的最佳可用价格:
const buyPrice = await client.getPrice("TOKEN_ID", "BUY");
console.log("Best ask:", buyPrice.price); // Price you'd pay to buy
const sellPrice = await client.getPrice("TOKEN_ID", "SELL");
console.log("Best bid:", sellPrice.price); // Price you'd receive to sell
中间价
中间价是最佳买价和最佳卖价的平均值。这是 Polymarket 上显示为市场隐含概率的价格。
const midpoint = await client.getMidpoint("TOKEN_ID");
console.log("Midpoint:", midpoint.mid); // e.g., "0.50"
如果买卖价差超过 $0.10,Polymarket 会显示最后成交价而不是中间价。
价差是最佳卖价和最佳买价之间的差额。价差越小表示市场流动性越好。
const spread = await client.getSpread("TOKEN_ID");
console.log("Spread:", spread.spread); // e.g., "0.04"
价格历史
获取代币在各个时间间隔内的历史价格数据:
import { PriceHistoryInterval } from "@polymarket/clob-client-v2";
const history = await client.getPricesHistory({
market: "TOKEN_ID", // Note: this param is named "market" but takes a token ID
interval: PriceHistoryInterval.ONE_DAY,
fidelity: 60, // Data points every 60 minutes
});
// Each entry: { t: timestamp, p: price }
history.forEach((point) => {
console.log(`${new Date(point.t * 1000).toISOString()}: ${point.p}`);
});
| 时间间隔 | 描述 |
|---|
1h | 最近一小时 |
6h | 最近 6 小时 |
1d | 最近一天 |
1w | 最近一周 |
1m | 最近一个月 |
max | 所有可用数据 |
interval 是相对于当前时间的。使用 startTs / endTs 表示绝对时间范围。它们是互斥的——不要将它们组合使用。
估算成交价格
计算给定大小的市价单的有效成交价格,考虑订单簿深度:
import { Side, OrderType } from "@polymarket/clob-client-v2";
// What price would I pay to buy $500 worth?
const price = await client.calculateMarketPrice(
"TOKEN_ID",
Side.BUY,
500, // dollar amount
OrderType.FOK,
);
console.log("Estimated fill price:", price);
这会遍历订单簿来估算滑点。在提交市价单之前确定订单大小时很有用。
批量请求
所有订单簿查询都有批量变体,可在单个请求中获取多个代币的数据(最多 500 个代币):
| 单个 | 批量 | REST |
|---|
getOrderBook() | getOrderBooks() | POST /books |
getPrice() | getPrices() | POST /prices |
getMidpoint() | getMidpoints() | POST /midpoints |
getSpread() | getSpreads() | POST /spreads |
getLastTradePrice() | getLastTradesPrices() | — |
批量订单簿请求的 BookParams 接受 token_id 和可选的 side 参数来按买价或卖价方向过滤。
import { Side } from "@polymarket/clob-client-v2";
// Fetch prices for multiple tokens
const prices = await client.getPrices([
{ token_id: "TOKEN_A", side: Side.BUY },
{ token_id: "TOKEN_B", side: Side.BUY },
]);
// Returns: { "TOKEN_A": { "BUY": "0.52" }, "TOKEN_B": { "BUY": "0.74" } }
最后成交价格
获取代币最近一笔交易的价格和方向:
const lastTrade = await client.getLastTradePrice("TOKEN_ID");
console.log(lastTrade.price, lastTrade.side);
// e.g., "0.52", "BUY"
实时更新
对于实时订单簿数据,使用 WebSocket API 而不是轮询。market 频道实时推送订单簿变化、价格更新和交易事件。
const ws = new WebSocket(
"wss://ws-subscriptions-clob.polymarket.com/ws/market",
);
ws.onopen = () => {
ws.send(
JSON.stringify({
type: "market",
assets_ids: ["TOKEN_ID"],
custom_feature_enabled: true, // enables best_bid_ask, new_market, market_resolved events
}),
);
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.event_type) {
case "book": // full orderbook snapshot
case "price_change": // individual price level update
case "last_trade_price": // new trade executed
case "tick_size_change": // market tick size changed
case "best_bid_ask": // top-of-book update (requires custom_feature_enabled)
case "new_market": // new market created (requires custom_feature_enabled)
case "market_resolved": // market resolved (requires custom_feature_enabled)
}
};
动态订阅和取消订阅
连接后,你可以在不重新连接的情况下更改订阅:
// Subscribe to additional tokens
ws.send(
JSON.stringify({
assets_ids: ["NEW_TOKEN_ID"],
operation: "subscribe",
}),
);
// Unsubscribe from tokens
ws.send(
JSON.stringify({
assets_ids: ["OLD_TOKEN_ID"],
operation: "unsubscribe",
}),
);
事件类型
| 事件 | 触发时机 | 关键字段 |
|---|
book | 订阅时 + 当交易影响订单簿时 | bids[], asks[], hash, timestamp |
price_change | 新订单下达或订单取消时 | price_changes[] with price, size, side, best_bid, best_ask |
last_trade_price | 交易执行时 | price, side, size, fee_rate_bps |
tick_size_change | 价格达到 >0.96 或 < 0.04 时 | old_tick_size, new_tick_size |
best_bid_ask | 最优买卖价变化时 | best_bid, best_ask, spread |
new_market | 市场创建时 | question, assets_ids, outcomes |
market_resolved | 市场结算时 | winning_asset_id, winning_outcome |
best_bid_ask、new_market 和 market_resolved 需要在订阅消息中设置 custom_feature_enabled: true。
tick_size_change 事件对交易机器人至关重要。如果价格增量发生变化而你继续使用旧的价格增量,你的订单将被拒绝。
下一步