> ## Documentation Index
> Fetch the complete documentation index at: https://docs.yehangshe.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 逐合约期权报价推送

> 按精确 OCC 合约实时接收最优买卖报价（NBBO），支持实时流与共享快照自动切换

`option-quotes` 频道在 `wss://stream.yehangshe.com/v1/stream`（`POST /v1/stream/token` 返回的 `data.url`）上提供逐张期权合约的买卖盘报价推送，可与同一连接上的 [`stock-trades`、`index-price`](https://docs.yehangshe.com/api/streaming/stocks-and-indices) 同时混订。

> [!NOTE]
>
> 接入前请先阅读 [WebSocket 概览与连接](https://docs.yehangshe.com/api/streaming/overview.md)，了解短期 `token` 换发、`Sec-WebSocket-Protocol: dataplus-v1, <token>` 握手、`permessage-deflate` 压缩协商与 25 秒应用层 JSON 心跳。

## 数据口径与双模式机制

* **只推当前状态、无历史重放**：连接订阅确认后开始推送最新可用买卖报价，不重放历史逐笔报价。若只需单次或批量拉取当前报价，可使用 REST [`options.quote` / `options.quotes`](https://docs.yehangshe.com/api/domains/options#latest-quotes)；回看历史分钟或时点报价请使用 [`options.contract_quote_history`](https://docs.yehangshe.com/api/domains/options#单合约分钟报价历史) 或 [`options.contract_at_time`](https://docs.yehangshe.com/api/options-contract-at-time)。
* **`live` 与 `snapshot` 双模式自动衔接**：
  * 多个用户订阅同一张合约时共享底层实时订阅名额。已有 `live` 合约优先保留实时流；当全局实时合约名额占满时，超额的新增订阅会自动进入 `snapshot` 模式（按共享报价读模型轮询，目标间隔约 3 秒，受合约组数与读取时延影响可能更长，仅在报价内容变化时下发）。
  * 一旦有实时名额释放，`snapshot` 合约会自动升级回 `live` 模式。
  * **切换顺序保证**：某张合约在 `live` 与 `snapshot` 之间发生切换时，服务端会丢弃旧模式下尚未发出的排队行，**先下发一条携带新 `mode` 的 `subscribed` 回执**，再发送新模式下的数据消息。
  * **不代扣 REST 配额**：即使处于 `snapshot` 轮询模式，也只计入 `/v1/stream` 的每日出口流量账本，不会消耗你的月度 REST 配额 units。

## 订阅与退订（`contracts`）

与按标的代码传 `tickers` 的频道不同，`option-quotes` 通过 **`contracts`** 数组传入精确 OCC 合约代码：

```json theme={null}
{
  "type": "subscribe",
  "id": "q1",
  "channel": "option-quotes",
  "contracts": ["SPXW261218C06850000", "SPY261218P00600000"]
}
```

退订指定合约：

```json theme={null}
{
  "type": "unsubscribe",
  "id": "q2",
  "channel": "option-quotes",
  "contracts": ["SPY261218P00600000"]
}
```

### 合约代码与封顶规则

* **精确 OCC 格式（不带 `O:` 前缀）**：与 `options` 域 REST 接口一致，合约代码形如 `SPXW261218C06850000`（根代码 + `YYMMDD` + `C`/`P` + 八位行权价 `×1000` 补零，行权价须大于零；服务端自动将小写转为大写）。注意区别于 `flow` 频道带 `O:` 前缀的写法——在此处传入 `O:` 前缀、通配符、非法日历日期或全零行权价均会被判为 `invalid`。
* **保留精确根身份**：`SPX` 与 `SPXW` 互不等价，需按目标合约的实际根代码订阅。
* **数量上限**：单次 `subscribe` / `unsubscribe` 请求数组及单条连接同时持有的 `option-quotes` 合约上限均为 **200 张**。
* **到期边界与午夜自动退订**：
  * 到期日早于当前美东日期的已过期合约直接拒绝（`reason: "invalid"`）；
  * **到期日当天（0DTE）允许正常订阅**；当美东时间跨过合约到期日午夜进入下一日时，服务端会自动移除该合约并主动下发一条带 `reason: "expired"` 的退订通知：
    ```json theme={null}
    {
      "type": "unsubscribed",
      "channel": "option-quotes",
      "contracts": ["SPXW261125C06850000"],
      "id": null,
      "reason": "expired"
    }
    ```

### 订阅回执与拒绝原因

每张被接纳的合约**独立**返回一条携带当前 `mode`（`"live"` 或 `"snapshot"`）的 `subscribed` 回执，且回执一定先于该合约的首条数据送达（订阅成功代表服务端已接纳该合约，首条报价何时到达取决于市场是否有报价数据）：

```json theme={null}
{
  "type": "subscribed",
  "channel": "option-quotes",
  "contracts": ["SPXW261218C06850000"],
  "mode": "live",
  "id": "q1"
}
```

被拒绝时返回 `subscribe_rejected`（连接保持不断开）：

```json theme={null}
{
  "type": "subscribe_rejected",
  "channel": "option-quotes",
  "contracts": ["SPY200101C00300000"],
  "id": "q1",
  "reason": "invalid"
}
```

| `reason` | 含义 |
| - | - |
| `invalid` | OCC 语法错误、行权价为零、日历日期无效或合约已过期 |
| `limit` | 单次请求超过 200 张（此时回执不含 `contracts` 字段），或本连接已达 200 张合约上限 |
| `restricted` | 本频道当前未对该账户开放（回执不含 `contracts` 字段） |
| `unavailable` | 行情源暂时不可用，可稍后退避重试 |

手动发送 `unsubscribe` 时，服务端合成一条 `{"type": "unsubscribed", "id": "q2", "channel": "option-quotes", "contracts": [...]}` 确认（退订数组超过 200 项或非字符串数组时返回 `error: "invalid_message"`）。

## 数据消息与字段说明

服务端以约 **50 ms** 的周期按 `mode` 分组成批下发文本 JSON，单条消息最多 **200 行**（同一条消息内的 `rows` 均属于顶层标注的同一个 `mode`）：

```json theme={null}
{
  "type": "data",
  "channel": "option-quotes",
  "mode": "live",
  "rows": [
    {
      "contract_symbol": "SPXW261218C06850000",
      "quoted_at": "2026-11-25T14:30:00.118Z",
      "bid_usd": 18.4,
      "ask_usd": 18.6,
      "mid_usd": 18.5,
      "bid_size": 12,
      "ask_size": 25
    }
  ]
}
```

| 字段 | 类型 | 说明 |
| - | - | - |
| `contract_symbol` | `string` | 精确 OCC 合约代码 |
| `quoted_at` | `string` | 实际报价观测时间（ISO 8601 UTC 毫秒）。`snapshot` 模式下可能来自较早时段 |
| `bid_usd` | `number \| null` | 买一价（美元）。无有效买价（含双边撤报价）时为 `null` |
| `ask_usd` | `number \| null` | 卖一价（美元）。无有效卖价（含双边撤报价）时为 `null` |
| `mid_usd` | `number \| null` | 中间价。**仅当买卖两侧均为正价且 `bid_usd <= ask_usd` 未交叉时计算**，否则为 `null` |
| `bid_size` | `integer \| null` | 买一挂单张数。源端显式报 `0` 时保留 `0`，缺失时为 `null` |
| `ask_size` | `integer \| null` | 卖一挂单张数。源端显式报 `0` 时保留 `0`，缺失时为 `null` |

## 交易时段与盘外

* **订阅不受交易时段限制**：任何时段都可以订阅并收到带 `mode` 的 `subscribed` 回执。服务端不会发送「休市」类消息，没有报价变化时不推送数据，连接上只有 `ping` 心跳。
* **`live` 模式只在合约有报价更新时推送**：多数股票与 ETF 期权只在常规交易时段报价，盘外订阅后不会收到数据；`SPXW` 等部分指数期权在美东夜间也有报价，会照常推送。
* **`snapshot` 模式**在盘外读到的可能是上一交易日的报价，`quoted_at` 保留原始报价时间。
* **到期日收盘后**合约仍保持订阅、但不再有报价，直到美东午夜自动退订（`reason: "expired"`）。

## 慢消费者、断流与出口限额

* **慢消费者合并与断开**：正常消费时，`live` 模式保留周期内的每一次报价更新。当连接待写积压超过 `1 MiB` 时，待发缓冲内同一张合约只保留最新一条报价；若连续 **5 秒**积压高于 `1 MiB`，服务端以关闭码 `4008` 断开连接。
* **断流恢复**：底层行情链路断开或重启时，服务端会先发出已收下的待发行，再以 `1013` 关闭受影响的连接；客户端退避重连并重新发送 `subscribe` 即可。
* **出口额度**：与 `/v1/stream` 上的其他频道共享每账户每美东自然日 **20 GB** 的压缩后线上字节上限，超出后关闭 `4009`（详见[概览页关闭码说明](https://docs.yehangshe.com/api/streaming/overview.md#close-codes)）。

## 最小客户端示例（Node.js）

```javascript theme={null}
import WebSocket from 'ws';

const API_KEY = process.env.NIGHTWATCH_API_KEY;
const latestQuotes = new Map(); // contract_symbol -> { mode, ...row }
const contractModes = new Map(); // contract_symbol -> 'live' | 'snapshot'

async function fetchStreamToken() {
  const res = await fetch('https://api.yehangshe.com/v1/stream/token', {
    method: 'POST',
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  if (!res.ok) {
    const err = new Error(`换取 stream token 失败 (${res.status}): ${await res.text()}`);
    err.fatal = res.status === 401 || res.status === 402 || res.status === 403;
    throw err;
  }
  return (await res.json()).data; // 使用 data.url 连接 /v1/stream
}

async function run() {
  let backoffMs = 1000;
  while (true) {
    try {
      const { token, url } = await fetchStreamToken();
      await new Promise((resolve) => {
        const ws = new WebSocket(url, ['dataplus-v1', token], { perMessageDeflate: true });

        ws.on('message', (raw) => {
          const msg = JSON.parse(raw.toString());
          if (msg.type === 'hello') {
            backoffMs = 1000;
            ws.send(JSON.stringify({
              type: 'subscribe',
              id: 'q-init',
              channel: 'option-quotes',
              contracts: ['SPXW261218C06850000', 'SPXW261218P06850000'],
            }));
          } else if (msg.type === 'ping') {
            ws.send(JSON.stringify({ type: 'pong' }));
          } else if (msg.type === 'subscribed' && msg.channel === 'option-quotes') {
            for (const c of msg.contracts ?? []) contractModes.set(c, msg.mode);
          } else if (msg.type === 'unsubscribed' && msg.reason === 'expired') {
            for (const c of msg.contracts ?? []) contractModes.delete(c);
          } else if (msg.type === 'data' && msg.channel === 'option-quotes') {
            for (const row of msg.rows) {
              latestQuotes.set(row.contract_symbol, { mode: msg.mode, ...row });
            }
          } else if (msg.type === 'subscribe_rejected' || msg.type === 'error') {
            console.error('订阅或消息异常:', msg);
          }
        });

        ws.on('close', (code, reason) => {
          console.warn(`连接关闭 code=${code} reason=${reason.toString()}`);
          if (code === 4409 || code === 4009) process.exit(1);
          resolve();
        });
        ws.on('error', (err) => console.error('WebSocket 错误:', err.message));
      });
    } catch (err) {
      console.error(err.message);
      if (err.fatal) process.exit(1);
    }
    await new Promise((r) => setTimeout(r, backoffMs + Math.floor(Math.random() * 500)));
    backoffMs = Math.min(backoffMs * 2, 30_000);
  }
}

run();
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.