# WebSocket 实时推送

保持一条连接，我们监控到你订阅主题的新公告、新闻或信号，就立即推送给你。每把 Key 同时 1 条连接。

> Source: https://tokenearly.com/developers/websocket · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json

## 连接

```
wss://api.tokenearly.com/v1/stream?topics=announcement.binance,news.*,my_alerts&after=<last_event_id>
```

### 订阅什么

`topics` 可以任意组合：逗号分隔，每一项可以是具体主题、通配（`news.*`、`*`），或特殊值 `my_alerts`（我的推送）。连上以后还能随时用 `subscribe` / `unsubscribe` 增减。

| 想要 | topics | 收到 |
|---|---|---|
| 全部可读的主题事件 | 省略，或 `*` | `op = "event"` |
| 某一类 | `announcement.*` | 全部交易所公告 |
| 挑几个来源 | `announcement.binance,news.odaily,twitter.44196397` | 只有这几个来源 |
| 只要我的推送 | `my_alerts` | `op = "alert"` |
| 我的推送 + 主题事件 | `my_alerts,announcement.*,news.*` | 两种都有，按 `op` 区分 |

> 网页「通知渠道」里的「开发者 API」开关只决定是否生成我的推送，不影响主题事件：连接没有订阅 `my_alerts` 时，开关打开与否收到的内容完全一样。`*` 不包含 `my_alerts`，要显式写上。

| 查询参数 | 说明 |
|---|---|
| `topics` | 要订阅的主题，逗号分隔，支持通配。省略 = 全部可读主题。加上特殊值 `my_alerts` 订阅我的推送（不会被 `*` 包含，必须显式写）；只写 `my_alerts` = 只要我的推送、不要主题事件。 |
| `after` | 上次收到的最后一个事件 ID。连接后先补发之后的事件（最多 200 条），再推实时。 |
| `api_key` | 浏览器里无法设置请求头时用它传 Key；服务端代码请用 Authorization 头。 |

鉴权与 REST 相同：请求头 `Authorization: Bearer <Key>`；浏览器里用 `api_key` 查询参数。

> 每把 Key 同时最多 1 条连接，名额满时新连接会以 4029 被拒绝。一条连接里用 `topics` 或 `subscribe` 就能订阅所有需要的主题；确实要多条连接，就多建 Key。

## 服务端消息

每条消息都是一个 JSON 对象，用 `op` 区分类型：

### op = "welcome"

连接成功后的第一条消息：topics 为实际生效的主题；denied 为你请求了但没有权限的主题；unknown 为不存在的主题（多半是拼错了）；heartbeat_seconds 为心跳间隔；my_alerts.subscribed 表示这条连接是否订阅了我的推送，my_alerts.channel_enabled 表示网页上的「开发者 API」开关是否打开；试用 Key 还带 expires_at（Unix 秒）。

```json
{
  "op": "welcome",
  "spec_version": "1.0",
  "topics": [
    "announcement.binance",
    "news.odaily"
  ],
  "denied": [
    "announcement.upbit"
  ],
  "unknown": [
    "announcement.nope"
  ],
  "heartbeat_seconds": 25,
  "my_alerts": {
    "subscribed": true,
    "channel_enabled": true
  }
}
```

### op = "event"

一条事件。补发的历史事件带 "replay": true。

```json
{
  "op": "event",
  "event": {
    "id": "…",
    "revision": 1,
    "topic": "announcement.binance",
    "…": "…"
  }
}
```

### op = "alert"

