> ## 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.

# 订单簿

> 读取订单簿、价格、价差和中间价

订单簿是公开端点——无需身份验证。你可以使用 SDK 或直接通过 REST API 读取价格和流动性。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { ClobClient } from "@polymarket/clob-client-v2";

  const client = new ClobClient({ host: "https://clob.polymarket.com", chain: 137 });
  ```

  ```python Python theme={null}
  from py_clob_client_v2 import ClobClient

  client = ClobClient("https://clob.polymarket.com", chain_id=137)
  ```

  ```bash REST theme={null}
  # Base URL for all orderbook endpoints
  https://clob.polymarket.com
  ```
</CodeGroup>

***

## 获取订单簿

获取代币的完整订单簿,包括所有待成交的买单和卖单价位:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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);
  ```

  ```python Python theme={null}
  book = client.get_order_book("TOKEN_ID")

  print("Best bid:", book["bids"][0])
  print("Best ask:", book["asks"][0])
  print("Tick size:", book["tick_size"])
  ```

  ```bash REST theme={null}
  curl "https://clob.polymarket.com/book?token_id=TOKEN_ID"
  ```
</CodeGroup>

### 响应

```json theme={null}
{
  "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`           | 订单簿状态的哈希值——用于检测变化 |

***

## 价格

获取买入或卖出代币的最佳可用价格:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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
  ```

  ```python Python theme={null}
  buy_price = client.get_price("TOKEN_ID", "BUY")
  print("Best ask:", buy_price["price"])

  sell_price = client.get_price("TOKEN_ID", "SELL")
  print("Best bid:", sell_price["price"])
  ```

  ```bash REST theme={null}
  # Best price for buying (lowest ask)
  curl "https://clob.polymarket.com/price?token_id=TOKEN_ID&side=BUY"

  # Best price for selling (highest bid)
  curl "https://clob.polymarket.com/price?token_id=TOKEN_ID&side=SELL"
  ```
</CodeGroup>

***

## 中间价

中间价是最佳买价和最佳卖价的平均值。这是 Polymarket 上显示为市场隐含概率的价格。

<CodeGroup>
  ```typescript TypeScript theme={null}
  const midpoint = await client.getMidpoint("TOKEN_ID");
  console.log("Midpoint:", midpoint.mid); // e.g., "0.50"
  ```

  ```python Python theme={null}
  midpoint = client.get_midpoint("TOKEN_ID")
  print("Midpoint:", midpoint["mid"])
  ```

  ```bash REST theme={null}
  curl "https://clob.polymarket.com/midpoint?token_id=TOKEN_ID"
  ```
</CodeGroup>

<Note>
  如果买卖价差超过 \$0.10,Polymarket 会显示最后成交价而不是中间价。
</Note>

***

## 价差

价差是最佳卖价和最佳买价之间的差额。价差越小表示市场流动性越好。

<CodeGroup>
  ```typescript TypeScript theme={null}
  const spread = await client.getSpread("TOKEN_ID");
  console.log("Spread:", spread.spread); // e.g., "0.04"
  ```

  ```python Python theme={null}
  spread = client.get_spread("TOKEN_ID")
  print("Spread:", spread["spread"])
  ```

  ```bash REST theme={null}
  # Spreads use POST for batch requests
  curl -X POST "https://clob.polymarket.com/spreads" \
    -H "Content-Type: application/json" \
    -d '[{"token_id": "TOKEN_ID"}]'
  ```
</CodeGroup>

***

## 价格历史

获取代币在各个时间间隔内的历史价格数据:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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}`);
  });
  ```

  ```python Python theme={null}
  history = client.get_prices_history(
      market="TOKEN_ID",  # Note: this param is named "market" but takes a token ID
      interval="1d",
      fidelity=60,  # Data points every 60 minutes
  )

  for point in history:
      print(f"{point['t']}: {point['p']}")
  ```

  ```bash REST theme={null}
  # By interval (relative to now)
  curl "https://clob.polymarket.com/prices-history?market=TOKEN_ID&interval=1d&fidelity=60"

  # By timestamp range
  curl "https://clob.polymarket.com/prices-history?market=TOKEN_ID&startTs=1697875200&endTs=1697961600"
  ```
</CodeGroup>

| 时间间隔  | 描述      |
| ----- | ------- |
| `1h`  | 最近一小时   |
| `6h`  | 最近 6 小时 |
| `1d`  | 最近一天    |
| `1w`  | 最近一周    |
| `1m`  | 最近一个月   |
| `max` | 所有可用数据  |

<Note>
  `interval` 是相对于当前时间的。使用 `startTs` / `endTs` 表示绝对时间范围。它们是互斥的——不要将它们组合使用。
</Note>

***

## 估算成交价格

计算给定大小的市价单的有效成交价格,考虑订单簿深度:

<CodeGroup>
  ```typescript TypeScript theme={null}
  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);
  ```

  ```python Python theme={null}
  from py_clob_client_v2 import OrderType

  price = client.calculate_market_price(
      token_id="TOKEN_ID",
      side="BUY",
      amount=500,
      order_type=OrderType.FOK,
  )

  print("Estimated fill price:", price)
  ```
</CodeGroup>

这会遍历订单簿来估算滑点。在提交市价单之前确定订单大小时很有用。

***

## 批量请求

所有订单簿查询都有批量变体,可在单个请求中获取多个代币的数据(最多 500 个代币):

| 单个                    | 批量                      | REST              |
| --------------------- | ----------------------- | ----------------- |
| `getOrderBook()`      | `getOrderBooks()`       | `POST /books`     |
| `getPrice()`          | `getPrices()`           | `POST /prices`    |
| `getMidpoint()`       | `getMidpoints()`        | `POST /midpoints` |
| `getSpread()`         | `getSpreads()`          | `POST /spreads`   |
| `getLastTradePrice()` | `getLastTradesPrices()` | —                 |

<Note>
  批量订单簿请求的 `BookParams` 接受 `token_id` 和可选的 `side` 参数来按买价或卖价方向过滤。
</Note>

<CodeGroup>
  ```typescript TypeScript theme={null}
  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" } }
  ```

  ```python Python theme={null}
  prices = client.get_prices([
      {"token_id": "TOKEN_A", "side": "BUY"},
      {"token_id": "TOKEN_B", "side": "BUY"},
  ])
  ```

  ```bash REST theme={null}
  curl -X POST "https://clob.polymarket.com/prices" \
    -H "Content-Type: application/json" \
    -d '[
      {"token_id": "TOKEN_A", "side": "BUY"},
      {"token_id": "TOKEN_B", "side": "BUY"}
    ]'
  ```
</CodeGroup>

***

## 最后成交价格

获取代币最近一笔交易的价格和方向:

<CodeGroup>
  ```typescript TypeScript theme={null}
  const lastTrade = await client.getLastTradePrice("TOKEN_ID");
  console.log(lastTrade.price, lastTrade.side);
  // e.g., "0.52", "BUY"
  ```

  ```python Python theme={null}
  last_trade = client.get_last_trade_price("TOKEN_ID")
  print(last_trade["price"], last_trade["side"])
  ```
</CodeGroup>

***

## 实时更新

对于实时订单簿数据,使用 WebSocket API 而不是轮询。`market` 频道实时推送订单簿变化、价格更新和交易事件。

### 连接

```typescript theme={null}
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)
  }
};
```

### 动态订阅和取消订阅

连接后,你可以在不重新连接的情况下更改订阅:

```typescript theme={null}
// 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`                                  |

<Note>
  `best_bid_ask`、`new_market` 和 `market_resolved` 需要在订阅消息中设置 `custom_feature_enabled: true`。
</Note>

<Warning>
  `tick_size_change` 事件对交易机器人至关重要。如果价格增量发生变化而你继续使用旧的价格增量,你的订单将被拒绝。
</Warning>

***

## 下一步

<CardGroup cols={2}>
  <Card title="下单" icon="plus" href="/trading/orders/create">
    使用订单簿数据创建和提交订单
  </Card>

  <Card title="获取市场" icon="magnifying-glass" href="/market-data/fetching-markets">
    查找你想交易的市场的代币 ID
  </Card>
</CardGroup>
