# Tokenearly 开发者 API > 两种接入方式:WebSocket 实时推送——我们监控到交易所公告、新闻快讯、信号或精选推特 KOL 的推文后立即推给你;REST 查询历史。数据是结构化事件:中英韩标题、公告的上新判定与代币代码、新闻摘要、推文原文、原文链接,每条都有稳定 ID。 - REST: https://api.tokenearly.com/v1 - WebSocket: wss://api.tokenearly.com/v1/stream - MCP: https://api.tokenearly.com/v1/mcp - Keys: create one in the dashboard (https://tokenearly.com/dashboard?tab=developer-api); accounts without the Developer API can apply for a 12-hour trial key there. ## 开始 - [概览](https://tokenearly.com/developers.md): 两种接入方式:WebSocket 实时推送——我们监控到交易所公告、新闻快讯、信号或精选推特 KOL 的推文后立即推给你;REST 查询历史。数据是结构化事件:中英韩标题、公告的上新判定与代币代码、新闻摘要、推文原文、原文链接,每条都有稳定 ID。 - [鉴权与 API Key](https://tokenearly.com/developers/authentication.md): 每个请求都带上 API Key:服务端代码放在 `Authorization: Bearer ` 请求头里;浏览器里的 WebSocket 不能设置请求头,改用 `api_key` 查询参数。 - [限流与配额](https://tokenearly.com/developers/limits.md): 默认每个账号 1 把 API Key;每把 Key 同时 1 条 WebSocket 连接,REST 与 MCP 每 3 秒 1 次。 ## 数据 - [主题](https://tokenearly.com/developers/topics.md): 主题是订阅的最小单位,格式为 <类型>.<来源>。主题清单由平台的全局注册表生成,新来源接入后自动出现。 - [事件格式](https://tokenearly.com/developers/events.md): 每条消息都是一个事件:固定的信封、稳定的 ID、可递增的修订号,以及按类型定义的 data。 - [我的推送](https://tokenearly.com/developers/my-alerts.md): 除了按主题订阅的全量事件,API 还能把**真正推给你的那一份**提醒原样给你:和你在网页上设置的 Bark、企业微信等渠道收到的完全相同,按你的来源、关键词、通知语言过滤。适合把我们的提醒接进你自己的机器人或工作流。 ## REST API - [查询事件](https://tokenearly.com/developers/rest/list-events.md): 按主题查询历史事件,支持游标翻页与断线补拉。 - [获取单个事件](https://tokenearly.com/developers/rest/get-event.md): 按 ID 取一个事件的最新修订版。 - [当前 Key 信息](https://tokenearly.com/developers/rest/me.md): 查看 Key 实际可读的主题、限额与 IP 白名单。 - [变更通知](https://tokenearly.com/developers/rest/notices.md): 限额调整、Key 变更与接口更新的记录。 - [我的推送](https://tokenearly.com/developers/rest/alerts.md): 和你的 Bark、企业微信等渠道收到的同一份推送(按你的网页设置过滤)。 - [主题清单](https://tokenearly.com/developers/rest/topics.md): 全部可订阅的主题;带 Key 时标注是否可读。 - [事件 JSON Schema](https://tokenearly.com/developers/rest/schema.md): 事件信封与各类 data 的 JSON Schema(draft 2020-12)。 - [健康检查](https://tokenearly.com/developers/rest/health.md): 服务是否在线。 ## 实时流 - [WebSocket 实时推送](https://tokenearly.com/developers/websocket.md): 保持一条连接,我们监控到你订阅主题的新公告、新闻或信号,就立即推送给你。每把 Key 同时 1 条连接。 ## AI 与工具 - [AI agent 与 MCP](https://tokenearly.com/developers/ai.md): 文档与接口都为 AI 准备好了:每页可复制成 Markdown,规范机器可读,AI agent 可以通过 MCP 直接查询事件。 ## 参考 - [错误码](https://tokenearly.com/developers/errors.md): REST 错误统一返回 JSON 对象 `error`,用 `code` 判断类型,不要依赖 `message` 文案。 ## Machine-readable - [OpenAPI 3.1](https://api.tokenearly.com/v1/openapi.json) - [AsyncAPI 3.0](https://api.tokenearly.com/v1/asyncapi.json) - [JSON Schema](https://api.tokenearly.com/v1/schema) - [All docs in one file](https://tokenearly.com/developers/llms-full.txt) ## Other languages - [English](https://tokenearly.com/en/developers/llms.txt) - [한국어](https://tokenearly.com/ko/developers/llms.txt) --- # Tokenearly 开发者 API 两种接入方式:WebSocket 实时推送——我们监控到交易所公告、新闻快讯、信号或精选推特 KOL 的推文后立即推给你;REST 查询历史。数据是结构化事件:中英韩标题、公告的上新判定与代币代码、新闻摘要、推文原文、原文链接,每条都有稳定 ID。 > Source: https://tokenearly.com/developers · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json - [WebSocket 实时推送](https://tokenearly.com/developers/websocket): 我们监控到新公告后立即推送给你;断线后按事件 ID 续传,不丢消息。 - [REST 查询历史](https://tokenearly.com/developers/rest/list-events): 按主题查询历史公告、新闻与信号,游标翻页。 - [规范的事件格式](https://tokenearly.com/developers/events): 固定信封 + 每类消息一份 JSON Schema,中英韩三语标题。 - [给 AI agent 用](https://tokenearly.com/developers/ai): 每页一键复制 Markdown;OpenAPI、llms.txt 与 MCP 服务器。 ## 三步跑通 ### 1. 拿到 Key 开通开发者 API 后,在[控制台](https://tokenearly.com/dashboard?tab=developer-api)创建 Key(只显示一次)。还没开通的话,可以先申请试用 Key:有效 12 小时,每 30 天可申请 6 次。 ```bash export TOKENEARLY_API_KEY=te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ### 2. 发第一个请求 查最近 3 条事件,范围是全部交易所公告加上 Odaily 新闻(多个主题用逗号连起来即可)。填入 Key 后点「发送请求」,直接在浏览器里调用真实接口。 **cURL** ```bash curl "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=3" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=3", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=3", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=3", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ### 3. 接实时流 用自己的 Key 连接 WebSocket,新公告一出现就会推过来;记下最后的事件 ID,重连时带上 `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= 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=, 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"]) } } } ``` ## 基础信息 | 项目 | 值 | |---|---| | REST 地址 | `https://api.tokenearly.com/v1` | | 实时流地址 | `wss://api.tokenearly.com/v1/stream` | | 鉴权 | `Authorization: Bearer ` | | 数据格式 | JSON,UTF-8;时间为 Unix 时间戳 | | 规范版本 | `1.0` | | 机器可读规范 | [OpenAPI](https://api.tokenearly.com/v1/openapi.json) · [AsyncAPI](https://api.tokenearly.com/v1/asyncapi.json) · [JSON Schema](https://api.tokenearly.com/v1/schema) | | 试用 Key | 在控制台申请,有效 12 小时 | ## 接入方式 | 方式 | 用途 | 限制 | |---|---|---| | **WebSocket(wss)** | 实时推送:我们监控到新公告、新闻或信号后立即推送给你 | 每把 Key 同时 1 条连接,多的拒绝 | | **REST** | 查询历史公告、新闻与信号,断线后补拉 | 每把 Key 每 3 秒 1 次 | | **MCP** | 给 AI agent 用的查询入口,数据与 REST 相同 | 与 REST 共用限频 | 每个账号可建 1 把 API Key,每把 Key 有自己的连接名额与限频,并可以绑定 IP 白名单。实时数据请用 WebSocket,不要轮询 REST。以上是默认值,你的 Key 实际生效的限额以 `GET /v1/me` 为准。 ## 可订阅的内容 **交易所公告**(`announcement.*`,含上新判定与代币代码)、**新闻快讯**(`news.*`,标题、摘要与原文链接)、**信号**(`signal.*`)与**推特 KOL 推文**(`twitter.*`,我们精选的一批 KOL 账号的原创、引用、回复与转推)。每个来源是一个主题,新接入的交易所、新闻源或信号源会自动出现在[主题清单](https://tokenearly.com/developers/topics)里;推特账号名单会调整,同样以主题清单为准。 ## FAQ **不付费能先试吗?** 可以。用已验证邮箱的账号登录后,在[控制台 → 开发者 API](https://tokenearly.com/dashboard?tab=developer-api)申请试用 Key:有效 12 小时,每个账号每 30 天可申请 6 次。接口、实时推送与数据格式和正式 Key 完全一样,试用 Key 仅供开发测试。 **同一条公告为什么会收到两次?** 首次入库时推送 revision=1;补齐中英韩标题或原文链接后会以同一个 id、更大的 revision 再推一次(action=updated)。推文同理:先到的精简版之后,完整版以同一个 id 再推一次。按 id 保留 revision 最大的一版即可。 **MCP 和 REST 有什么区别?** 数据和权限完全一样,只是调用方不同:REST 给你写的程序调用;MCP(Model Context Protocol)给 Claude、Cursor 这类 AI 客户端调用,AI 会自己发现有哪些工具、该传什么参数。两者共用同一个 Key 和同一份限频(每 3 秒 1 次),都只能查询,实时推送只有 WebSocket。 **AI agent 能直接调用吗?** 可以。MCP 服务器地址是 `https://api.tokenearly.com/v1/mcp`,Claude、Cursor 等客户端填上地址和 Key 即可使用;也可以把任意文档页复制成 Markdown 交给 AI。 --- # 鉴权与 API Key 每个请求都带上 API Key:服务端代码放在 `Authorization: Bearer ` 请求头里;浏览器里的 WebSocket 不能设置请求头,改用 `api_key` 查询参数。 > Source: https://tokenearly.com/developers/authentication · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 示例 下面每个示例都调用 `GET /v1/me`,它返回这把 Key 能读的主题、限额与 IP 白名单,适合用来验证 Key 是否配置正确。 **cURL** ```bash curl "https://api.tokenearly.com/v1/me" \ -H "Authorization: Bearer te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` **Python** ```python import os, requests KEY = os.environ["TOKENEARLY_API_KEY"] # te_live_... resp = requests.get( "https://api.tokenearly.com/v1/me", headers={"Authorization": f"Bearer {KEY}"}, timeout=10, ) print(resp.status_code, resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/me", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); console.log(resp.status, await resp.json()); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **X-API-Key** ```bash curl "https://api.tokenearly.com/v1/me" \ -H "X-API-Key: te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` **WebSocket** ```python import asyncio, os import websockets # pip install websockets async def main(): async with websockets.connect( "wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*", additional_headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, ) as ws: print(await ws.recv()) # {"op": "welcome", ...} asyncio.run(main()) ``` **Browser** ```javascript // Browsers cannot set headers on WebSocket: pass the key as a query parameter. // Only do this in tools you control; never ship a real key in public front-end code. const ws = new WebSocket("wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*&api_key=te_live_..."); ws.onmessage = (e) => console.log(JSON.parse(e.data)); ``` Key 缺失或无效时返回 401: **401 响应** ```json { "error": { "code": "invalid_api_key", "message": "This API key does not exist or has been revoked.", "docs": "https://tokenearly.com/en/developers/errors" } } ``` ## 三种传法 | 方式 | 示例 | 适用 | |---|---|---| | Authorization | `Authorization: Bearer te_live_…` | 推荐,REST、WebSocket、MCP 都支持 | | X-API-Key | `X-API-Key: te_live_…` | 无法设置 Bearer 的工具 | | api_key | `wss://…/v1/stream?api_key=te_live_…` | 仅限浏览器 WebSocket(浏览器不能设置请求头) | ## 创建 Key 1. 登录后打开[控制台 → 开发者 API](https://tokenearly.com/dashboard?tab=developer-api)。 2. 点「创建 API Key」,起个名字;需要的话填上 IP 白名单(可选)。 3. 复制弹窗里的 Key。它只显示这一次,我们只保存它的哈希值。 每个账号默认可建 1 把 Key,要换 Key 时点「重置」。Key 可以读取套餐开放的全部主题,具体要哪些主题在请求或连接时用 `topics` 参数选择;用 [GET /v1/me](https://tokenearly.com/developers/rest/me) 随时查看实际生效的主题。 Key 归账号所有,只是账号的钥匙:正式 Key 可读的主题和[我的推送](https://tokenearly.com/developers/my-alerts)(开关、历史与游标)都跟账号走,换 Key 后照旧。实时流订阅了哪些主题由客户端每次连接时用 `topics` 指定,不保存在 Key 上,换 Key 后用同样的参数重连即可。IP 白名单是每把 Key 各自设置的:重置会保留,新建的 Key 需要重新填。 ### 重置 Key Key 泄露、丢失或要定期更换时,在控制台点这把 Key 的「重置」(试用 Key 也可以):生成一把新 Key,旧 Key 立即失效——REST 与 MCP 返回 401 `invalid_api_key`,正在用旧 Key 的实时流连接收到 `op = "error"` 后以 4001 断开,不要自动重连,换成新 Key 再连。Key ID、名称、IP 白名单、限额和到期时间都不变;试用 Key 重置不消耗申请次数,也不延长有效期。 ### Key 的有效期 正式 Key 本身不过期,能不能用取决于账号的会员:含开发者 API 的会员有效期内一直可用,会员到期后所有正式 Key 以 403 `plan_required`(实时流 4003)被拒;续费后同一把 Key 立即恢复,不用重建。到期时间看 [GET /v1/me](https://tokenearly.com/developers/rest/me) 的 `access_expires_at` 或控制台。到期前 7、3、1 天和到期后,我们会发邮件、推送到你设置的通知渠道,并通过[变更通知](https://tokenearly.com/developers/rest/notices)(`access_expiring` / `access_expired`)告诉接入程序。试用 Key 不跟随会员,按自身的 `expires_at`(与 `access_expires_at` 相同)到期,到期后返回的是 401 `key_expired`(实时流 4001),不能续期:重新申请试用 Key,或开通后创建正式 Key。 > Key 等同于密码:不要写进前端代码、不要提交到代码仓库。泄露后在控制台重置或吊销,旧 Key 立即失效,用它的实时流连接也会立即断开。 ## IP 白名单(可选) 在控制台给 Key 填上服务器的出口 IP,之后只有这些地址能用这把 Key,Key 即使泄露也无法在别处使用。不填 = 不限来源。随时可以修改,修改后一分钟内对已建立的实时流连接生效。 | 写法 | 含义 | |---|---| | `203.0.113.5` | 单个 IPv4 地址 | | `203.0.113.0/24` | 一个网段(CIDR) | | `2001:db8::1` | IPv6 地址或网段 | REST 与 MCP 从白名单外的地址调用时返回 403 `ip_not_allowed`;WebSocket 先发 `op = "error"` 再以关闭码 4003 断开。 **403 响应** ```json { "error": { "code": "ip_not_allowed", "message": "Requests from 198.51.100.7 are not in this key's IP allowlist.", "docs": "https://tokenearly.com/en/developers/errors" } } ``` ## 边界行为 | 情况 | 行为 | |---|---| | 同时带 `Authorization: Bearer` 与 `X-API-Key` | 以 `Authorization` 为准,忽略 `X-API-Key` | | `Authorization` 不是 Bearer(例如 Basic) | 忽略它,改读 `X-API-Key` / `api_key` | | 优先级 | `Authorization: Bearer` > `X-API-Key` > `api_key`。`api_key` 查询参数只在 WebSocket 生效,REST 上会被忽略(返回 401 `missing_api_key`);Bearer 里的 Key 错了不会再去试 `api_key`,直接 4001 | | `bearer` 小写、Key 前后多空格 | 都接受 | ## 试用 Key 还没开通开发者 API 的账号,可以在控制台申请试用 Key,先把代码跑通。 | 项目 | 试用 Key | |---|---| | 申请条件 | 已验证邮箱的正式账号(游客账号不行) | | 有效期 | 12 小时,到期自动失效 | | 次数 | 每个账号每 30 天 6 次;同一时间只有一把生效 | | 数据 | 全部主题,实时推送;历史可查 7 天 | | 限频与连接 | 与正式 Key 默认值相同:每 3 秒 1 次,同时 1 条连接 | | 到期后 | REST 返回 401 `key_expired`,实时连接以关闭码 4001 断开 | > 试用 Key 仅供开发测试,不得用于生产或商业用途。正式接入请开通后创建正式 Key。 --- # 限流与配额 默认每个账号 1 把 API Key;每把 Key 同时 1 条 WebSocket 连接,REST 与 MCP 每 3 秒 1 次。 > Source: https://tokenearly.com/developers/limits · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 规则一览 | 项目 | 限制 | 超出时 | |---|---|---| | API Key | 每个账号 1 把 | 无法创建新 Key,先吊销旧的 | | WebSocket 连接 | 每把 Key 同时 1 条 | 新连接被拒绝,关闭码 `4029` | | REST 与 MCP | 每把 Key 每 3 秒 1 次(两者合计) | `429`,按 `Retry-After` 等待 | | 历史范围 | 以套餐为准,见 `/v1/me` 的 `limits.api_history_days` | 更早的事件不返回(不报错) | 无需 Key 的接口(`/v1/topics`、`/v1/schema`、`/v1/health`)不计入限频。 > 上表是默认值。我们可以按账号或按单把 Key 调整(例如给某把 Key 更高的频率或更多连接);你的 Key 实际生效的限额请调用 `GET /v1/me` 查看 `limits`。 限额有调整时(默认值、你的账号或某把 Key),在线的实时连接会立刻收到一条 `op = "notice"` 消息,内容包括旧值和新值;同样的记录可以用 [GET /v1/notices](https://tokenearly.com/developers/rest/notices) 补拉,也会显示在控制台的「变更记录」里。 ## REST 限频 同一把 Key 两次请求之间至少间隔 3 秒。需要 Key 的接口返回成功(200)时带下面这些头;`429` 同样带上它们,另加 `Retry-After`;其他错误响应不带: | 响应头 | 含义 | |---|---| | `X-RateLimit-Limit` | 窗口内允许的次数(1) | | `X-RateLimit-Window` | 窗口长度,秒(3) | | `X-RateLimit-Remaining` | 当前窗口剩余次数 | | `X-RateLimit-Reset` | 距离下次可请求的秒数 | | `Retry-After` | 仅 429 时出现:等待多少秒再试(整数秒) | ### 哪些请求计入 | 请求 | 是否计入 | |---|---| | 成功的请求(200) | 计入 | | 通过鉴权之后才失败的请求:`400 invalid_cursor`、`GET /v1/events/{id}` 的 `404 not_found` | 计入(响应不带限频头) | | 鉴权失败:`401`(缺 Key、Key 无效或已到期)、`403`(`ip_not_allowed`、`plan_required`) | 不计入 | | 参数格式错误 `400 invalid_parameter`(例如 `limit` 超出范围;在核对 Key 之前就被拒绝) | 不计入 | | 路径不存在(`404`)或方法不对(`405`) | 不计入 | | 被限频拒绝的请求(`429`) | 不计入,也不会推迟下次可请求的时间 | | `/v1/topics`(带不带 Key 都一样)、`/v1/schema`、`/v1/health` | 不计入 | | MCP 的 `get_events`、`get_event`、`get_alerts`、`whoami`(REST 的 `/v1/events`、`/v1/alerts`、`/v1/me`、`/v1/notices` 同样计入) | 计入,与 REST 共用同一份额度;但 MCP 的响应是 JSON-RPC,不带这些响应头,超限时工具返回 `rate_limited` 错误,消息里写明还要等几秒 | | MCP 的 `list_topics`、`get_schema`,以及 `initialize`、`tools/list` | 不计入 | **按 Retry-After 重试** ```python import time, requests def get(url, key, tries=5): for i in range(tries): r = requests.get(url, headers={"Authorization": f"Bearer {key}"}, timeout=10) if r.status_code != 429: r.raise_for_status() return r.json() time.sleep(int(r.headers.get("Retry-After", "1"))) # wait as instructed raise RuntimeError("still rate limited") ``` > REST 用来查历史和断线补拉,不适合轮询新消息。要实时数据请连 WebSocket:监控到新公告会直接推给你,也不占 REST 次数。 ## WebSocket 连接 连接数按 Key 计:每把 Key 同时最多 1 条实时流连接,名额满时新连接会收到 `too_many_connections` 并以关闭码 4029 断开——先关闭旧连接再连。要多条连接(例如多台服务器各连一条),就多建几把 Key,每台用自己的 Key。网络异常断开(没有正常关闭)的连接,服务端会在心跳超时后自动释放,通常不超过一分钟。 处理太慢、积压超过 500 条时连接以 4008 断开,带 `after` 重连即可续上。 --- # 主题:可订阅的消息来源 主题是订阅的最小单位,格式为 <类型>.<来源>。主题清单由平台的全局注册表生成,新来源接入后自动出现。 > Source: https://tokenearly.com/developers/topics · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 写法 | 写法 | 含义 | |---|---| | `announcement.binance` | 一个精确主题 | | `announcement.*` | 某一类型的全部来源 | | `*` | 全部主题 | | `announcement.binance,signal.*` | 逗号分隔组合使用 | 通配会在每次请求时展开,所以新来源接入后无需修改订阅。主题 ID 不区分大小写(`Announcement.Binance` = `announcement.binance`),返回的一律是小写。 推特主题是 `twitter.<账号的 X 数字 ID>`,对应我们精选的 KOL 账号:账号改名后主题 ID 不变,名单会增减。用 `twitter.*` 订阅即可自动跟上名单变化。 ## 当前主题 | 主题 ID | 名称 | 类型 | |---|---|---| | `announcement.binance` | 币安 | 交易所公告 | | `announcement.okx` | 欧易 | 交易所公告 | | `announcement.mexc` | 抹茶 | 交易所公告 | | `announcement.bitget` | Bitget | 交易所公告 | | `announcement.gate` | Gate.io | 交易所公告 | | `announcement.huobi` | 火币 | 交易所公告 | | `announcement.bybit` | Bybit | 交易所公告 | | `announcement.kucoin` | KuCoin | 交易所公告 | | `announcement.upbit` | Upbit | 交易所公告 | | `announcement.bithumb` | Bithumb | 交易所公告 | | `news.odaily` | Odaily | 新闻快讯 | | `news.jinse` | 金色财经 | 新闻快讯 | | `news.theblockbeats` | 律动 | 新闻快讯 | | `news.foresight` | Foresight News | 新闻快讯 | | `news.panews` | PANews | 新闻快讯 | | `news.coinmarketcap` | CoinMarketCap | 新闻快讯 | | `news.wallstreetcn` | 华尔街见闻 | 新闻快讯 | | `news.theblock` | The Block | 新闻快讯 | | `signal.binance_alpha` | Binance Alpha | 信号 | | `twitter.44196397` | @elonmusk (Elon Musk) | 推特 KOL 推文 | | `twitter.902926941413453824` | @cz_binance (CZ 🔶 BNB) | 推特 KOL 推文 | | `twitter.574032254` | @coinbase (Coinbase 🛡️) | 推特 KOL 推文 | | `twitter.1422537905885442055` | @CoinbaseAssets (Coinbase Assets 🛡️) | 推特 KOL 推文 | | `twitter.720487892670410753` | @CoinbaseMarkets (Coinbase Markets 🛡️) | 推特 KOL 推文 | | `twitter.877807935493033984` | @binance (Binance) | 推特 KOL 推文 | | `twitter.295218901` | @VitalikButerin (vitalik.eth) | 推特 KOL 推文 | | `twitter.1003840309166366721` | @heyibinance (Yi He) | 推特 KOL 推文 | | `twitter.902839045356744704` | @justinsuntron (H.E. Justin Sun 👨‍🚀 🌞) | 推特 KOL 推文 | | `twitter.900935123968737281` | @hebi555 (何币) | 推特 KOL 推文 | | `twitter.1403881130802225152` | @BTCdayu (大宇) | 推特 KOL 推文 | | `twitter.2985599460` | @star_okx (Star_OKX) | 推特 KOL 推文 | | `twitter.1533037218444476416` | @xincctnnq (币圈女菩萨|Pizza披萨🍕) | 推特 KOL 推文 | | `twitter.25073877` | @realDonaldTrump (Donald J. Trump) | 推特 KOL 推文 | | `twitter.1686901686185721857` | @TrumpDailyPosts (Commentary Trump Daily Posts) | 推特 KOL 推文 | | `twitter.20736511` | @nayibbukele (Nayib Bukele) | 推特 KOL 推文 | | `twitter.1844002277218242560` | @Plasma | 推特 KOL 推文 | | `twitter.2414580907` | @pauliepunt (Paul) | 推特 KOL 推文 | | `twitter.867617849208037377` | @okx (OKX) | 推特 KOL 推文 | | `twitter.1138033434` | @Rewkang (Andrew Kang) | 推特 KOL 推文 | | `twitter.1789908971953799168` | @Aster_DEX (Aster 🥷) | 推特 KOL 推文 | | `twitter.1948234340556763136` | @zakk_okx (Zakk 🟪 OKX AI) | 推特 KOL 推文 | | `twitter.357312062` | @Bitcoin | 推特 KOL 推文 | | `twitter.973261472` | @blknoiz06 (Ansem 🐂🀄️) | 推特 KOL 推文 | | `twitter.132749200` | @OxSunNFT (0xSun ❤️ Memecoin) | 推特 KOL 推文 | | `twitter.844304603336232960` | @MustStopMurad (Murad 💹🧲) | 推特 KOL 推文 | | `twitter.1195728139898376193` | @0xcryptowizard (0xWizard) | 推特 KOL 推文 | | `twitter.992590209752629249` | @notEezzy (Eezzy 🧸) | 推特 KOL 推文 | | `twitter.1800348208461205504` | @xiaomucrypto (新股神白毛股神) | 推特 KOL 推文 | | `twitter.16228398` | @mcuban (Mark Cuban) | 推特 KOL 推文 | | `twitter.1189381231198134272` | @CookerFlips (Cooker.hl \| 版本之子 \| (Theo Arc)) | 推特 KOL 推文 | | `twitter.1279711663264894977` | @DekuKing1 (0x易经(刘彻版)) | 推特 KOL 推文 | | `twitter.725984371946082304` | @XXAntiWar (XX) | 推特 KOL 推文 | | `twitter.1462727797135216641` | @lookonchain (Lookonchain) | 推特 KOL 推文 | | `twitter.1466673394649559040` | @huahuayjy (花花) | 推特 KOL 推文 | | `twitter.1401718840535379970` | @hellosuoha (梭教授说) | 推特 KOL 推文 | | `twitter.1453603581932687368` | @laofeiyyds (比特币老肥.btc(敏感肥)) | 推特 KOL 推文 | | `twitter.1852674305517342720` | @aixbt_agent (aixbt) | 推特 KOL 推文 | | `twitter.1279918106111025153` | @assetdash (Dash News) | 推特 KOL 推文 | | `twitter.169686021` | @kanyewest (ye) | 推特 KOL 推文 | | `twitter.1483495485889564674` | @bwenews (方程式新闻 BWEnews 🏎️) | 推特 KOL 推文 | | `twitter.1052454006537314306` | @BNBCHAIN (BNB Chain) | 推特 KOL 推文 | | `twitter.1451036242431262720` | @binancezh (币安Binance华语) | 推特 KOL 推文 | | `twitter.1940360837547565056` | @aleabitoreddit (Serenity) | 推特 KOL 推文 | 程序里请调用 [GET /v1/topics](https://tokenearly.com/developers/rest/topics) 获取最新清单。 --- # 事件格式:信封与各类消息字段 每条消息都是一个事件:固定的信封、稳定的 ID、可递增的修订号,以及按类型定义的 data。 > Source: https://tokenearly.com/developers/events · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 信封 所有事件共用同一个外壳;`data` 的结构由 `type` 决定。实时流与 REST 返回的事件出自同一个构建函数,字段完全一致。 | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| | `spec_version` | `"1.0"` | ✓ | 事件格式版本。同一大版本内只增字段、不删不改。 | | `id` | `string` | ✓ | 事件的稳定 ID(24 位十六进制),所有修订版共用,永不改变;按事件首次入库时间递增,可以直接按字符串比较大小。也是分页与续传的游标。 | | `revision` | `integer` | ✓ | 修订号,从 1 开始;补齐翻译或原文链接后递增,推文的完整版到达后也递增。按 (id, revision) 去重,保留最大的一版。 | | `action` | `"created" \| "updated"` | ✓ | created = 首次出现;updated = 同一事件的新修订版。 | | `topic` | `string` | ✓ | 主题 ID,格式 <类型>.<来源>,例如 announcement.binance;推特账号用数字 ID,例如 twitter.44196397。 | | `type` | `"announcement" \| "news" \| "signal" \| "twitter"` | ✓ | 消息类型,决定 data 的结构。 | | `source` | `object` | ✓ | 来源:id 与主题后缀一致,name 为英文显示名(推特为 @用户名 与显示名)。 (id, name) | | `published_at` | `integer \| null` | ✓ | 来源发布时间,Unix 秒。 | | `published_at_ms` | `integer \| null` | | 来源发布时间,Unix 毫秒;来源不提供毫秒时为秒 × 1000。 | | `detected_at_ms` | `integer \| null` | ✓ | Tokenearly 收到这条消息的时间,Unix 毫秒;极少数早期记录没有,为 null。 | | `data` | `object` | ✓ | 消息内容,结构随 type 而定(见下方各类型)。 | ## 生命周期与去重 - 首次出现:`action = "created"`,`revision = 1`。 - 补齐中英韩标题或原文链接后(推文:完整版到达后):同一个 `id`,`action = "updated"`,`revision` 递增。 - `id` 永不改变;按 (id, revision) 去重,保留 revision 最大的一版。 **去重示例** ```python latest = {} # event id -> highest revision seen def handle(ev): if latest.get(ev["id"], 0) >= ev["revision"]: return # duplicate or older revision first_time = ev["id"] not in latest latest[ev["id"]] = ev["revision"] if first_time: notify(ev) # new to you, whatever its action: after a reconnect a new item # can already be at revision 2 (action = "updated") else: update(ev) # same event, translations / link filled in ``` ## 交易所公告(type = announcement) | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| | `titles` | `object` | ✓ | 标题,zh / en / ko;尚未翻译的语言暂缺,翻译完成后以新修订版推送。 (zh, en, ko) | | `original_lang` | `string` | ✓ | 交易所发布时使用的语言:zh / en / ko 之一。 | | `translated_langs` | `array` | ✓ | 由机器翻译生成的标题语言。不在这里的标题都是交易所官方版本:多数交易所只发布一种语言;部分交易所同时发布中文与英文官方版本,可能同一次推送就带上两种,也可能稍后才出现(届时以新修订版推送,并会替换之前的机器翻译、从这里移除)。机器翻译首次推送时为空,通常几秒到几十秒内补齐并以新修订版再推一次,偶尔会晚几分钟或缺失。 | | `url` | `string \| null` | ✓ | 交易所原文链接;个别来源稍后补齐(届时以新修订版推送)。 | | `exchange_category` | `string \| null` | ✓ | 交易所自己的分类名,原样给出、不翻译。 | | `listing` | `object` | ✓ | 上新判定:is_listing 是否为新币上线,market 为 spot / futures / null。与站内上新时间线同一判定。 (is_listing, market) | | `symbols` | `array` | ✓ | 从标题中识别出的代币代码。 | `data.listing` 是上新判定,`data.symbols` 是标题里识别出的代币代码,可直接用来过滤上新。`is_listing = false` 时 `market` 一定是 null。 **首次推送(revision 1):只有原文语言的标题** ```json { "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": [] } } ``` **翻译补齐后(同一个 id,revision 更大):多了机器翻译的标题** ```json { "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) | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| | `titles` | `object` | ✓ | 标题,zh / en / ko;尚未翻译的语言暂缺,翻译完成后以新修订版推送。 (zh, en, ko) | | `original_lang` | `string` | ✓ | 新闻源发布时使用的语言:zh / en / ko 之一。 | | `translated_langs` | `array` | ✓ | 由机器翻译生成的标题语言。不在这里的标题都是新闻源官方版本:多数新闻源只发布一种语言;部分新闻源同时发布中文与英文官方版本,可能同一次推送就带上两种,也可能稍后才出现(届时以新修订版推送,并会替换之前的机器翻译、从这里移除)。机器翻译首次推送时为空,通常几秒到几十秒内补齐并以新修订版再推一次,偶尔会晚几分钟或缺失。 | | `summary` | `string \| null` | ✓ | 新闻源给出的摘要,原文语言,最长 600 字;不提供正文。可能为空。 | | `url` | `string \| null` | ✓ | 原文链接;部分新闻源的快讯没有链接,此时为 null。 | `data.summary` 是新闻源给出的摘要(原文语言),不提供正文;完整内容请打开 `data.url`(部分快讯没有链接,为 null)。 快讯类来源本身没有标题,`titles` 取自正文开头,可能被截断并以「...」结尾。 **首次推送(revision 1):只有原文语言的标题** ```json { "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" } } ``` **翻译补齐后(同一个 id,revision 更大):多了机器翻译的标题** ```json { "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) | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| | `signal_type` | `string` | ✓ | 信号类型(来源自定义的细分类型)。 | | `level` | `"info" \| "warning" \| "critical"` | ✓ | 重要程度:info / warning / critical。 | | `titles` | `object` | ✓ | 标题,zh / en / ko;个别语言可能缺失,请按需回退到其他语言。 (zh, en, ko) | | `contents` | `object` | ✓ | 正文摘要,zh / en / ko。 (zh, en, ko) | | `url` | `string \| null` | ✓ | 相关链接(可能为空)。 | | `symbols` | `array` | ✓ | 涉及的代币代码。 | | `tags` | `array` | ✓ | 标签。 | **示例:一条信号(真实数据)** ```json { "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) | 字段 | 类型 | 必填 | 说明 | |---|---|---|---| | `kind` | `"tweet" \| "quote" \| "reply" \| "retweet"` | ✓ | 推文类型:tweet = 原创,quote = 引用,reply = 回复,retweet = 转推。首次推送时偶尔还不是最终类型(例如原创后来确认为引用),以新修订版更正。 | | `tweet_id` | `string` | ✓ | 这条推文在 X 上的 ID。转推、回复、引用都是这条动作本身的 ID。 | | `author` | `object` | ✓ | 发推的账号:id 为 X 数字 ID(与主题后缀一致,改名不变),screen_name 为当时的用户名(不含 @),name 为显示名。 (id, screen_name, name) | | `text` | `string` | ✓ | 推文正文,原文,不翻译。首次推送可能是精简版(complete = false)。 | | `lang` | `string \| null` | ✓ | X 标注的语言代码(如 en、zh、ja);未知时为 null。X 还会给出几个不是语言的特殊代码,原样透传:`zxx`(无文字,如只有图片或链接)、`qme`(只有表情或提及)、`qst`(极短文本)、`art`(只有表情符号)等。 | | `url` | `string \| null` | ✓ | 推文在 X 上的链接。 | | `referenced_tweet_id` | `string \| null` | ✓ | 被引用、被回复或被转推的那条推文的 ID;原创为 null。首次推送时可能还没有,以新修订版补上;个别较早的帖子可能一直为 null。 | | `conversation_id` | `string \| null` | ✓ | 预留字段:会话(话题串)ID。目前数据源不提供,恒为 null;要串起回复,请用 `referenced_tweet_id` 逐级往上找。 | | `media` | `array` | ✓ | 图片 / 视频的链接,最多 20 个;首次推送时可能为空,完整版补齐。 | | `complete` | `boolean` | ✓ | 是否已是完整版。推文有时先以精简版推送(正文可能截断、媒体与被引用推文暂缺),完整版到达后以同一个 id、更大的 revision 再推一次,此时为 true。 | 只包含我们精选的一批 KOL 账号的推文:原创、引用、回复与转推;资料修改、关注变化等动态不在 API 里。名单会增减,当前名单以 `GET /v1/topics` 为准。 `data.kind`:`tweet` 原创、`quote` 引用、`reply` 回复、`retweet` 转推;后三种的 `data.referenced_tweet_id` 是被引用、被回复或被转推的那条推文。 推文有时先推精简版(`data.complete = false`):正文可能截断,媒体、被引用推文与语言暂缺,类型偶尔还会从 `tweet` 更正为 `quote`。完整版随后以同一个 `id`、更大的 `revision` 再推一次。 推文按原文给出,不翻译,没有 `titles`。如果订阅了 `*`,请按 `type` 分别解析。 推文只保留最近 10 天:REST 查询与断线续传都只能取到这个范围内的推文(与套餐的历史天数取较小值)。 **示例:一条推文(真实数据)** ```json { "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 } } ``` ## 兼容性约定 - 同一大版本内只会**新增**字段,不删除、不改名、不改类型。请忽略不认识的字段。 - 新的消息类型会以新的 `type` 出现,请对未知 `type` 做忽略处理。 - 完整的 JSON Schema 见 [GET /v1/schema](https://tokenearly.com/developers/rest/schema)。 --- # 我的推送 除了按主题订阅的全量事件,API 还能把**真正推给你的那一份**提醒原样给你:和你在网页上设置的 Bark、企业微信等渠道收到的完全相同,按你的来源、关键词、通知语言过滤。适合把我们的提醒接进你自己的机器人或工作流。 > Source: https://tokenearly.com/developers/my-alerts · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 两种数据的区别 | | 主题事件(通用数据流) | 我的推送(本页) | |---|---|---| | 内容 | 订阅主题下的**全部**消息,不经过任何个人设置 | 只有**推给你的**那些:按你在网页上设置的来源开关、关键词、通知语言、会员延迟过滤 | | 和渠道的关系 | 无关 | 与 Bark、企业微信等渠道收到的是同一份,逐条一致 | | 格式 | 结构化事件,`op = "event"`(字段见[事件格式](https://tokenearly.com/developers/events)) | 推送文本 + 少量结构化字段,`op = "alert"` | | 语言 | 中英韩标题都在一条事件里,补齐后以新修订版再推 | 按你的通知语言:原文不是你的语言时先推原文(`label = "original"`),译文到了再补推一条(`followup = true`) | | 怎么订阅 | `topics=announcement.binance,news.*` 等(逗号分隔,可任意组合) | `topics=my_alerts`(特殊主题,`*` 不包含它) | | 断线补齐 | 带 `after` 重连自动补发 | 实时流不补发;用 `GET /v1/alerts?after=` 补拉 | | 保留 | 按套餐的历史天数 | 最近 7 天 | > 两者可以在同一条 WebSocket 连接里同时订阅(`topics=my_alerts,announcement.*`),靠 `op` 区分:`event` 是主题事件,`alert` 是我的推送。同一条公告既会作为事件推送,也可能作为我的推送推送,两者 ID 不同,`ref.event_id` 指向对应的事件。 ## 开通 1. 在网页「全局通知管理 → 通知渠道」打开「开发者 API」开关。关着时不会产生新的我的推送(`welcome.my_alerts.channel_enabled` 与 REST 响应里的 `channel_enabled` 会告诉你)。 2. 在网页上照常设置要订阅的来源、关键词和通知语言——我的推送完全跟随这些设置,不需要在每个来源单独勾选「开发者 API」:只要有一条推送发给你,API 就会同时收到一份。 3. 用任意一把 API Key 连接 `wss://api.tokenearly.com/v1/stream?topics=my_alerts`,或调用 [GET /v1/alerts](https://tokenearly.com/developers/rest/alerts)。同一账号的所有 Key 看到的是同一份我的推送。`my_alerts` 只在实时流里是特殊主题;REST 的 `GET /v1/events?topics=my_alerts` 会把它当作不存在的主题放进 `access.unknown`,补拉请用 `GET /v1/alerts`。 > 我的推送遵循你账号的会员延迟:付费会员实时,免费账号与其他渠道一样延迟送达。 ## 消息格式 实时流里每条推送是 `{"op": "alert", "alert": {...}}`;REST 返回 `{"alerts": [...]}`,里面的对象完全相同。 | 字段 | 说明 | |---|---| | `id` | 推送 ID(24 位十六进制,随时间递增)。`after` / `before` 游标用它;与事件 ID 不是一套。 | | `category` | 类别:`announcement` 公告、`news` 新闻、`twitter` 推特、`signal` 信号、`price_alert` 价格提醒、`contract_movement` 合约异动。 | | `source` | `{id, name}`:来源 ID(如 `binance`、`odaily`、推特账号数字 ID)与显示名。 | | `followup` | `true` = 对一条已推给你的提醒的补推(例如先推原文、这条是译文)。 | | `lang` | `text` 的语言(`zh` / `en` / `ko`),公告与新闻才有,其他类别为 `null`。 | | `label` | `original` = 原文不是你设置的通知语言,先推原文(之后会补推译文);`translation` = 译文(机器翻译);`official_translation` = 来源(交易所或新闻媒体)后来发布的官方该语言版本;`null` = 推送时就已经是你的语言(来源原本就是这个语言,或推送前来源已经发布了这个语言的官方版本),或不适用(如价格提醒)。请按 `label` 和 `lang` 字段判断,不要解析 `text` 的第一行:标注行的写法会随推送语言变化,历史数据里也有旧写法。 | | `title` | 渠道上显示的标题,跟随你的通知语言:中文如 `【币安(BINANCE)】`,英文、韩文如 `[BINANCE]`、`[WallStreetCN]`。 | | `text` | 和 Bark、企业微信收到的正文完全相同的纯文本(含换行与原文 / 译文标注行)。只翻译标题:新闻的摘要保持来源的原文语言(来源自己发布了你的语言版本时除外)。 | | `url` | 提醒里的链接;公告与新闻是 `lang` 对应语言的官方页面。 | | `titles` | 发送时已有的各语言标题(公告与新闻),否则 `null`。 | | `ref` | 这条提醒对应的主题事件 `{type, topic, event_id}`(公告与新闻),用 `GET /v1/events/{event_id}` 取结构化数据;其他类别为 `null`。 | | `created_at` | 发送时间(Unix 秒)。 | ### 示例:原文先推(你的通知语言是中文,公告原文是英文) ```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 } } ``` ### 示例:译文补推(同一条公告) ```json { "op": "alert", "alert": { "id": "6af57203e1b0c95f3a7d2e47", "category": "announcement", "source": { "id": "binance", "name": "Binance" }, "followup": true, "lang": "zh", "label": "translation", "title": "【币安(BINANCE)】", "text": "【译文】\n币安将上线 Fooken (FOO) 并添加种子标签\n— — — — — — — — — —\nhttps://www.binance.com/zh-CN/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)", "url": "https://www.binance.com/zh-CN/support/announcement/detail/abc123", "titles": { "en": "Binance Will List Fooken (FOO) with Seed Tag Applied", "zh": "币安将上线 Fooken (FOO) 并添加种子标签", "ko": "바이낸스, 시드 태그가 적용된 Fooken(FOO) 상장" }, "ref": { "type": "announcement", "topic": "announcement.binance", "event_id": "6af57200e1b0c95f3a7d2e40" }, "created_at": 1794470403 } } ``` 同一条公告的原文与译文是两条推送(`id` 不同),`ref.event_id` 相同。每种语言最多补推一次;翻译失败时不补推(你已经收到原文)。原文本来就是你的通知语言时只有一条,`label = null`。 ### 示例:REST 响应 **GET /v1/alerts?limit=2** ```json { "alerts": [ { "id": "6af57203e1b0c95f3a7d2e47", "category": "announcement", "source": { "id": "binance", "name": "Binance" }, "followup": true, "lang": "zh", "label": "translation", "title": "【币安(BINANCE)】", "text": "【译文】\n币安将上线 Fooken (FOO) 并添加种子标签\n— — — — — — — — — —\nhttps://www.binance.com/zh-CN/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)", "url": "https://www.binance.com/zh-CN/support/announcement/detail/abc123", "titles": { "en": "Binance Will List Fooken (FOO) with Seed Tag Applied", "zh": "币安将上线 Fooken (FOO) 并添加种子标签", "ko": "바이낸스, 시드 태그가 적용된 Fooken(FOO) 상장" }, "ref": { "type": "announcement", "topic": "announcement.binance", "event_id": "6af57200e1b0c95f3a7d2e40" }, "created_at": 1794470403 }, { "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 } ], "has_more": false, "next_cursor": null, "cursor_param": "before", "channel_enabled": true } ``` ## 断线补齐 1. 处理每条推送时保存它的 `id`。 2. 重连收到 `welcome` 后,用 `GET /v1/alerts?after=<最后的 id>` 按时间正序补拉,`has_more = true` 时用最后一条的 `id` 继续。 3. 补拉与实时推送可能重叠,按 `id` 去重。保留期是 7 天,离线超过 7 天的部分取不回来。 ## 订阅与退订 | 操作 | 写法 | |---|---| | 只要我的推送 | `?topics=my_alerts` | | 我的推送 + 主题事件 | `?topics=my_alerts,announcement.*,news.odaily` | | 连接后再订阅 / 退订 | `{"op":"subscribe","topics":["my_alerts"]}` / `{"op":"unsubscribe","topics":["my_alerts"]}` | | `unsubscribe` `["*"]` | 只退订主题事件,我的推送保持(要停止请显式退订 `my_alerts`) | `subscribed` 回复里的 `my_alerts.subscribed` 是这条连接当前的状态。 ## 完整示例 **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}"} STREAM = "wss://api.tokenearly.com/v1/stream?topics=my_alerts" # my alerts only; add topics (e.g. ",announcement.*") to also get events ALERTS = "https://api.tokenearly.com/v1/alerts" FATAL = {4001, 4003} # bad / expired key, no permission: fix it, do not retry last_id = None # last alert id you processed (store it durably in production) seen = set() # ids already handled: the REST catch-up and the stream can overlap def handle(n): global last_id if n["id"] in seen: return seen.add(n["id"]) if not last_id or n["id"] > last_id: # ids grow with time; only move the cursor forward last_id = n["id"] # n["text"] is exactly what your Bark / WeCom received; n["label"] says original / translation print(n["category"], n["source"]["name"], n["label"], "follow-up" if n["followup"] else "first") print(n["text"]) if n["ref"]: # announcements and news: the topic event behind this alert print("event:", n["ref"]["event_id"]) # GET /v1/events/{event_id} for the structured data def catch_up(): """Notifications sent while you were offline: the stream does not replay them.""" if not last_id: return while True: r = requests.get(ALERTS, params={"after": last_id, "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() page = r.json() for n in page["alerts"]: # oldest first when `after` is given handle(n) if not page["has_more"]: return time.sleep(int(r.headers.get("X-RateLimit-Reset", "3"))) # respect the per-key interval async def main(): delay = 1 while True: try: async with websockets.connect(STREAM, additional_headers=H) as ws: async for raw in ws: msg = json.loads(raw) op = msg["op"] if op == "welcome": delay = 1 if not msg["my_alerts"]["channel_enabled"]: print("Turn on the Developer API switch under Notification channels in the dashboard.") await asyncio.to_thread(catch_up) # blocking HTTP off the event loop elif op == "alert": handle(msg["alert"]) elif op == "error": print("server error:", msg["code"], msg["message"]) 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 except Exception as e: print("disconnected:", e) await asyncio.sleep(delay) delay = min(delay * 2, 60) # exponential backoff asyncio.run(main()) ``` **Node.js** ```javascript // npm install ws (Node.js 18+ for fetch) const WebSocket = require("ws"); const KEY = process.env.TOKENEARLY_API_KEY; const H = { Authorization: `Bearer ${KEY}` }; const STREAM = "wss://api.tokenearly.com/v1/stream?topics=my_alerts"; const ALERTS = "https://api.tokenearly.com/v1/alerts"; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let lastId = null; // last alert id processed (persist it in production) const seen = new Set(); // REST catch-up and the stream can overlap function handle(n) { if (seen.has(n.id)) return; seen.add(n.id); if (!lastId || n.id > lastId) lastId = n.id; console.log(n.category, n.source.name, n.label, n.followup ? "follow-up" : "first"); console.log(n.text); // exactly what your Bark / WeCom received } async function catchUp() { if (!lastId) return; // the stream does not replay my alerts for (;;) { const r = await fetch(`${ALERTS}?after=${lastId}&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.alerts.forEach(handle); // oldest first when `after` is given if (page.has_more) await sleep(1000 * Number(r.headers.get("x-ratelimit-reset") || 3)); // respect the per-key interval else return; } } function connect(delay = 1) { const ws = new WebSocket(STREAM, { headers: H }); ws.on("message", (raw) => { const msg = JSON.parse(raw); if (msg.op === "welcome") { delay = 1; if (!msg.my_alerts.channel_enabled) console.log("Turn on the Developer API switch in the dashboard."); catchUp().catch((e) => console.error("catch-up failed:", e.message)); // runs alongside live messages; dedupe by id } else if (msg.op === "alert") { handle(msg.alert); } else if (msg.op === "error") { console.error("server error:", msg.code, msg.message); } }); ws.on("close", (code) => { if (code === 4001 || code === 4003) return console.error("stopped: close code", code); // fix the key / plan first const wait = code === 4029 ? Math.max(delay, 5) : delay; // 4029: the slot may take a few seconds to free up setTimeout(() => connect(Math.min(wait * 2, 60)), wait * 1000); }); ws.on("error", (e) => console.error("socket error:", e.message)); } connect(); ``` --- # 查询事件 按主题查询历史事件,支持游标翻页与断线补拉。 > Source: https://tokenearly.com/developers/rest/list-events · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/events` 默认返回最新的事件(按时间倒序)。带 `after` 时改为正序,返回该事件之后的所有事件,适合断线补拉;带 `before` 时向更早翻页。`has_more` 为 true 时,把 `next_cursor` 原样放进 `cursor_param` 指明的参数里继续请求。响应里的 `access` 列出本次请求的主题中哪些有权限(granted)、哪些没有(denied)、哪些不存在(unknown)。可查询的时间范围由套餐的历史天数决定。 **需要 API Key** ## 参数 | 参数 | 位置 | 类型 | 必填 | 说明 | |---|---|---|---|---| | `topics` | query | string | | 逗号分隔,可以任意组合(例如 `announcement.binance,news.*`),每一项是主题或通配:`announcement.binance`、`announcement.*`、`news.*`、`signal.*`、`twitter.*`、`*`。省略 = Key 可用的全部主题。 | | `after` | query | string | | 返回比该事件 ID 更新的事件,按时间正序。用于断线后补拉。 | | `before` | query | string | | 返回比该事件 ID 更早的事件,按时间倒序。用于向前翻页。 | | `updated_after` | query | integer | | 返回在这个时间(Unix 秒)之后产生了新修订版的事件(事件本身可以更早),按事件 ID 正序;用来补齐断线期间旧事件的更新。翻页时 updated_after 保持不变,把上一页的 next_cursor 作为 after 传入。不能与 before 同时用。不传或传 0 表示不使用这个参数(此时按普通列表返回,最新在前)。 | | `limit` | query | integer | | 每页条数,1–200,默认 50。 | | `listings_only` | query | boolean | | 设为 true 时只返回判定为上新的交易所公告(`data.listing.is_listing = true`),其他类型的主题一律不返回;可与 `after` / `before` / `updated_after` 一起用。因为是按判定结果筛选,一页可能少于 `limit` 条而 `has_more` 仍为 true:继续用 `next_cursor` 翻页,直到 `has_more = false`。 | ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "events": [ { "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" } }, { "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 } }, { "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": [] } }, { "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" ] } } ], "has_more": true, "next_cursor": "6b055216d0e4e92d8480d1e5", "cursor_param": "before", "access": { "granted": [ "announcement.gate", "news.jinse", "signal.binance_alpha", "twitter.44196397" ], "denied": [], "unknown": [] } } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `invalid_cursor` | 400 | after / before 不是合法的 ID(查事件时是事件 ID,查我的推送时是推送 ID),两者同时出现,或(仅查事件)updated_after 与 before 同时使用。 | | `invalid_parameter` | 400 | 参数类型或取值不合法(例如 limit 超出范围)。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | ## 可以查询哪些主题 `topics` 参数填下表里的主题 ID,或用 `announcement.*`、`news.*`、`signal.*`、`twitter.*`、`*` 通配。能否读取由套餐决定:响应里的 `access` 会逐个告诉你——`granted` 有权限并已返回,`denied` 没有权限,`unknown` 主题不存在。 **示例:请求 topics=announcement.binance,announcement.upbit,announcement.nope** ```json { "access": { "granted": [ "announcement.binance" ], "denied": [ "announcement.upbit" ], "unknown": [ "announcement.nope" ] } } ``` | 主题 ID | 名称 | 类型 | |---|---|---| | `announcement.binance` | 币安 | 交易所公告 | | `announcement.okx` | 欧易 | 交易所公告 | | `announcement.mexc` | 抹茶 | 交易所公告 | | `announcement.bitget` | Bitget | 交易所公告 | | `announcement.gate` | Gate.io | 交易所公告 | | `announcement.huobi` | 火币 | 交易所公告 | | `announcement.bybit` | Bybit | 交易所公告 | | `announcement.kucoin` | KuCoin | 交易所公告 | | `announcement.upbit` | Upbit | 交易所公告 | | `announcement.bithumb` | Bithumb | 交易所公告 | | `news.odaily` | Odaily | 新闻快讯 | | `news.jinse` | 金色财经 | 新闻快讯 | | `news.theblockbeats` | 律动 | 新闻快讯 | | `news.foresight` | Foresight News | 新闻快讯 | | `news.panews` | PANews | 新闻快讯 | | `news.coinmarketcap` | CoinMarketCap | 新闻快讯 | | `news.wallstreetcn` | 华尔街见闻 | 新闻快讯 | | `news.theblock` | The Block | 新闻快讯 | | `signal.binance_alpha` | Binance Alpha | 信号 | | `twitter.44196397` | @elonmusk (Elon Musk) | 推特 KOL 推文 | | `twitter.902926941413453824` | @cz_binance (CZ 🔶 BNB) | 推特 KOL 推文 | | `twitter.574032254` | @coinbase (Coinbase 🛡️) | 推特 KOL 推文 | | `twitter.1422537905885442055` | @CoinbaseAssets (Coinbase Assets 🛡️) | 推特 KOL 推文 | | `twitter.720487892670410753` | @CoinbaseMarkets (Coinbase Markets 🛡️) | 推特 KOL 推文 | | `twitter.877807935493033984` | @binance (Binance) | 推特 KOL 推文 | | `twitter.295218901` | @VitalikButerin (vitalik.eth) | 推特 KOL 推文 | | `twitter.1003840309166366721` | @heyibinance (Yi He) | 推特 KOL 推文 | | `twitter.902839045356744704` | @justinsuntron (H.E. Justin Sun 👨‍🚀 🌞) | 推特 KOL 推文 | | `twitter.900935123968737281` | @hebi555 (何币) | 推特 KOL 推文 | | `twitter.1403881130802225152` | @BTCdayu (大宇) | 推特 KOL 推文 | | `twitter.2985599460` | @star_okx (Star_OKX) | 推特 KOL 推文 | | `twitter.1533037218444476416` | @xincctnnq (币圈女菩萨|Pizza披萨🍕) | 推特 KOL 推文 | | `twitter.25073877` | @realDonaldTrump (Donald J. Trump) | 推特 KOL 推文 | | `twitter.1686901686185721857` | @TrumpDailyPosts (Commentary Trump Daily Posts) | 推特 KOL 推文 | | `twitter.20736511` | @nayibbukele (Nayib Bukele) | 推特 KOL 推文 | | `twitter.1844002277218242560` | @Plasma | 推特 KOL 推文 | | `twitter.2414580907` | @pauliepunt (Paul) | 推特 KOL 推文 | | `twitter.867617849208037377` | @okx (OKX) | 推特 KOL 推文 | | `twitter.1138033434` | @Rewkang (Andrew Kang) | 推特 KOL 推文 | | `twitter.1789908971953799168` | @Aster_DEX (Aster 🥷) | 推特 KOL 推文 | | `twitter.1948234340556763136` | @zakk_okx (Zakk 🟪 OKX AI) | 推特 KOL 推文 | | `twitter.357312062` | @Bitcoin | 推特 KOL 推文 | | `twitter.973261472` | @blknoiz06 (Ansem 🐂🀄️) | 推特 KOL 推文 | | `twitter.132749200` | @OxSunNFT (0xSun ❤️ Memecoin) | 推特 KOL 推文 | | `twitter.844304603336232960` | @MustStopMurad (Murad 💹🧲) | 推特 KOL 推文 | | `twitter.1195728139898376193` | @0xcryptowizard (0xWizard) | 推特 KOL 推文 | | `twitter.992590209752629249` | @notEezzy (Eezzy 🧸) | 推特 KOL 推文 | | `twitter.1800348208461205504` | @xiaomucrypto (新股神白毛股神) | 推特 KOL 推文 | | `twitter.16228398` | @mcuban (Mark Cuban) | 推特 KOL 推文 | | `twitter.1189381231198134272` | @CookerFlips (Cooker.hl \| 版本之子 \| (Theo Arc)) | 推特 KOL 推文 | | `twitter.1279711663264894977` | @DekuKing1 (0x易经(刘彻版)) | 推特 KOL 推文 | | `twitter.725984371946082304` | @XXAntiWar (XX) | 推特 KOL 推文 | | `twitter.1462727797135216641` | @lookonchain (Lookonchain) | 推特 KOL 推文 | | `twitter.1466673394649559040` | @huahuayjy (花花) | 推特 KOL 推文 | | `twitter.1401718840535379970` | @hellosuoha (梭教授说) | 推特 KOL 推文 | | `twitter.1453603581932687368` | @laofeiyyds (比特币老肥.btc(敏感肥)) | 推特 KOL 推文 | | `twitter.1852674305517342720` | @aixbt_agent (aixbt) | 推特 KOL 推文 | | `twitter.1279918106111025153` | @assetdash (Dash News) | 推特 KOL 推文 | | `twitter.169686021` | @kanyewest (ye) | 推特 KOL 推文 | | `twitter.1483495485889564674` | @bwenews (方程式新闻 BWEnews 🏎️) | 推特 KOL 推文 | | `twitter.1052454006537314306` | @BNBCHAIN (BNB Chain) | 推特 KOL 推文 | | `twitter.1451036242431262720` | @binancezh (币安Binance华语) | 推特 KOL 推文 | | `twitter.1940360837547565056` | @aleabitoreddit (Serenity) | 推特 KOL 推文 | 想一次看清所有主题的权限:带上你的 Key 调用 [GET /v1/topics](https://tokenearly.com/developers/rest/topics),每个主题都有 `accessible` 字段。 ## 断线补拉 分两步:先用 `after=<最后的事件 id>` 一页页拉新事件到 `has_more = false`;再用 `updated_after=<断线时间>` 拉断线期间产生了新修订版的旧事件(`after` 只按事件 ID 往后找,拿不到旧事件的更新)。然后连回实时流。 ```python import os, time, requests KEY = os.environ["TOKENEARLY_API_KEY"] API = "https://api.tokenearly.com/v1/events" TOPICS = "announcement.*,news.*,signal.*,twitter.*" H = {"Authorization": f"Bearer {KEY}"} def get(params): while True: r = requests.get(API, 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"))) # whole seconds continue r.raise_for_status() time.sleep(int(r.headers.get("X-RateLimit-Reset", "3"))) # respect the per-key interval return r.json() cursor = load_last_event_id() # the last event id you stored (None on the first run) offline_since = load_last_seen_time() # Unix seconds when you last had a live connection (0 on the first run) # First run: nothing to catch up. Just connect to the stream and start storing ids and times. if cursor and offline_since: # 1) new events after the cursor (oldest first, `cursor_param` is "after") while True: page = get({"after": cursor}) for ev in page["events"]: handle(ev) cursor = ev["id"] if not page["has_more"]: break # 2) older events that got a new revision while you were away params = {"updated_after": offline_since} while True: page = get(params) for ev in page["events"]: handle(ev) # same (id, revision) dedupe as for live events if not page["has_more"]: break # always pass next_cursor under the name the response gives in `cursor_param` params = {"updated_after": offline_since, page["cursor_param"]: page["next_cursor"]} save_last_event_id(cursor) ``` --- # 获取单个事件 按 ID 取一个事件的最新修订版。 > Source: https://tokenearly.com/developers/rest/get-event · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/events/{id}` 总是返回该事件当前的最新修订版。事件不在你的主题范围内时返回 404(不区分“不存在”和“无权限”)。 **需要 API Key** ## 参数 | 参数 | 位置 | 类型 | 必填 | 说明 | |---|---|---|---|---| | `id` | path | string | ✓ | 事件 ID(列表接口返回的 id)。 | ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/events/6b0ff643d0e4e92d84810499" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/events/6b0ff643d0e4e92d84810499", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/events/6b0ff643d0e4e92d84810499", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/events/6b0ff643d0e4e92d84810499", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "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": [] } } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `not_found` | 404 | 你的主题范围内没有这个事件(GET /v1/events/{id}),或请求的路径不存在(例如拼错了接口地址)。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | --- # 当前 Key 信息 查看 Key 实际可读的主题、限额与 IP 白名单。 > Source: https://tokenearly.com/developers/rest/me · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/me` `topics` 是最终生效的主题:Key 设定的范围与套餐开放来源的交集。接入前先调一次,确认范围符合预期。 **需要 API Key** ## 参数 没有参数。 ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/me" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/me", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/me", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/me", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "key": { "id": "key_3f9c2a71d0b84e6c5a12", "name": "prod-bot", "prefix": "te_live_Ab12", "topics": [ "*" ], "allowed_ips": [ "203.0.113.5" ], "kind": "standard", "status": "active", "created_at": 1794100000, "last_used_at": 1794200000, "expires_at": null }, "limits": { "api_keys": 1, "streams_per_key": 1, "rest_interval_seconds": 3, "api_history_days": 30 }, "topics": [ "announcement.binance", "announcement.okx", "announcement.mexc" ], "trial": false, "expires_at": null, "access_expires_at": 1796800000 } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | --- # 变更通知 限额调整、Key 变更与接口更新的记录。 > Source: https://tokenearly.com/developers/rest/notices · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/notices` 返回与这把 Key 有关的通知:全体接入方的公告、你的账号的调整、这把 Key 自己的变更,按时间倒序。全体与账号级的通知不按 Key 的创建时间过滤:新建的 Key 也能看到它创建之前发布的这些通知;Key 级通知从这把 Key 创建后才会有。实时流在线时同样的通知会以 `op = "notice"` 立即推送;离线后用 `since` 补拉。 **需要 API Key** ## 参数 | 参数 | 位置 | 类型 | 必填 | 说明 | |---|---|---|---|---| | `since` | query | integer | | 只返回这个时间(Unix 秒)之后的通知;0 = 全部。 | | `limit` | query | integer | | 最多返回条数,1–200,默认 50。 | ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/notices?limit=10" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/notices?limit=10", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/notices?limit=10", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/notices?limit=10", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "notices": [ { "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 } ] } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `invalid_parameter` | 400 | 参数类型或取值不合法(例如 limit 超出范围)。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | ## 通知类型 | kind | scope | 含义 | |---|---|---| | `defaults_changed` | `global` | 默认限额调整(带旧值 → 新值) | | `account_limits_changed` | `user` | 你的账号限额调整 | | `key_limits_changed` | `key` | 某把 Key 的限额调整 | | `ip_allowlist_changed` | `key` | 某把 Key 的 IP 白名单修改(data.before / data.after) | | `key_reset` | `key` | 某把 Key 被重置(data.old_prefix / data.prefix 为新旧前缀;发给新 Key,旧 Key 的连接已断开) | | `key_revoked` | `key` | 某把 Key 被吊销 | | `access_expiring` | `user` | 含 API 的会员即将到期(7 / 3 / 1 天前各一次,data.expires_at 为到期时间) | | `access_expired` | `user` | 含 API 的会员已到期,Key 将以 403 plan_required / 4003 被拒,续费后原 Key 自动恢复 | | `api_update` | `global` | 接口更新公告 | - `scope`:`global` = 全体接入方,`user` = 你的账号,`key` = 某把 Key(看 `key_id`)。 - `data.changes` 是 `{项: [旧值, 新值]}`,`null` 表示「默认值」。 - `since` 是开区间(只返回严格晚于这个时间的通知);每次最多 200 条,没有分页游标——把最后一条的 `created_at` 作为下一次的 `since` 即可。 --- # 我的推送 和你的 Bark、企业微信等渠道收到的同一份推送(按你的网页设置过滤)。 > Source: https://tokenearly.com/developers/rest/alerts · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/alerts` 我的推送:经过你在网页上设置的来源开关、关键词、通知语言(原文先推、译文补推)与会员延迟之后,真正推送给你的那一份,和 Bark、企业微信收到的完全相同。与主题事件(`GET /v1/events`)是两种不同的数据,见[我的推送](https://tokenearly.com/developers/my-alerts)。需要先在网页「全局通知管理 → 通知渠道」打开「开发者 API」开关,否则不会产生新的我的推送;响应里的 `channel_enabled` 表示当前开关状态。默认最新的在前,用 `before` 翻页;断线后用 `after=<最后一条通知 id>` 按时间正序补拉。保留最近 7 天。 **需要 API Key** ## 参数 | 参数 | 位置 | 类型 | 必填 | 说明 | |---|---|---|---|---| | `after` | query | string | | 只返回这条推送之后的,按时间正序(补拉用)。 | | `before` | query | string | | 只返回这条推送之前的,按时间倒序(翻页用)。 | | `limit` | query | integer | | 最多返回条数,1–200,默认 50。 | ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/alerts?limit=5" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY" ``` **Python** ```python import os, requests resp = requests.get( "https://api.tokenearly.com/v1/alerts?limit=5", headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"}, timeout=10, ) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/alerts?limit=5", { headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }, }); const body = await resp.json(); if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`); console.log(body); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" "os" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/alerts?limit=5", nil) req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "alerts": [ { "id": "6af57203e1b0c95f3a7d2e47", "category": "announcement", "source": { "id": "binance", "name": "Binance" }, "followup": true, "lang": "zh", "label": "translation", "title": "【币安(BINANCE)】", "text": "【译文】\n币安将上线 Fooken (FOO) 并添加种子标签\n— — — — — — — — — —\nhttps://www.binance.com/zh-CN/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)", "url": "https://www.binance.com/zh-CN/support/announcement/detail/abc123", "titles": { "en": "Binance Will List Fooken (FOO) with Seed Tag Applied", "zh": "币安将上线 Fooken (FOO) 并添加种子标签", "ko": "바이낸스, 시드 태그가 적용된 Fooken(FOO) 상장" }, "ref": { "type": "announcement", "topic": "announcement.binance", "event_id": "6af57200e1b0c95f3a7d2e40" }, "created_at": 1794470403 }, { "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 } ], "has_more": true, "next_cursor": "6af57201e1b0c95f3a7d2e41", "cursor_param": "before", "channel_enabled": true } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `invalid_cursor` | 400 | after / before 不是合法的 ID(查事件时是事件 ID,查我的推送时是推送 ID),两者同时出现,或(仅查事件)updated_after 与 before 同时使用。 | | `invalid_parameter` | 400 | 参数类型或取值不合法(例如 limit 超出范围)。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | --- # 主题清单 全部可订阅的主题;带 Key 时标注是否可读。 > Source: https://tokenearly.com/developers/rest/topics · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/topics` 无需 Key,不计入限频。新接入的交易所、新闻源或信号源会自动出现在这里;推特主题是我们精选的 KOL 账号,名单会增减,以这里为准。带上 Key 时,每个主题多一个 `accessible` 字段,表示你的 Key 是否有权限读取。 **公开接口,无需 Key(带 Key 时返回更多信息)** ## 参数 没有参数。 ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/topics" ``` **Python** ```python import requests resp = requests.get("https://api.tokenearly.com/v1/topics", timeout=10) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/topics"); console.log(await resp.json()); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/topics", nil) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "spec_version": "1.0", "topics": [ { "id": "announcement.binance", "type": "announcement", "source_id": "binance", "names": { "zh": "币安", "en": "Binance", "ko": "바이낸스" }, "accessible": true }, { "id": "announcement.okx", "type": "announcement", "source_id": "okx", "names": { "zh": "欧易", "en": "OKX", "ko": "OKX" }, "accessible": false }, { "id": "announcement.mexc", "type": "announcement", "source_id": "mexc", "names": { "zh": "抹茶", "en": "MEXC", "ko": "MEXC" }, "accessible": false } ] } ``` ## 错误 | 错误码 | HTTP | 说明 | |---|---|---| | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | --- # 事件 JSON Schema 事件信封与各类 data 的 JSON Schema(draft 2020-12)。 > Source: https://tokenearly.com/developers/rest/schema · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/schema` 无需 Key,不计入限频。可直接用于校验收到的事件或生成类型定义。 **公开接口,无需 Key** ## 参数 没有参数。 ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/schema" ``` **Python** ```python import requests resp = requests.get("https://api.tokenearly.com/v1/schema", timeout=10) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/schema"); console.log(await resp.json()); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/schema", nil) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "spec_version": "1.0", "event": { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://api.tokenearly.com/v1/schema/event", "title": "Tokenearly event", "allOf": [ "…" ], "$defs": { "announcement": "…", "news": "…", "signal": "…", "twitter": "…" } }, "envelope": { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Tokenearly event envelope", "type": "object", "required": [ "spec_version", "id", "revision", "action", "topic", "type", "source", "published_at", "detected_at_ms", "data" ], "properties": { "id": { "type": "string", "description": "Stable event id (24 hex characters) shared by every revision; never changes. Ids increase with the time the event was first stored and compare correctly as strings. Also the pagination and resume cursor." }, "…": "…" } }, "data": { "announcement": { "title": "announcement data", "type": "object", "properties": { "…": "…" } }, "news": { "title": "news data", "type": "object", "properties": { "…": "…" } }, "signal": { "title": "signal data", "type": "object", "properties": { "…": "…" } }, "twitter": { "title": "twitter data", "type": "object", "properties": { "…": "…" } } } } ``` --- # 健康检查 服务是否在线。 > Source: https://tokenearly.com/developers/rest/health · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/health` 无需 Key,不计入限流。适合放进你的监控。 **公开接口,无需 Key** ## 参数 没有参数。 ## 请求示例 **cURL** ```bash curl "https://api.tokenearly.com/v1/health" ``` **Python** ```python import requests resp = requests.get("https://api.tokenearly.com/v1/health", timeout=10) resp.raise_for_status() print(resp.json()) ``` **Node.js** ```javascript // Node 18+ (built-in fetch) async function main() { const resp = await fetch("https://api.tokenearly.com/v1/health"); console.log(await resp.json()); } main().catch((err) => { console.error(err); process.exit(1); }); ``` **Go** ```go package main import ( "fmt" "io" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/health", nil) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(resp.Status, string(body)) } ``` ## 示例响应 ```json { "status": "ok", "spec_version": "1.0" } ``` --- # 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= ``` ### 订阅什么 `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 `;浏览器里用 `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": "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):翻译补齐后再推一次** ```json { "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)** ```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": "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" 追加订阅主题(同样支持通配)。 ```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= 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=, 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"]) } } } ``` --- # AI agent 接入:Markdown 文档、llms.txt、OpenAPI 与 MCP 文档与接口都为 AI 准备好了:每页可复制成 Markdown,规范机器可读,AI agent 可以通过 MCP 直接查询事件。 > Source: https://tokenearly.com/developers/ai · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## MCP 是什么 MCP(Model Context Protocol)是 AI 客户端调用外部工具的开放协议。它也是一个接口,但调用方是 AI:Claude、Cursor 等客户端连上 MCP 服务器后,会自动拿到工具清单和参数说明,在对话里按需查询,不需要你写请求代码。 | | REST | MCP | WebSocket | |---|---|---|---| | 谁来调用 | 你写的程序 | AI 客户端(Claude、Cursor…) | 你写的程序 | | 能做什么 | 查询历史 | 查询历史(同一份数据) | 实时推送 | | 鉴权 | 同一把 API Key | 同一把 API Key | 同一把 API Key | | 限制 | 每 3 秒 1 次 | 与 REST 共用 | 每把 Key 同时 1 条连接 | MCP 的每次工具调用(`get_events`、`get_event`、`get_alerts`、`whoami`)与 REST 请求共用同一把 Key 的限频,合计每 3 秒 1 次;超出时工具返回 `rate_limited` 错误,AI 会按提示稍后重试。`list_topics` 与 `get_schema` 不计入。 ## MCP 服务器 地址 `https://api.tokenearly.com/v1/mcp`(Streamable HTTP)。用请求头 `Authorization: Bearer ` 鉴权,试用 Key 也可以用。所有工具都是只读的。 **Claude Code** ```bash claude mcp add --transport http tokenearly https://api.tokenearly.com/v1/mcp \ --header "Authorization: Bearer YOUR_API_KEY" ``` **Cursor** ```json { "mcpServers": { "tokenearly": { "url": "https://api.tokenearly.com/v1/mcp", "headers": { "Authorization": "Bearer YOUR_API_KEY" } } } } ``` **Claude Desktop** ```json { "mcpServers": { "tokenearly": { "command": "npx", "args": [ "-y", "mcp-remote", "https://api.tokenearly.com/v1/mcp", "--header", "Authorization:${TOKENEARLY_AUTH}" ], "env": { "TOKENEARLY_AUTH": "Bearer YOUR_API_KEY" } } } } ``` **cURL** ```bash curl -s https://api.tokenearly.com/v1/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_events","arguments":{"topics":"announcement.*","limit":3}}}' ``` | 工具 | 作用 | |---|---| | `list_topics` | 列出全部可订阅的主题(交易所公告、新闻、信号、精选推特 KOL 账号),每个主题含 `id`、`type`、`source_id`、`names`;带 Key 时多一个 `accessible`,表示这把 Key 能否读取。与 REST `GET /v1/topics` 相同,不计入限频。 | | `get_events` | 查询结构化事件(交易所公告、新闻、信号、精选推特 KOL 的推文),默认最新的在前。参数与 REST `GET /v1/events` 相同,只有 `limit` 的范围不同。与 REST 共用这把 Key 的限频。 | | `get_event` | 按 ID 取一个事件的最新修订版,与 REST `GET /v1/events/{id}` 相同。计入限频。 | | `get_alerts` | 查询这个账号的我的推送:按你的来源、关键词、通知语言与延迟设置真正推送给你的那一份,默认最新的在前。与 get_events(主题下的全部事件)不同。参数与 REST `GET /v1/alerts` 相同,只有 `limit` 的范围不同。需要在网页打开「开发者 API」开关。计入限频。 | | `get_schema` | 事件信封与各类 data 的 JSON Schema,与 REST `GET /v1/schema` 相同。不需要 Key,不计入限频。 | | `whoami` | 当前 Key 实际生效的主题、限额、IP 白名单与到期时间,与 REST `GET /v1/me` 相同。计入限频。 | ## 工具参数 参数严格按工具定义校验,与 REST 一样:传了未定义的参数、缺少必填参数、类型不对或数值超出范围,都会直接返回 JSON-RPC 错误 `-32602`(Invalid params),消息里写明原因,不会执行查询,也不计入限频。`get_events` 的参数与 REST `GET /v1/events` 相同,只有 `limit` 不同:MCP 是 1–50,默认 10。 ### `list_topics` 没有参数。 ### `get_events` | 参数 | 类型 | 必填 | 默认值 | 范围 | 说明 | |---|---|---|---|---|---| | `topics` | string | | | | 逗号分隔,可以任意组合(例如 `announcement.binance,news.*`),每一项是主题或通配:`announcement.binance`、`announcement.*`、`news.*`、`signal.*`、`twitter.*`、`*`。省略 = Key 可用的全部主题。 | | `limit` | integer | | `10` | 1–50 | 返回条数,1–50,默认 10(REST 是 1–200)。超出范围或不是整数时返回参数错误(-32602)。 | | `after` | string | | | | 返回比该事件 ID 更新的事件,按时间正序。用于断线后补拉。 | | `before` | string | | | | 返回比该事件 ID 更早的事件,按时间倒序。用于向前翻页。 | | `listings_only` | boolean | | `false` | | 设为 true 时只返回判定为上新的交易所公告(`data.listing.is_listing = true`),其他类型的主题一律不返回;可与 `after` / `before` / `updated_after` 一起用。因为是按判定结果筛选,一页可能少于 `limit` 条而 `has_more` 仍为 true:继续用 `next_cursor` 翻页,直到 `has_more = false`。 | | `updated_after` | integer | | | ≥ 0 | 返回在这个时间(Unix 秒)之后产生了新修订版的事件(事件本身可以更早),按事件 ID 正序;用来补齐断线期间旧事件的更新。翻页时 updated_after 保持不变,把上一页的 next_cursor 作为 after 传入。不能与 before 同时用。不传或传 0 表示不使用这个参数(此时按普通列表返回,最新在前)。 | ### `get_event` | 参数 | 类型 | 必填 | 默认值 | 范围 | 说明 | |---|---|---|---|---|---| | `id` | string | ✓ | | | 事件 ID(列表接口返回的 id)。 | ### `get_alerts` | 参数 | 类型 | 必填 | 默认值 | 范围 | 说明 | |---|---|---|---|---|---| | `limit` | integer | | `10` | 1–50 | 返回条数,1–50,默认 10;超出范围返回参数错误。 | | `after` | string | | | | 只返回这条推送之后的,按时间正序。 | | `before` | string | | | | 只返回这条推送之前的,按时间倒序。 | ### `get_schema` 没有参数。 ### `whoami` 没有参数。 ## 给 AI 读的文档 - 每一页右上角都有「复制 Markdown」,也可以直接在 URL 末尾加 `.md` 取得纯文本版本。 - [llms.txt](https://tokenearly.com/developers/llms.txt):文档目录,适合让 AI 先浏览再按需读取。 - [llms-full.txt](https://tokenearly.com/developers/llms-full.txt):全部文档合成一个文件,一次读完。 ## 机器可读文件:llms.txt、OpenAPI、AsyncAPI 文档左下角的几个链接就是这些文件。它们不是给人读的页面,而是给程序和 AI 用的:导入工具后自动生成请求、客户端代码或让 AI 理解接口。 | 文件 | 用途 | |---|---| | [llms.txt](https://tokenearly.com/developers/llms.txt) | 文档目录(Markdown 链接清单),AI 先读它再按需打开各页 | | [openapi.json](https://api.tokenearly.com/v1/openapi.json) | OpenAPI 3.1:导入 Postman、生成客户端、配置 GPT Actions | | [asyncapi.json](https://api.tokenearly.com/v1/asyncapi.json) | AsyncAPI 3.0:实时流的消息定义 | | [schema](https://api.tokenearly.com/v1/schema) | JSON Schema:校验事件、生成类型 | ## 提示词模板 把下面这段交给 AI 编程助手,它会先读文档再写代码: ``` 你是我的编程助手。请先阅读 Tokenearly 开发者 API 文档:https://tokenearly.com/developers/llms-full.txt 然后用 Python 写一个服务:通过 WebSocket 订阅 announcement.*,只处理 data.listing.is_listing 为 true 的事件,按 (id, revision) 去重,断线后带 after 续传,并把标题转发到我的 Telegram 群。先用我在控制台申请的试用 Key 测试。 ``` --- # 错误码与处理建议 REST 错误统一返回 JSON 对象 `error`,用 `code` 判断类型,不要依赖 `message` 文案。 > Source: https://tokenearly.com/developers/errors · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 格式 ```json { "error": { "code": "invalid_api_key", "message": "This API key does not exist or has been revoked.", "docs": "https://tokenearly.com/en/developers/errors" } } ``` 所有 REST 错误都是这个格式,包括路径不存在(404 `not_found`)、HTTP 方法不对(405 `method_not_allowed`)与服务端错误(5xx `internal_error`)。MCP 的响应保持 JSON-RPC 格式:协议层的问题(未知工具、参数不合规)是 JSON-RPC `error`,接口层的错误(Key、权限、限频等)是工具结果里的 `isError: true`,内容同样是 `{"error": {"code", "message"}}`。 ## HTTP 错误 | code | HTTP | 含义与处理 | |---|---|---| | `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer 。 | | `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `invalid_api_key` | 401 | Key 不存在,或已被重置 / 吊销。 | | `plan_required` | 403 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `invalid_cursor` | 400 | after / before 不是合法的 ID(查事件时是事件 ID,查我的推送时是推送 ID),两者同时出现,或(仅查事件)updated_after 与 before 同时使用。 | | `invalid_parameter` | 400 | 参数类型或取值不合法(例如 limit 超出范围)。 | | `not_found` | 404 | 你的主题范围内没有这个事件(GET /v1/events/{id}),或请求的路径不存在(例如拼错了接口地址)。 | | `method_not_allowed` | 405 | 路径存在,但不支持这个 HTTP 方法(例如对 /v1/events 发 POST)。REST 接口都是 GET,只有 MCP 用 POST;响应头 Allow 列出支持的方法。 | | `rate_limited` | 429 | 超过这把 Key 的请求频率(REST 与 MCP 合计,间隔见 `/v1/me` 的 `limits.rest_interval_seconds`);按 Retry-After 头等待后重试。 | | `internal_error` | 500 | 服务端出错(5xx,格式同上)。用指数退避重试(1、2、4… 秒,设上限)。服务重启的短暂时间里也可能收到不带 JSON 正文的 502 / 503 / 504,按同样方式重试。 | ## 实时流错误 实时流先发一条 `op = "error"` 的消息,再以对应关闭码断开;只有 `invalid_message`(客户端消息不合规)不断开: | code | 关闭码 | 含义与处理 | |---|---|---| | `missing_api_key` | 4001 | 没有带 Key。用 Authorization: Bearer 。 | | `key_expired` | 4001 | 试用 Key 已到期。重新申请试用 Key,或开通后创建正式 Key。 | | `invalid_api_key` | 4001 | Key 不存在,或已被重置 / 吊销。 | | `plan_required` | 4003 | 当前套餐不含开发者 API,或不含该项能力。 | | `ip_not_allowed` | 4003 | 这把 Key 设置了 IP 白名单,请求来源 IP 不在其中。 | | `invalid_cursor` | 4400 | 连接参数 after 不是合法的事件 ID;以 4400 关闭,改正后再连。 | | `too_many_connections` | 4029 | 这把 Key 的实时连接名额已满(见 `/v1/me` 的 `limits.streams_per_key`),新连接被拒绝。先关闭旧连接,或给另一台机器用另一把 Key。 | | `invalid_message` | 不断开 | WebSocket 客户端消息不合规:不是 JSON 对象、缺少字符串 op、op 未知,或 topics 为空 / 不是字符串列表。连接保持不断,改正后重发即可。 | | `slow_consumer` | 4008 | 客户端处理太慢、积压过多;带 after 重连即可续上。 | ## 什么时候重试 - `429`:按 `Retry-After` 等待后重试。 - `5xx` 与网络错误:指数退避重试(1、2、4… 秒,设上限)。 - `401` / `403` / `400`:不要重试,先修正 Key、套餐或参数。