一条推送（只有订阅了 `my_alerts` 的连接才会收到）：和你的 Bark、企业微信收到的同一份推送，字段见[我的推送](https://tokenearly.com/developers/my-alerts)。注意它是 `op = "alert"`，不是主题事件 `op = "event"`；断线期间的用 GET /v1/alerts?after= 补拉（实时流不补发我的推送）。

```json
{
  "op": "alert",
  "alert": {
    "id": "6af57201e1b0c95f3a7d2e41",
    "category": "announcement",
    "source": {
      "id": "binance",
      "name": "Binance"
    },
    "followup": false,
    "lang": "en",
    "label": "original",
    "title": "【币安(BINANCE)】",
    "text": "【原文·英文】\nBinance Will List Fooken (FOO) with Seed Tag Applied\n— — — — — — — — — —\nhttps://www.binance.com/en/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)",
    "url": "https://www.binance.com/en/support/announcement/detail/abc123",
    "titles": {
      "en": "Binance Will List Fooken (FOO) with Seed Tag Applied"
    },
    "ref": {
      "type": "announcement",
      "topic": "announcement.binance",
      "event_id": "6af57200e1b0c95f3a7d2e40"
    },
    "created_at": 1794470401
  }
}
```

### op = "replay_done"

带 after 连接时补发结束的标记，之后都是实时事件。count 为补发条数；truncated = true 表示缺口超过补发上限，请先用 REST（after 与 updated_after）补齐再重连。

```json
{
  "op": "replay_done",
  "count": 3,
  "truncated": false
}
```

### op = "subscribed"

subscribe / unsubscribe 之后返回新的生效主题（可能为空列表）；denied 同 welcome；unknown 为这次消息里不存在的主题。

```json
{
  "op": "subscribed",
  "topics": [
    "announcement.binance"
  ],
  "denied": [],
  "unknown": [],
  "my_alerts": {
    "subscribed": false,
    "channel_enabled": true
  }
}
```

### op = "notice"

变更通知。kind：defaults_changed（默认限额调整，全体）、account_limits_changed（你的账号）、key_limits_changed（某把 Key）、ip_allowlist_changed、key_reset（Key 被重置）、key_revoked、api_update（接口更新公告）、access_expiring / access_expired（含 API 的会员即将到期 / 已到期，你的账号）。scope：global = 全体，user = 你的账号，key = 某把 Key（key_id）。title / body 是三语说明；data.changes 为 {项: [旧值, 新值]}，null 表示「默认值」。离线期间的通知用 GET /v1/notices 补拉。

```json
{
  "op": "notice",
  "notice": {
    "id": "ntc_3f9c2a71d0b84e6c5a12",
    "kind": "key_limits_changed",
    "scope": "key",
    "key_id": "key_8d2f0c1b7a6e4d3c2b1a",
    "title": {
      "zh": "API Key 限额已调整",
      "en": "API key limits changed",
      "ko": "API 키 한도 변경"
    },
    "body": {
      "zh": "te_live_Ab12…  每把 Key 的实时连接数: 1 → 2",
      "en": "te_live_Ab12…  Stream connections per key: 1 → 2",
      "ko": "te_live_Ab12…  키당 실시간 연결 수: 1 → 2"
    },
    "data": {
      "key_id": "key_8d2f0c1b7a6e4d3c2b1a",
      "prefix": "te_live_Ab12",
      "changes": {
        "streams_per_key": [
          1,
          2
        ]
      }
    },
    "created_at": 1794208744
  }
}
```

### op = "ping"

服务端心跳：连续 heartbeat_seconds 秒没有推送任何事件、我的推送或变更通知（event / alert / notice）就发一次，所以没有事件时每 heartbeat_seconds 秒一次；ts 为 Unix 秒。计时从 welcome（带 after 时从 replay_done）之后开始；对你发来的消息的回复（subscribed、pong、invalid_message 错误）不会让计时重来，因此 ping 可能紧跟在这些回复之后到达。无需回复；超过两个心跳周期什么都没收到，说明连接已断，应重连。

```json
{
  "op": "ping",
  "ts": 1794208744
}
```

### op = "pong"

对客户端 ping 的回复。

```json
{
  "op": "pong",
  "ts": 1794208744
}
```

### op = "error"

错误说明。鉴权、权限、参数类错误之后会关闭连接（关闭码见下表）；code = invalid_message（客户端消息不合规）时连接保持不断。

```json
{
  "op": "error",
  "code": "invalid_api_key",
  "message": "This API key does not exist or has been revoked."
}
```

## 完整消息示例

实时推送时每条消息就是一个 JSON 对象：`op = "event"`，`event` 是完整事件（字段说明见[事件格式](https://tokenearly.com/developers/events)）。以下是各类型的真实消息，原样复制即可用于解析测试：

**交易所公告（type = announcement）：首次推送（只有原文）**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b0ff643d0e4e92d84810499",
    "revision": 1,
    "action": "created",
    "topic": "announcement.gate",
    "type": "announcement",
    "source": {
      "id": "gate",
      "name": "Gate.io"
    },
    "published_at": 1796208195,
    "published_at_ms": 1796208195000,
    "detected_at_ms": 1796208195896,
    "data": {
      "titles": {
        "zh": "Gate 已上线 RITUAL 合约交易、杠杆借贷交易、交易机器人、跟单、闪兑、定投功能",
        "en": "Gate Now Supports RITUAL for Futures Trading, Margin Loans, Bots, Copy, Convert, and Auto-Invest"
      },
      "original_lang": "zh",
      "translated_langs": [],
      "url": "https://www.gate.io/article/103112",
      "exchange_category": "listing",
      "listing": {
        "is_listing": true,
        "market": "futures"
      },
      "symbols": []
    }
  }
}
```

**交易所公告（type = announcement）：翻译补齐后再推一次**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b0ff643d0e4e92d84810499",
    "revision": 3,
    "action": "updated",
    "topic": "announcement.gate",
    "type": "announcement",
    "source": {
      "id": "gate",
      "name": "Gate.io"
    },
    "published_at": 1796208195,
    "published_at_ms": 1796208195000,
    "detected_at_ms": 1796208195896,
    "data": {
      "titles": {
        "zh": "Gate 已上线 RITUAL 合约交易、杠杆借贷交易、交易机器人、跟单、闪兑、定投功能",
        "en": "Gate Now Supports RITUAL for Futures Trading, Margin Loans, Bots, Copy, Convert, and Auto-Invest",
        "ko": "Gate는 RITUAL 계약 거래, 레버리지 대출 거래, 트레이딩 봇, 팔로우 트레이딩, 스왑, 정기 투자 기능을 출시했습니다."
      },
      "original_lang": "zh",
      "translated_langs": [
        "ko"
      ],
      "url": "https://www.gate.io/article/103112",
      "exchange_category": "listing",
      "listing": {
        "is_listing": true,
        "market": "futures"
      },
      "symbols": []
    }
  }
}
```

