# 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=<new last_id>
        await asyncio.sleep(delay)
        delay = min(delay * 2, 60)          # exponential backoff

asyncio.run(main())
```

**Node.js**

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

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

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

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

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

**Go**

```go
package main

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

	"github.com/coder/websocket"
)

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

## 基础信息

| 项目 | 值 |
|---|---|
| REST 地址 | `https://api.tokenearly.com/v1` |
| 实时流地址 | `wss://api.tokenearly.com/v1/stream` |
| 鉴权 | `Authorization: Bearer <API Key>` |
| 数据格式 | 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。
