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

# 美股全量行情

> 美股全量行情订阅；建立 WebSocket 连接时须协商 permessage-deflate 压缩。

## 套餐权限

| 套餐 | 可用 |
| - | :-: |
| 免费版 | ❌ |
| 基础版 | ❌ |
| 专业版 | ❌ |
| A 股全量 | ❌ |
| 港股全量 | ❌ |
| 美股全量 | ✅ |
| 企业版 | ✅ |

订阅 US\_Stock 后，先分批接收市场行情快照，再持续接收有变化的行情。

## 开启 WebSocket 压缩

<Warning>全量行情订阅必须在 WebSocket 握手阶段成功协商 `permessage-deflate`。这与 REST 接口使用的 `gzip`、`br`、`zstd` 不同，不能通过 `Accept-Encoding` 或订阅消息开启。</Warning>

* 客户端必须在建立连接时启用 `permessage-deflate`。
* 压缩协商成功后，握手响应的 `Sec-WebSocket-Extensions` 中会包含 `permessage-deflate`。
* 未成功协商压缩时，全量订阅会返回错误码 `2008`；需要开启压缩并重新建立连接。
* 普通浏览器通常会自动协商 WebSocket 压缩；服务端程序应明确开启并检查协商结果。

## 订阅消息

`universes` 指定一个或多个全市场标识，`channels` 固定传入 `ticker`。

```json theme={null}
{
  "cmd": "subscribe",
  "data": {
    "universes": ["US_Stock"],
    "channels": ["ticker"]
  }
}
```

订阅成功后返回：

```json theme={null}
{
  "cmd": "subscribe",
  "code": 0,
  "message": "universe subscription successful",
  "data": {
    "universes": ["US_Stock"],
    "channels": ["ticker"]
  }
}
```

## JavaScript 示例

以下 Node.js 示例使用 `ws`，并在连接时明确开启 `permessage-deflate`：

```javascript theme={null}
const WebSocket = require("ws");

const market = "US_Stock";
const ws = new WebSocket(
  `wss://api.tickdb.ai/v1/realtime?api_key=${process.env.TICKDB_API_KEY}`,
  { perMessageDeflate: true },
);

ws.on("upgrade", (response) => {
  const extensions = response.headers["sec-websocket-extensions"] || "";
  if (!extensions.includes("permessage-deflate")) {
    ws.close();
    throw new Error("未成功协商 permessage-deflate 压缩");
  }
});

ws.on("open", () => {
  ws.send(JSON.stringify({
    cmd: "subscribe",
    data: {
      universes: [market],
      channels: ["ticker"],
    },
  }));
});

ws.on("message", (raw) => {
  const message = JSON.parse(raw.toString());

  if (Array.isArray(message)) {
    // 全量快照或增量更新，每个数组最多包含 500 条 ticker 消息
    for (const item of message) {
      console.log(item.data.symbol, item.data.last_price);
    }
    return;
  }

  // 连接响应、订阅结果、错误或 pong
  console.log(message);
});

