↗

WebSocket 实时推送

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

在线调试 · WebSocket
申请试用 Key
未连接

填入你的 API Key(正式 Key,或在控制台申请的试用 Key)即可调用真实接口;Key 只保存在你的浏览器里。

连接

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_alertsop = "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 秒)。

{
  "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。

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

op = "alert"

一条推送(只有订阅了 my_alerts 的连接才会收到):和你的 Bark、企业微信收到的同一份推送,字段见我的推送。注意它是 op = "alert",不是主题事件 op = "event";断线期间的用 GET /v1/alerts?after= 补拉(实时流不补发我的推送)。

{
  "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)补齐再重连。

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

op = "subscribed"

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

{
  "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 补拉。

{
  "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 可能紧跟在这些回复之后到达。无需回复;超过两个心跳周期什么都没收到,说明连接已断,应重连。

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

op = "pong"

对客户端 ping 的回复。

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

op = "error"

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

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

完整消息示例

实时推送时每条消息就是一个 JSON 对象:op = "event",event 是完整事件(字段说明见事件格式)。以下是各类型的真实消息,原样复制即可用于解析测试:

交易所公告(type = announcement):首次推送(只有原文)
{
  "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):翻译补齐后再推一次
{
  "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):首次推送(只有原文)
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b1509cbd0e4e92d84812118",
    "revision": 1,
    "action": "created",
    "topic": "news.jinse",
    "type": "news",
    "source": {
      "id": "jinse",
      "name": "Jinse Finance"
    },
    "published_at": 1796540806,
    "published_at_ms": 1796540806000,
    "detected_at_ms": 1796540875000,
    "data": {
      "titles": {
        "zh": "美国高频交易“窃密”案反转:前量化交易员两项刑事指控均获判无罪"
      },
      "original_lang": "zh",
      "translated_langs": [],
      "summary": "【美国高频交易“窃密”案反转:前量化交易员两项刑事指控均获判无罪】金色财经报道,12月6日,据财新网披露,美国纽约南区联邦地区法院陪审团裁定,前Headlands Technologies量化交易员何卓峰(Cheuk Fung Richard Ho)被控的商业秘密盗窃和电信欺诈两项罪名均不成立。陪审团经过约3小时评议后作出无罪裁决。 \n美国检方指控,何卓峰在Headlands任职期间,未经授权复制公司核心交易代码,并秘密创办交易公司One R Squared(ORS),随后向另一家高频交易巨头Tower Research Capital保证相关软件由其团队独立开发,以获得资金及交易基础设施支持。检方认为,ORS将相关技术用于中国期货市场及其他国际衍生品市场交易。 \n辩方则承认何卓峰曾将Headlands的部分文件上传至私人文件夹,但否认这些文件被用于开发ORS的交易算法,并指出相关代码包含大量行业通用技术,不应直接认定为受法律保护的商业秘密。辩方还强调,何卓峰拥有剑桥大学计算机科学背景及十余年金融交易算法开发经验,具备独立开发交易系统的能力。最终,陪审团未支持检方提出的两项刑事指控。",
      "url": "https://www.jinse.com.cn/lives/544520.html"
    }
  }
}
新闻快讯(type = news):翻译补齐后再推一次
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b1509cbd0e4e92d84812118",
    "revision": 2,
    "action": "updated",
    "topic": "news.jinse",
    "type": "news",
    "source": {
      "id": "jinse",
      "name": "Jinse Finance"
    },
    "published_at": 1796540806,
    "published_at_ms": 1796540806000,
    "detected_at_ms": 1796540875000,
    "data": {
      "titles": {
        "zh": "美国高频交易“窃密”案反转:前量化交易员两项刑事指控均获判无罪",
        "en": "Reversal in US High-Frequency Trading \"Theft\" Case: Former Quantitative Trader Acquitted on Both Criminal Charges",
        "ko": "미국 고빈도 거래 '정보 도용' 사건 반전: 전 양적 트레이더 두 가지 형사 기소 모두 무죄 판결"
      },
      "original_lang": "zh",
      "translated_langs": [
        "en",
        "ko"
      ],
      "summary": "【美国高频交易“窃密”案反转:前量化交易员两项刑事指控均获判无罪】金色财经报道,12月6日,据财新网披露,美国纽约南区联邦地区法院陪审团裁定,前Headlands Technologies量化交易员何卓峰(Cheuk Fung Richard Ho)被控的商业秘密盗窃和电信欺诈两项罪名均不成立。陪审团经过约3小时评议后作出无罪裁决。 \n美国检方指控,何卓峰在Headlands任职期间,未经授权复制公司核心交易代码,并秘密创办交易公司One R Squared(ORS),随后向另一家高频交易巨头Tower Research Capital保证相关软件由其团队独立开发,以获得资金及交易基础设施支持。检方认为,ORS将相关技术用于中国期货市场及其他国际衍生品市场交易。 \n辩方则承认何卓峰曾将Headlands的部分文件上传至私人文件夹,但否认这些文件被用于开发ORS的交易算法,并指出相关代码包含大量行业通用技术,不应直接认定为受法律保护的商业秘密。辩方还强调,何卓峰拥有剑桥大学计算机科学背景及十余年金融交易算法开发经验,具备独立开发交易系统的能力。最终,陪审团未支持检方提出的两项刑事指控。",
      "url": "https://www.jinse.com.cn/lives/544520.html"
    }
  }
}
信号(type = signal)
{
  "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)
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b1507bfe70ade1bb493e04f",
    "revision": 1,
    "action": "created",
    "topic": "twitter.44196397",
    "type": "twitter",
    "source": {
      "id": "44196397",
      "name": "@elonmusk (Elon Musk)"
    },
    "published_at": 1796540346,
    "published_at_ms": 1796540346846,
    "detected_at_ms": 1796540351247,
    "data": {
      "kind": "quote",
      "tweet_id": "2129470673395523653",
      "author": {
        "id": "44196397",
        "screen_name": "elonmusk",
        "name": "Elon Musk"
      },
      "text": "Bullseye 🎯",
      "lang": "tr",
      "url": "https://x.com/elonmusk/status/2129470673395523653",
      "referenced_tweet_id": "2129429267469722069",
      "conversation_id": null,
      "media": [],
      "complete": true
    }
  }
}

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

客户端消息

op = "subscribe"

追加订阅主题(同样支持通配)。

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

op = "unsubscribe"

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

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

op = "ping"

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

{
  "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 秒。

关闭码

关闭码含义
4001Key 无效、未提供、已重置 / 吊销或(试用 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 出现多次只取最后一个

完整示例

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 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();
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"])
		}
	}
}