**新闻快讯（type = news）：首次推送（只有原文）**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b150bf2d0e4e92d8481211f",
    "revision": 1,
    "action": "created",
    "topic": "news.panews",
    "type": "news",
    "source": {
      "id": "panews",
      "name": "PANews"
    },
    "published_at": 1796541408,
    "published_at_ms": 1796541408000,
    "detected_at_ms": 1796541426000,
    "data": {
      "titles": {
        "zh": "DWF Labs合伙人：比特币已挺过风暴，若Strategy没有崩盘，市场或已触底",
        "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed"
      },
      "original_lang": "zh",
      "translated_langs": [],
      "summary": "PANews 12月6日消息，DWF Labs 合伙人 Andrei Grachev 发文预测，比特币已经受住这轮市场风暴，如果 Strategy 没有崩盘，那么市场可能已经触底。",
      "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169"
    }
  }
}
```

**新闻快讯（type = news）：翻译补齐后再推一次**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b150bf2d0e4e92d8481211f",
    "revision": 3,
    "action": "updated",
    "topic": "news.panews",
    "type": "news",
    "source": {
      "id": "panews",
      "name": "PANews"
    },
    "published_at": 1796541408,
    "published_at_ms": 1796541408000,
    "detected_at_ms": 1796541426000,
    "data": {
      "titles": {
        "zh": "DWF Labs合伙人：比特币已挺过风暴，若Strategy没有崩盘，市场或已触底",
        "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed",
        "ko": "DWF Labs 파트너: 비트코인은 폭풍을 견뎌냈으며, 만약 Strategy가 붕괴되지 않았다면 시장은 이미 바닥에 도달했을 수 있다"
      },
      "original_lang": "zh",
      "translated_langs": [
        "ko"
      ],
      "summary": "PANews 12月6日消息，DWF Labs 合伙人 Andrei Grachev 发文预测，比特币已经受住这轮市场风暴，如果 Strategy 没有崩盘，那么市场可能已经触底。",
      "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169"
    }
  }
}
```

