Tokenearly 개발자 API
두 가지 방식: WebSocket은 거래소 공지·뉴스·시그널·선정된 X(트위터) KOL 게시물을 감지하는 즉시 푸시하고, REST로는 기록을 조회합니다. 이벤트는 구조화되어 있습니다: 중·영·한 제목, 상장 판정, 토큰 티커, X 게시물 원문, 원문 링크, 그리고 고정 ID.
빠른 시작
- 키 받기
개발자 API가 포함된 플랜이면 대시보드에서 키를 만드세요(한 번만 표시). 아직이라면 체험 키를 신청할 수 있습니다: 12시간 유효, 30일마다 최대 6회.
export TOKENEARLY_API_KEY=te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - 첫 요청 보내기
모든 거래소 공지와 Odaily 뉴스를 합쳐 최근 이벤트 3건을 조회합니다(여러 토픽은 쉼표로 연결). 키를 넣고 보내기를 누르면 브라우저에서 실제 API를 호출합니다.
curl "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=3" \ -H "Authorization: Bearer $TOKENEARLY_API_KEY"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 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); });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)) }실제 응답 - 스트림 연결
본인 키로 WebSocket에 연결하면 새 공지가 나오는 즉시 푸시됩니다. 마지막 이벤트 ID를 저장해 재연결 시
after로 넘기면 누락이 없습니다.import asyncio, json, os, time import requests # pip install requests import websockets # pip install websockets KEY = os.environ["TOKENEARLY_API_KEY"] H = {"Authorization": f"Bearer {KEY}"} TOPICS = "announcement.*,news.*,signal.*,twitter.*" STREAM = "wss://api.tokenearly.com/v1/stream?topics=" + TOPICS EVENTS = "https://api.tokenearly.com/v1/events" FATAL = {4001, 4003} # bad / expired key, no permission: fix it, do not retry last_id = None # last event id: resume cursor (store it durably in production) live_at = int(time.time()) # last moment the stream was live: `updated_after` for a REST catch-up def handle(ev): global last_id if not last_id or ev["id"] > last_id: # ids grow with time; only move the cursor forward last_id = ev["id"] data = ev["data"] # same envelope for every type; `data` depends on ev["type"] if ev["type"] == "twitter": # X posts: text as published, no titles text = "@" + data["author"]["screen_name"] + ": " + data["text"] else: text = data["titles"].get("en") or next(iter(data["titles"].values()), "") print(ev["type"], ev["topic"], ev["revision"], text) # dedupe on (id, revision) in production def rest_get(params): while True: r = requests.get(EVENTS, params=dict(params, topics=TOPICS, limit=200), headers=H, timeout=10) if r.status_code == 429: time.sleep(int(r.headers.get("Retry-After", "3"))) continue r.raise_for_status() time.sleep(int(r.headers.get("X-RateLimit-Reset", "3"))) # respect the per-key interval return r.json() def catch_up(): """replay_done.truncated: the gap is too big for the stream, so fill it over REST.""" while True: # 1) new events after the cursor, oldest first page = rest_get({"after": last_id}) for ev in page["events"]: handle(ev) if not page["has_more"]: break params = {"updated_after": live_at} # 2) older events that got a new revision while away while True: page = rest_get(params) for ev in page["events"]: handle(ev) if not page["has_more"]: break params = {"updated_after": live_at, page["cursor_param"]: page["next_cursor"]} async def main(): global live_at, last_id delay = 1 while True: url = STREAM + (f"&after={last_id}" if last_id else "") truncated = False try: async with websockets.connect(url, additional_headers=H) as ws: async for raw in ws: msg = json.loads(raw) op = msg["op"] if op == "welcome": delay = 1 elif op == "event": handle(msg["event"]) elif op == "replay_done" and msg["truncated"]: truncated = True # 1) close, 2) catch up over REST, 3) reconnect with the new cursor break elif op == "notice": print("notice:", msg["notice"]["kind"], msg["notice"]["body"].get("en")) elif op == "error": print("server error:", msg["code"], msg["message"]) if op == "ping" or (op == "event" and not msg.get("replay")): live_at = int(time.time()) # live traffic only comes after the replay except websockets.ConnectionClosed as e: if e.rcvd and e.rcvd.code in FATAL: raise SystemExit(f"stopped: close code {e.rcvd.code}") if e.rcvd and e.rcvd.code == 4029: delay = max(delay, 5) # slot not free yet if e.rcvd and e.rcvd.code == 4400: print("stored cursor rejected; reconnecting without it") last_id = None # never retry the same invalid `after` except Exception as e: print("disconnected:", e) if truncated: await asyncio.to_thread(catch_up) # blocking HTTP off the event loop continue # reconnect right away with after=<new last_id> await asyncio.sleep(delay) delay = min(delay * 2, 60) # exponential backoff asyncio.run(main())// Node 18+ (built-in fetch): npm install ws const WebSocket = require("ws"); const TOPICS = "announcement.*,news.*,signal.*,twitter.*"; const EVENTS = "https://api.tokenearly.com/v1/events"; const H = { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` }; const FATAL = new Set([4001, 4003]); // bad / expired key, no permission: fix it, do not retry const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let lastId = null, liveAt = Math.floor(Date.now() / 1000), delay = 1000; function handle(ev) { if (!lastId || ev.id > lastId) lastId = ev.id; // ids grow with time; only move the cursor forward const d = ev.data; // shape depends on ev.type; X posts carry text instead of titles const text = ev.type === "twitter" ? `@${d.author.screen_name}: ${d.text}` : (d.titles.en || Object.values(d.titles)[0]); console.log(ev.type, ev.topic, ev.revision, text); // dedupe on (id, revision) in production } async function restPages(params) { // all pages of one REST query, following `cursor_param` for (;;) { const r = await fetch(`${EVENTS}?${new URLSearchParams({ ...params, topics: TOPICS, limit: "200" })}`, { headers: H }); if (r.status === 429) { await sleep(1000 * Number(r.headers.get("retry-after") || 3)); continue; } if (!r.ok) throw new Error(`HTTP ${r.status}`); const page = await r.json(); page.events.forEach(handle); if (!page.has_more) return; params = { ...params, [page.cursor_param]: page.next_cursor }; await sleep(1000 * Number(r.headers.get("x-ratelimit-reset") || 3)); // respect the per-key interval } } async function catchUp() { // replay_done.truncated: the gap is too big for the stream, so fill it over REST await restPages({ after: lastId }); // 1) new events after the cursor, oldest first await restPages({ updated_after: String(liveAt) }); // 2) older events that got a new revision while away } function connect() { const ws = new WebSocket(`wss://api.tokenearly.com/v1/stream?topics=${TOPICS}` + (lastId ? `&after=${lastId}` : ""), { headers: H }); let truncated = false; ws.on("message", (raw) => { const msg = JSON.parse(raw); if (msg.op === "welcome") delay = 1000; if (msg.op === "event") handle(msg.event); if (msg.op === "replay_done" && msg.truncated) { truncated = true; ws.close(); return; } if (msg.op === "notice") console.log("notice:", msg.notice.kind, msg.notice.body.en); if (msg.op === "error") console.error("server error:", msg.code, msg.message); if (msg.op === "ping" || (msg.op === "event" && !msg.replay)) liveAt = Math.floor(Date.now() / 1000); }); ws.on("close", async (code) => { if (FATAL.has(code)) return console.error("stopped: close code", code); if (truncated) { // 1) closed, 2) catch up over REST, 3) reconnect with the new cursor try { await catchUp(); } catch (e) { console.error("catch-up failed:", e.message); } return connect(); } if (code === 4400) { console.error("stored cursor rejected; reconnecting without it"); lastId = null; } if (code === 4029) delay = Math.max(delay, 5000); setTimeout(connect, delay); delay = Math.min(delay * 2, 60000); }); ws.on("error", (e) => console.error(e.message)); } connect();package main // go get github.com/coder/websocket import ( "context" "encoding/json" "fmt" "net/http" "os" "github.com/coder/websocket" ) func main() { ctx := context.Background() h := http.Header{} h.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY")) c, _, err := websocket.Dial(ctx, "wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*,signal.*,twitter.*", &websocket.DialOptions{HTTPHeader: h}) if err != nil { panic(err) } defer c.CloseNow() for { _, data, err := c.Read(ctx) if err != nil { // in production: reconnect with after=<last event id>, back off 1,2,4…60 s; stop on close code 4001 / 4003; // on 4400 drop the stored cursor; on replay_done with truncated = true catch up over REST first (see the Python tab) panic(err) } var msg map[string]any json.Unmarshal(data, &msg) if msg["op"] == "event" { ev := msg["event"].(map[string]any) fmt.Println(ev["type"], ev["topic"], ev["revision"], ev["id"]) } } }
기본 정보
| 항목 | 값 |
|---|---|
| REST 주소 | https://api.tokenearly.com/v1 |
| 스트림 주소 | wss://api.tokenearly.com/v1/stream |
| 인증 | Authorization: Bearer <API 키> |
| 형식 | JSON, UTF-8, 시간은 Unix 타임스탬프 |
| 규격 버전 | 1.0 |
| 기계 판독 규격 | OpenAPI · AsyncAPI · JSON Schema |
| 체험 키 | 대시보드에서 신청, 12시간 유효 |
연동 방식
| 방식 | 용도 | 제한 |
|---|---|---|
| WebSocket (wss) | 실시간 푸시: 새 공지나 시그널을 감지하는 즉시 전송 | 키당 동시 연결 1개, 초과 연결은 거부 |
| REST | 과거 공지·뉴스·시그널 조회, 끊긴 뒤 따라잡기 | 키당 3초에 1회 |
| MCP | AI 에이전트용 조회 창구, 데이터는 REST와 동일 | REST와 같은 제한 공유 |
계정당 API 키를 1개 만들 수 있고, 키마다 연결 수와 속도 제한이 따로 있으며 IP 허용 목록을 걸 수 있습니다. 실시간 데이터는 REST 폴링 대신 WebSocket을 쓰세요. 기본값이며 실제 적용 한도는 GET /v1/me에서 확인하세요.
구독 가능한 내용
거래소 공지(announcement.*, 상장 판정과 토큰 티커 포함), 뉴스(news.*, 제목·요약·원문 링크), 시그널(signal.*), X(트위터) KOL 게시물(twitter.*, 저희가 선정한 KOL 계정의 원본·인용·답글·리트윗). 소스마다 하나의 토픽이며, 새로 추가된 거래소·뉴스 소스·시그널 소스는 토픽 목록에 자동으로 나타납니다. X 계정 목록도 수시로 바뀌니 토픽 목록을 기준으로 하세요.
FAQ
결제 전에 시험해 볼 수 있나요?
네. 이메일 인증된 계정으로 로그인해 대시보드 → 개발자 API에서 체험 키를 신청하세요: 12시간 유효, 계정당 30일마다 최대 6회. 엔드포인트·실시간 푸시·데이터 형식은 정식 키와 같으며, 체험 키는 개발·테스트 용도입니다.
같은 공지를 두 번 받는 이유는?
처음 저장될 때 revision=1로 보내고, 중·영·한 제목이나 원문 링크가 보완되면 같은 id에 더 큰 revision(action=updated)으로 다시 보냅니다. X 게시물도 같아서 축약본 뒤에 완전한 버전이 같은 id로 다시 올 수 있습니다. id별로 revision이 가장 큰 것만 남기면 됩니다.
MCP와 REST는 무엇이 다른가요?
데이터와 권한은 같고 호출 주체만 다릅니다. REST는 직접 작성한 프로그램이, MCP(Model Context Protocol)는 Claude·Cursor 같은 AI 클라이언트가 호출하며 AI가 도구와 파라미터를 스스로 파악합니다. 둘은 같은 키와 같은 제한(3초에 1회)을 공유하고 조회만 가능하며, 실시간 푸시는 WebSocket뿐입니다.
AI 에이전트가 직접 호출할 수 있나요?
네. MCP 서버 주소는 https://api.tokenearly.com/v1/mcp이며 Claude, Cursor 같은 클라이언트에 주소와 키만 넣으면 됩니다. 문서 페이지를 Markdown으로 복사해 AI에 넘길 수도 있습니다.