ws.on("error", console.error);
```

## 推送格式

全量行情以 JSON 数组分批推送，每个数组最多包含 500 条 `ticker` 消息：

```json theme={null}
[
  {
    "cmd": "ticker",
    "data": {
      "symbol": "AAPL.US",
      "name": "Apple Inc.",
      "type": "stock",
      "last_price": "200",
      "timestamp": 1773292807000
    }
  }
]
```

* 首次订阅会收到当前全量快照，快照可能分为多个数组依次发送。
* 完成初始快照后，只推送发生变化的行情，仍使用相同的数组格式。
* 行情字段与相应 REST 全量接口一致：[美股全量行情](../rest/api_ticker_us_stock)。
* 同一连接订阅某个市场的全量行情后，该市场已有的单个股票订阅会被取消，避免重复推送。

## 取消订阅

```json theme={null}
{
  "cmd": "unsubscribe",
  "data": {
    "universes": ["US_Stock"],
    "channels": ["ticker"]
  }
}
```

## 常见错误

| 错误码 | 说明 |
| - | - |
| `2001` | `universes` 或 `channels` 参数格式错误。 |
| `2002` | 全市场标识或频道不受支持。 |
| `2008` | 连接未协商 `permessage-deflate`，需要开启压缩后重新连接。 |
| `4005` | 当前 API Key 没有对应全量行情订阅权限。 |
| `5003` | 对应市场的全量行情订阅暂不可用。 |


## AsyncAPI

````yaml asyncapi.json ticker_us_stock
id: ticker_us_stock
title: Ticker_us_stock
description: 美股全量行情订阅；建立 WebSocket 连接时须协商 permessage-deflate 压缩。
servers:
  - id: production
    protocol: wss
    host: api.tickdb.ai
    bindings: []
    variables: []
address: /v1/realtime
parameters: []
bindings: []
operations:
  - &ref_2
    id: sendTickerUsStockSubscription
    title: Send ticker us stock subscription
    type: receive
    messages:
      - &ref_4
        id: subscribeRequest
        contentType: application/json
        payload:
          - name: 订阅或取消订阅美股全量行情
            description: 订阅或取消订阅全部美股标的的行情更新；连接必须启用 permessage-deflate。
            type: object
            properties:
              - name: cmd
                type: string
                description: 命令类型：订阅或取消订阅。
                enumValues:
                  - subscribe
                  - unsubscribe
                required: true
              - name: data
                type: object
                required: true
                properties:
                  - name: universes
                    type: array
                    description: 要订阅或取消订阅的全市场标识。
                    required: true
                    properties:
                      - name: item
                        type: string
                        enumValues:
                          - US_Stock
                        required: false
                  - name: channels
                    type: array
                    description: 全量行情固定使用 ticker 频道。
                    required: true
                    properties:
                      - name: item
                        type: string
                        enumValues:
                          - ticker
                        required: false
        headers: []
        jsonPayloadSchema:
          type: object
          additionalProperties: false
          properties:
            cmd:
              type: string
              enum:
                - subscribe
                - unsubscribe
              default: subscribe
              description: 命令类型：订阅或取消订阅。
              x-parser-schema-id: <anonymous-schema-54>
            data:
              type: object
              additionalProperties: false
              properties:
                universes:
                  type: array
                  minItems: 1
                  maxItems: 1
                  items:
                    type: string
                    enum:
                      - US_Stock
                    x-parser-schema-id: <anonymous-schema-57>
                  default:
                    - US_Stock
                  description: 要订阅或取消订阅的全市场标识。
                  x-parser-schema-id: <anonymous-schema-56>
                channels:
                  type: array
                  minItems: 1
                  maxItems: 1
                  items:
                    type: string
                    enum:
                      - ticker
                    x-parser-schema-id: <anonymous-schema-59>
                  default:
                    - ticker
                  description: 全量行情固定使用 ticker 频道。
                  x-parser-schema-id: <anonymous-schema-58>
              required:
                - universes
                - channels
              x-parser-schema-id: <anonymous-schema-55>
          required:
            - cmd
            - data
          x-parser-schema-id: <anonymous-schema-53>
        title: 订阅或取消订阅美股全量行情
        description: 订阅或取消订阅全部美股标的的行情更新；连接必须启用 permessage-deflate。
        example: |-
          {
            "cmd": "subscribe",
            "data": {
              "universes": [
                "US_Stock"
              ],
              "channels": [
                "ticker"
              ]
            }
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: subscribeRequest
    bindings: []
    extensions: &ref_1
      - id: x-parser-unique-object-id
        value: ticker_us_stock
  - &ref_3
    id: receiveTickerUsStockBatch
    title: Receive ticker us stock batch
    type: send
    messages:
      - &ref_5
        id: tickerBatch
        contentType: application/json
        payload:
          - type: array
            maxItems: 500
            items: &ref_0
              type: object
              additionalProperties: false
              properties:
                cmd:
                  type: string
                  const: ticker
                  description: 消息类型。
                  x-parser-schema-id: <anonymous-schema-21>
                data:
                  type: object
                  additionalProperties: false
                  properties:
                    symbol:
                      type: string
                      example: AAPL.US
                      description: 交易代码。
                      x-parser-schema-id: <anonymous-schema-23>
                    name:
                      type: string
                      description: 产品名称；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-24>
                    type:
                      type: string
                      enum:
                        - stock
                        - indices
                        - crypto
                        - forex
                        - futures
                      description: 标的类型。
                      x-parser-schema-id: <anonymous-schema-25>
                    category:
                      type: string
                      description: 产品细分类别；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-26>
                    last_price:
                      type: string
                      example: '150.25'
                      description: 最新价。
                      x-parser-schema-id: <anonymous-schema-27>
                    open:
                      type: string
                      description: 开盘价；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-28>
                    prev_close:
                      type: string
                      description: 昨收价或参考价；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-29>
                    bid_price:
                      type: string
                      description: 最优买价；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-30>
                    ask_price:
                      type: string
                      description: 最优卖价；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-31>
                    spread:
                      type: string
                      description: 外汇或贵金属的买卖价差；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-32>
                    volume_24h:
                      type: string
                      description: 成交量；加密货币通常为滚动 24 小时，股票和期货通常为当日或当前交易时段。
                      x-parser-schema-id: <anonymous-schema-33>
                    quote_volume_24h:
                      type: string
                      description: 与 volume_24h 相同统计窗口内的成交额；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-34>
                    high_24h:
                      type: string
                      description: 与 volume_24h 相同统计窗口内的最高价。
                      x-parser-schema-id: <anonymous-schema-35>
                    low_24h:
                      type: string
                      description: 与 volume_24h 相同统计窗口内的最低价。
                      x-parser-schema-id: <anonymous-schema-36>
                    price_change_24h:
                      type: string
                      description: 相同统计窗口内的价格变化；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-37>
                    price_change_percent_24h:
                      type: string
                      description: 价格变化百分比；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-38>
                    trade_session:
                      type: string
                      enum:
                        - pre_market
                        - post_market
                        - overnight
                      description: 美股扩展交易时段；适用时返回。
                      x-parser-schema-id: <anonymous-schema-39>
                    quote_volume:
                      type: string
                      description: 当前扩展交易时段的成交额；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-40>
                    pre_market_quote:
                      type: object
                      description: 盘前行情；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-41>
                    post_market_quote:
                      type: object
                      description: 盘后行情；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-42>
                    overnight_quote:
                      type: object
                      description: 夜盘行情；有数据时返回。
                      x-parser-schema-id: <anonymous-schema-43>
                    timestamp:
                      type: integer
                      example: 1703123456789
                      description: Unix 时间戳，单位为毫秒。
                      x-parser-schema-id: <anonymous-schema-44>
                  required:
                    - symbol
                    - last_price
                    - timestamp
                  x-parser-schema-id: <anonymous-schema-22>
              required:
                - cmd
                - data
              x-parser-schema-id: <anonymous-schema-20>
            x-parser-schema-id: <anonymous-schema-60>
            name: 美股全量行情批次
            description: 初始快照和后续行情更新均以数组分批发送，每批最多 500 条消息。
        headers: []
        jsonPayloadSchema:
          type: array
          maxItems: 500
          items: *ref_0
          x-parser-schema-id: <anonymous-schema-60>
        title: 美股全量行情批次
        description: 初始快照和后续行情更新均以数组分批发送，每批最多 500 条消息。
        example: '{}'
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: tickerBatch
      - &ref_6
        id: errorResponse
        contentType: application/json
        payload:
          - name: WebSocket 错误响应
            description: WebSocket 连接建立后返回的订阅或命令错误。
            type: object
            properties:
              - name: cmd
                type: string
                description: 触发错误的命令。
                required: true
              - name: code
                type: oneOf
                description: 错误码；比较前应统一转为字符串。
                required: true
              - name: message
                type: string
                description: 错误说明。
                required: true
              - name: data
                type: oneOf
                description: 可选的错误上下文。
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          additionalProperties: false
          properties:
            cmd:
              type: string
              description: 触发错误的命令。
              x-parser-schema-id: <anonymous-schema-2>
            code:
              description: 错误码；比较前应统一转为字符串。
              oneOf:
                - type: integer
                  x-parser-schema-id: <anonymous-schema-4>
                - type: string
                  x-parser-schema-id: <anonymous-schema-5>
              x-parser-schema-id: <anonymous-schema-3>
            message:
              type: string
              description: 错误说明。
              x-parser-schema-id: <anonymous-schema-6>
            data:
              description: 可选的错误上下文。
              oneOf:
                - type: 'null'
                  x-parser-schema-id: <anonymous-schema-8>
                - type: object
                  additionalProperties: true
                  x-parser-schema-id: <anonymous-schema-9>
                - type: array
                  items:
                    x-parser-schema-id: <anonymous-schema-11>
                  x-parser-schema-id: <anonymous-schema-10>
              x-parser-schema-id: <anonymous-schema-7>
          required:
            - cmd
            - code
            - message
          x-parser-schema-id: <anonymous-schema-1>
        title: WebSocket 错误响应
        description: WebSocket 连接建立后返回的订阅或命令错误。
        example: |-
          {
            "cmd": "<string>",
            "message": "<string>"
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: errorResponse
    bindings: []
    extensions: *ref_1
sendOperations:
  - *ref_2
receiveOperations:
  - *ref_3
sendMessages:
  - *ref_4
receiveMessages:
  - *ref_5
  - *ref_6
extensions:
  - id: x-parser-unique-object-id
    value: ticker_us_stock
securitySchemes:
  - id: apiKey
    name: api_key
    type: httpApiKey
    in: query
    extensions: []

````

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