**信号（type = signal）**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b055216d0e4e92d8480d1e5",
    "revision": 1,
    "action": "created",
    "topic": "signal.binance_alpha",
    "type": "signal",
    "source": {
      "id": "binance_alpha",
      "name": "Binance Alpha"
    },
    "published_at": 1795510800,
    "published_at_ms": 1795510800000,
    "detected_at_ms": 1795510806000,
    "data": {
      "signal_type": "binance_alpha",
      "level": "info",
      "titles": {
        "zh": "🆕 Binance Alpha 新币上线: SHARE (BSC)",
        "en": "🆕 Binance Alpha New Token: SHARE (BSC)",
        "ko": "🆕 바이낸스 알파 신규 토큰: SHARE (BSC)"
      },
      "contents": {
        "zh": "代币: SHARE (ShareX)\n链: BSC\n价格: $0.0572\n合约: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\n持有者: 61649\n市值: $56.19M",
        "en": "Token: SHARE (ShareX)\nChain: BSC\nPrice: $0.0572\nContract: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\nHolders: 61649\nMarket Cap: $56.19M",
        "ko": "토큰: SHARE (ShareX)\n체인: BSC\n가격: $0.0572\n컨트랙트: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\n보유자: 61649\n시가총액: $56.19M"
      },
      "url": "https://www.binance.com/en/alpha/bsc/0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34",
      "symbols": [
        "SHARE"
      ],
      "tags": [
        "new_listing",
        "bsc"
      ]
    }
  }
}
```

**推特 KOL 推文（type = twitter）**

```json
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b150c67e70ade1bb493e0e2",
    "revision": 1,
    "action": "created",
    "topic": "twitter.44196397",
    "type": "twitter",
    "source": {
      "id": "44196397",
      "name": "@elonmusk (Elon Musk)"
    },
    "published_at": 1796541539,
    "published_at_ms": 1796541539136,
    "detected_at_ms": 1796541543941,
    "data": {
      "kind": "quote",
      "tweet_id": "2129475674222317961",
      "author": {
        "id": "44196397",
        "screen_name": "elonmusk",
        "name": "Elon Musk"
      },
      "text": "Yeah",
      "lang": "en",
      "url": "https://x.com/elonmusk/status/2129475674222317961",
      "referenced_tweet_id": "2129371437043483081",
      "conversation_id": null,
      "media": [],
      "complete": true
    }
  }
}
```

断线续传补发的历史事件多一个 `"replay": true`，其余完全相同。

## 客户端消息

### op = "subscribe"

追加订阅主题（同样支持通配）。

```json
{
  "op": "subscribe",
  "topics": [
    "announcement.okx",
    "signal.*"
  ]
}
```

### op = "unsubscribe"

取消订阅主题（支持通配；["*"] = 取消全部主题，连接保持，之后只收心跳、变更通知，以及已订阅的我的推送；我的推送要显式取消 my_alerts）。

```json
{
  "op": "unsubscribe",
  "topics": [
    "announcement.okx"
  ]
}
```

### op = "ping"

客户端心跳，服务端回 pong。

```json
{
  "op": "ping"
}
```

## 同一条消息为什么会收到两次

先推送的是监控到的原始版本（`revision = 1`）。之后同一条公告补全了中英韩标题或原文链接（推文：完整版到达），会用同一个 `id`、更大的 `revision` 再推一次（`action = "updated"`）。按 (`id`, `revision`) 去重、保留最大的一版。判断「是不是新消息」请看这个 `id` 你有没有见过，不要只看 `action`：断线补发时一条新消息可能已经是 `revision = 2`（`action = "updated"`）。

## 断线续传

1. 处理每条 `event` 时保存它的 `event.id`。
2. 断线后带 `after=<最后的 id>` 重连。
3. 服务端先补发 `after` 之后的新事件，再补发「`after` 那条事件入库之后」产生的新修订版（包括 `after` 那条本身及更早的事件，都带 `replay: true`，合计最多 200 条），发完给 `replay_done`，然后继续推实时事件。补发可能包含你已经收到过的修订版，务必按 (`id`, `revision`) 去重。
4. `replay_done.truncated = true` 表示缺口超过上限：断开，用 REST 的 `after` 与 `updated_after` 补齐后再重连。

## 心跳

连续 `heartbeat_seconds`（见 welcome）秒没有推送事件、我的推送或变更通知（`event` / `alert` / `notice`），服务端就发一次 `ping`，所以没有事件时每 `heartbeat_seconds` 秒一次（我的推送 `alert` 同样会让计时重来）。计时从 `welcome` 之后开始（带 `after` 连接时从 `replay_done` 之后）；服务端对你发来的消息的回复（`subscribed`、`pong`、`invalid_message` 错误）不会让计时重来，所以 `ping` 可能紧跟在这些回复后面到达，这是正常的。超过两个心跳周期什么都没收到，说明连接已失效，请主动重连。重连时退避 1、2、4… 秒（上限 60 秒）；关闭码 4001 / 4003 不要自动重连，4029 至少等 5 秒。

## 关闭码

| 关闭码 | 含义 |
|---|---|
| `4001` | Key 无效、未提供、已重置 / 吊销或（试用 Key）已到期（error.code = missing_api_key / invalid_api_key / key_expired）。不要自动重连。 |
| `4003` | 没有权限：套餐不含开发者 API / 已到期（error.code = plan_required），或来源 IP 不在白名单（error.code = ip_not_allowed）。不要自动重连，先处理原因。 |
| `4029` | 这把 Key 的连接名额已满，新连接被拒绝。旧连接刚关闭时名额释放可能有几秒延迟：至少等 5 秒再重连，并指数退避。 |
| `4400` | 连接参数不合法：after 不是合法的事件 ID（error.code = invalid_cursor）。改正参数后再连，不要原样重连。 |
| `4008` | 消费太慢被断开，带 after 重连。 |
| `1000` | 正常关闭。 |
| `1001 / 1006 / 1011 / 1012 / 1013` | 服务重启、网络中断或服务器错误。带 `after=<最后的事件 id>` 重连，退避 1、2、4… 秒，上限 60 秒。 |

## 边界行为

| 情况 | 服务端行为 |
|---|---|
| 发来的不是 JSON 对象、缺少 `op`、`op` 未知 | 回 `{"op":"error","code":"invalid_message"}`，连接保持 |
| subscribe / unsubscribe 的 `topics` 为空或不是字符串列表 | 同上，回 `invalid_message`；`topics` 也可以是逗号分隔的字符串 |
| `unsubscribe` `["*"]` | 取消全部主题，`subscribed.topics = []`；连接保持，之后只收心跳、变更通知，以及仍然订阅着的我的推送（`*` 不包含 `my_alerts`，要停收请单独退订 `my_alerts`） |
| 订阅不存在的主题 | 不报错，列在 `welcome.unknown` / `subscribed.unknown` 里 |
| 连接时 `topics` 为空或省略 | 订阅全部可读主题 |
| 连接时 `topics` 里只有不存在（或没有权限）的主题 | 照常连上，`welcome.topics = []`，这些主题列在 `welcome.unknown`（或 `welcome.denied`）里；连接只收心跳与通知，之后可以用 `subscribe` 补订 |
| 主题 ID 的大小写 | 不区分：`Announcement.Binance` 与 `announcement.binance` 相同（连接参数、`subscribe`、REST 都一样）；返回的一律是小写 |
| 事件 ID（`after` 等游标）的大小写 | 不区分：十六进制大小写都接受，REST 的 `after` / `before` 与 `GET /v1/events/{id}` 也一样；返回的 ID 一律是小写 |
| `after` 不是合法的事件 ID | 发 `error`（`invalid_cursor`）后以 4400 关闭 |
| `after` 格式合法但没有这条事件（例如已过保留期） | 按 ID 中的时间位置补发其后的事件，行为与存在时相同 |
| `after=`（空值） | 等同于不带 `after`：不补发，也不发 `replay_done` |
| `after` 出现多次 | 只取最后一个 |

## 完整示例

**Python**

```python
import asyncio, json, os, time
import requests    # pip install requests
import websockets  # pip install websockets

