# Tokenearly Developer API

Two ways in: WebSocket pushes each exchange announcement, news item, signal or post from a curated X (Twitter) KOL to you as soon as we detect it, and REST lets you query history. Events are structured: zh/en/ko titles, listing verdict and tickers for announcements, summaries for news, post text for X, and the original link, each with a stable id.

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

- [WebSocket push](https://tokenearly.com/en/developers/websocket): We push each new announcement to you as soon as we detect it; resume by event id after a disconnect.
- [REST history](https://tokenearly.com/en/developers/rest/list-events): Query past announcements, news and signals by topic, with cursor pagination.
- [One event format](https://tokenearly.com/en/developers/events): A fixed envelope plus a JSON Schema per message type, with zh/en/ko titles.
- [Built for AI agents](https://tokenearly.com/en/developers/ai): Copy any page as Markdown; OpenAPI, llms.txt and an MCP server.

## Quickstart

### 1. Get a key

Once your plan includes the Developer API, create a key in the [dashboard](https://tokenearly.com/dashboard?tab=developer-api); it is shown once. Not subscribed yet? Apply for a trial key there: valid for 12 hours, up to 6 times every 30 days.

```bash
export TOKENEARLY_API_KEY=te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

### 2. Make your first request

Fetch the three latest events across all exchange announcements plus Odaily news (join several topics with commas). Paste your key and press Send to call the real API from your browser.

**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. Connect to the stream

Connect with your own key and new announcements are pushed as they appear. Keep the last event id and pass it as `after` when reconnecting so nothing is missed.

**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"])
		}
	}
}
```

## Basics

| Item | Value |
|---|---|
| REST base URL | `https://api.tokenearly.com/v1` |
| Stream URL | `wss://api.tokenearly.com/v1/stream` |
| Authentication | `Authorization: Bearer <API key>` |
| Format | JSON, UTF-8; times are Unix timestamps |
| Spec version | `1.0` |
| Machine-readable specs | [OpenAPI](https://api.tokenearly.com/v1/openapi.json) · [AsyncAPI](https://api.tokenearly.com/v1/asyncapi.json) · [JSON Schema](https://api.tokenearly.com/v1/schema) |
| Trial key | From the dashboard, valid 12 hours |

## How to connect

| Interface | What it is for | Limit |
|---|---|---|
| **WebSocket (wss)** | Real-time push: each new announcement, news item or signal is sent to you as soon as we detect it | Up to 1 at a time per key; extra ones are refused |
| **REST** | Query past announcements, news and signals; catch up after a disconnect | 1 request every 3 seconds per key |
| **MCP** | Query entry point for AI agents; same data as REST | Shares the REST limit |

Each account can create 1 API key(s); every key has its own connection allowance and rate limit and can be bound to an IP allowlist. Use WebSocket for real-time data instead of polling REST. These are defaults; `GET /v1/me` shows what applies to your key.

## What you can subscribe to

**Exchange announcements** (`announcement.*`, with listing verdict and token tickers), **news** (`news.*`, title, summary and link), **signals** (`signal.*`) and **X (Twitter) KOL posts** (`twitter.*`: original posts, quotes, replies and retweets from a curated list of KOL accounts). Each source is a topic; newly added exchanges, news sources and signal sources show up in the [topic list](https://tokenearly.com/en/developers/topics) automatically, and the list of X accounts changes over time, so the topic list is the reference for it too.

## FAQ

**Can I try it before paying?**

Yes. Sign in with a verified email and apply for a trial key under [Dashboard → Developer API](https://tokenearly.com/dashboard?tab=developer-api): valid for 12 hours, up to 6 times per account every 30 days. Endpoints, real-time push and data format are exactly the same as a regular key; trial keys are for development and testing only.

**Why do I get the same announcement twice?**

It is sent with revision=1 when first stored, then again with the same id and a higher revision (action=updated) once titles in all three languages or the original link are filled in. Posts from X work the same way: a shortened first version can be followed by the complete one under the same id. Keep the highest revision per id.

**How is MCP different from REST?**

Same data and permissions, different caller: REST is for programs you write; MCP (Model Context Protocol) is for AI clients such as Claude and Cursor, which discover the tools and their parameters on their own. Both use the same key and share one limit (1 call every 3 seconds); both are query-only, and real-time push is WebSocket only.

**Can an AI agent call it directly?**

Yes. The MCP server is at `https://api.tokenearly.com/v1/mcp`; clients such as Claude and Cursor only need the URL and a key. You can also copy any docs page as Markdown and hand it to an AI.