KEY = os.environ["TOKENEARLY_API_KEY"]
H = {"Authorization": f"Bearer {KEY}"}
TOPICS = "announcement.*,news.*,signal.*,twitter.*"
STREAM = "wss://api.tokenearly.com/v1/stream?topics=" + TOPICS
EVENTS = "https://api.tokenearly.com/v1/events"
FATAL = {4001, 4003}                        # bad / expired key, no permission: fix it, do not retry

last_id = None                              # last event id: resume cursor (store it durably in production)
live_at = int(time.time())                  # last moment the stream was live: `updated_after` for a REST catch-up

def handle(ev):
    global last_id
    if not last_id or ev["id"] > last_id:   # ids grow with time; only move the cursor forward
        last_id = ev["id"]
    data = ev["data"]                       # same envelope for every type; `data` depends on ev["type"]
    if ev["type"] == "twitter":             # X posts: text as published, no titles
        text = "@" + data["author"]["screen_name"] + ": " + data["text"]
    else:
        text = data["titles"].get("en") or next(iter(data["titles"].values()), "")
    print(ev["type"], ev["topic"], ev["revision"], text)   # dedupe on (id, revision) in production

def rest_get(params):
    while True:
        r = requests.get(EVENTS, params=dict(params, topics=TOPICS, limit=200), headers=H, timeout=10)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "3")))
            continue
        r.raise_for_status()
        time.sleep(int(r.headers.get("X-RateLimit-Reset", "3")))   # respect the per-key interval
        return r.json()

def catch_up():
    """replay_done.truncated: the gap is too big for the stream, so fill it over REST."""
    while True:                             # 1) new events after the cursor, oldest first
        page = rest_get({"after": last_id})
        for ev in page["events"]:
            handle(ev)
        if not page["has_more"]:
            break
    params = {"updated_after": live_at}     # 2) older events that got a new revision while away
    while True:
        page = rest_get(params)
        for ev in page["events"]:
            handle(ev)
        if not page["has_more"]:
            break
        params = {"updated_after": live_at, page["cursor_param"]: page["next_cursor"]}

async def main():
    global live_at, last_id
    delay = 1
    while True:
        url = STREAM + (f"&after={last_id}" if last_id else "")
        truncated = False
        try:
            async with websockets.connect(url, additional_headers=H) as ws:
                async for raw in ws:
                    msg = json.loads(raw)
                    op = msg["op"]
                    if op == "welcome":
                        delay = 1
                    elif op == "event":
                        handle(msg["event"])
                    elif op == "replay_done" and msg["truncated"]:
                        truncated = True    # 1) close, 2) catch up over REST, 3) reconnect with the new cursor
                        break
                    elif op == "notice":
                        print("notice:", msg["notice"]["kind"], msg["notice"]["body"].get("en"))
                    elif op == "error":
                        print("server error:", msg["code"], msg["message"])
                    if op == "ping" or (op == "event" and not msg.get("replay")):
                        live_at = int(time.time())   # live traffic only comes after the replay
        except websockets.ConnectionClosed as e:
            if e.rcvd and e.rcvd.code in FATAL:
                raise SystemExit(f"stopped: close code {e.rcvd.code}")
            if e.rcvd and e.rcvd.code == 4029:
                delay = max(delay, 5)       # slot not free yet
            if e.rcvd and e.rcvd.code == 4400:
                print("stored cursor rejected; reconnecting without it")
                last_id = None              # never retry the same invalid `after`
        except Exception as e:
            print("disconnected:", e)
        if truncated:
            await asyncio.to_thread(catch_up)   # blocking HTTP off the event loop
            continue                            # reconnect right away with after=<new last_id>
        await asyncio.sleep(delay)
        delay = min(delay * 2, 60)          # exponential backoff

asyncio.run(main())
```

**Node.js**

```javascript
// Node 18+ (built-in fetch): npm install ws
const WebSocket = require("ws");
const TOPICS = "announcement.*,news.*,signal.*,twitter.*";
const EVENTS = "https://api.tokenearly.com/v1/events";
const H = { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` };
const FATAL = new Set([4001, 4003]);   // bad / expired key, no permission: fix it, do not retry
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let lastId = null, liveAt = Math.floor(Date.now() / 1000), delay = 1000;

function handle(ev) {
  if (!lastId || ev.id > lastId) lastId = ev.id;   // ids grow with time; only move the cursor forward
  const d = ev.data;   // shape depends on ev.type; X posts carry text instead of titles
  const text = ev.type === "twitter" ? `@${d.author.screen_name}: ${d.text}` : (d.titles.en || Object.values(d.titles)[0]);
  console.log(ev.type, ev.topic, ev.revision, text);   // dedupe on (id, revision) in production
}

async function restPages(params) {   // all pages of one REST query, following `cursor_param`
  for (;;) {
    const r = await fetch(`${EVENTS}?${new URLSearchParams({ ...params, topics: TOPICS, limit: "200" })}`, { headers: H });
    if (r.status === 429) { await sleep(1000 * Number(r.headers.get("retry-after") || 3)); continue; }
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    const page = await r.json();
    page.events.forEach(handle);
    if (!page.has_more) return;
    params = { ...params, [page.cursor_param]: page.next_cursor };
    await sleep(1000 * Number(r.headers.get("x-ratelimit-reset") || 3));   // respect the per-key interval
  }
}

async function catchUp() {   // replay_done.truncated: the gap is too big for the stream, so fill it over REST
  await restPages({ after: lastId });             // 1) new events after the cursor, oldest first
  await restPages({ updated_after: String(liveAt) }); // 2) older events that got a new revision while away
}

function connect() {
  const ws = new WebSocket(`wss://api.tokenearly.com/v1/stream?topics=${TOPICS}` + (lastId ? `&after=${lastId}` : ""), { headers: H });
  let truncated = false;
  ws.on("message", (raw) => {
    const msg = JSON.parse(raw);
    if (msg.op === "welcome") delay = 1000;
    if (msg.op === "event") handle(msg.event);
    if (msg.op === "replay_done" && msg.truncated) { truncated = true; ws.close(); return; }
    if (msg.op === "notice") console.log("notice:", msg.notice.kind, msg.notice.body.en);
    if (msg.op === "error") console.error("server error:", msg.code, msg.message);
    if (msg.op === "ping" || (msg.op === "event" && !msg.replay)) liveAt = Math.floor(Date.now() / 1000);
  });
  ws.on("close", async (code) => {
    if (FATAL.has(code)) return console.error("stopped: close code", code);
    if (truncated) {   // 1) closed, 2) catch up over REST, 3) reconnect with the new cursor
      try { await catchUp(); } catch (e) { console.error("catch-up failed:", e.message); }
      return connect();
    }
    if (code === 4400) { console.error("stored cursor rejected; reconnecting without it"); lastId = null; }
    if (code === 4029) delay = Math.max(delay, 5000);
    setTimeout(connect, delay);
    delay = Math.min(delay * 2, 60000);
  });
  ws.on("error", (e) => console.error(e.message));
}
connect();
```

**Go**

```go
package main

// go get github.com/coder/websocket
import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"

	"github.com/coder/websocket"
)

func main() {
	ctx := context.Background()
	h := http.Header{}
	h.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY"))
	c, _, err := websocket.Dial(ctx, "wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*,signal.*,twitter.*", &websocket.DialOptions{HTTPHeader: h})
	if err != nil {
		panic(err)
	}
	defer c.CloseNow()
	for {
		_, data, err := c.Read(ctx)
		if err != nil {
			// in production: reconnect with after=<last event id>, back off 1,2,4…60 s; stop on close code 4001 / 4003;
			// on 4400 drop the stored cursor; on replay_done with truncated = true catch up over REST first (see the Python tab)
			panic(err)
		}
		var msg map[string]any
		json.Unmarshal(data, &msg)
		if msg["op"] == "event" {
			ev := msg["event"].(map[string]any)
			fmt.Println(ev["type"], ev["topic"], ev["revision"], ev["id"])
		}
	}
}
```
