# Tokenearly 개발자 API > 두 가지 방식: WebSocket은 거래소 공지·뉴스·시그널·선정된 X(트위터) KOL 게시물을 감지하는 즉시 푸시하고, REST로는 기록을 조회합니다. 이벤트는 구조화되어 있습니다: 중·영·한 제목, 상장 판정, 토큰 티커, X 게시물 원문, 원문 링크, 그리고 고정 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/ko/developers.md): 두 가지 방식: WebSocket은 거래소 공지·뉴스·시그널·선정된 X(트위터) KOL 게시물을 감지하는 즉시 푸시하고, REST로는 기록을 조회합니다. 이벤트는 구조화되어 있습니다: 중·영·한 제목, 상장 판정, 토큰 티커, X 게시물 원문, 원문 링크, 그리고 고정 ID. - [인증과 API 키](https://tokenearly.com/ko/developers/authentication.md): 모든 요청에 API 키를 보냅니다. 서버 코드에서는 `Authorization: Bearer <키>` 헤더를 쓰고, 헤더를 설정할 수 없는 브라우저 WebSocket에서는 `api_key` 쿼리 파라미터를 씁니다. - [속도 제한과 한도](https://tokenearly.com/ko/developers/limits.md): 기본적으로 계정당 API 키 1개, 키마다 동시 WebSocket 연결 1개, REST·MCP는 3초에 1회입니다. ## 데이터 - [토픽](https://tokenearly.com/ko/developers/topics.md): 토픽은 구독 단위로 <유형>.<소스> 형식입니다. 목록은 플랫폼 전역 레지스트리에서 생성되며 새 소스는 자동으로 나타납니다. - [이벤트 형식](https://tokenearly.com/ko/developers/events.md): 모든 메시지는 이벤트입니다: 고정 봉투, 고정 ID, 증가하는 리비전, 유형별 data. - [내 알림](https://tokenearly.com/ko/developers/my-alerts.md): 토픽별 전체 이벤트와 별도로, **실제로 나에게 보내진** 알림을 그대로 받을 수 있습니다. 웹에서 설정한 Bark·위챗 워크 등 채널이 받는 것과 같으며 소스·키워드·알림 언어로 필터링됩니다. 우리 알림을 직접 만든 봇이나 워크플로에 연결할 때 쓰세요. ## REST API - [이벤트 조회](https://tokenearly.com/ko/developers/rest/list-events.md): 토픽별 과거 이벤트 조회. 커서 페이지네이션과 따라잡기를 지원합니다. - [단일 이벤트 조회](https://tokenearly.com/ko/developers/rest/get-event.md): ID로 이벤트의 최신 리비전을 가져옵니다. - [현재 키 정보](https://tokenearly.com/ko/developers/rest/me.md): 키가 읽을 수 있는 토픽, 한도, IP 허용 목록을 확인합니다. - [변경 알림](https://tokenearly.com/ko/developers/rest/notices.md): 한도 조정, 키 변경, API 업데이트 기록. - [내 알림](https://tokenearly.com/ko/developers/rest/alerts.md): Bark·위챗 워크 등 채널이 받는 것과 같은 푸시(웹 설정으로 필터링). - [토픽 목록](https://tokenearly.com/ko/developers/rest/topics.md): 구독 가능한 모든 토픽. 키를 보내면 읽기 가능 여부를 표시합니다. - [이벤트 JSON Schema](https://tokenearly.com/ko/developers/rest/schema.md): 봉투와 data 유형별 JSON Schema(draft 2020-12). - [상태 확인](https://tokenearly.com/ko/developers/rest/health.md): 서비스 가동 여부. ## 스트리밍 - [WebSocket 실시간 푸시](https://tokenearly.com/ko/developers/websocket.md): 연결 하나를 유지하면 구독 토픽의 새 공지·뉴스·시그널을 감지하는 즉시 푸시합니다. 키당 동시 연결은 1개입니다. ## AI·도구 - [AI 에이전트와 MCP](https://tokenearly.com/ko/developers/ai.md): 문서와 API 모두 AI용으로 준비되어 있습니다. 모든 페이지를 Markdown으로 복사할 수 있고, 규격은 기계 판독 가능하며, 에이전트는 MCP로 이벤트를 직접 조회할 수 있습니다. ## 참고 - [오류 코드](https://tokenearly.com/ko/developers/errors.md): REST 오류는 항상 `error` 객체를 반환합니다. `message` 문구가 아닌 `code`로 분기하세요. ## 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/ko/developers/llms-full.txt) ## Other languages - [中文](https://tokenearly.com/developers/llms.txt) - [English](https://tokenearly.com/en/developers/llms.txt) --- # Tokenearly 개발자 API 두 가지 방식: WebSocket은 거래소 공지·뉴스·시그널·선정된 X(트위터) KOL 게시물을 감지하는 즉시 푸시하고, REST로는 기록을 조회합니다. 이벤트는 구조화되어 있습니다: 중·영·한 제목, 상장 판정, 토큰 티커, X 게시물 원문, 원문 링크, 그리고 고정 ID. > Source: https://tokenearly.com/ko/developers · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json - [WebSocket 실시간 푸시](https://tokenearly.com/ko/developers/websocket): 새 공지를 감지하는 즉시 푸시합니다. 끊겨도 이벤트 ID로 이어 받습니다. - [REST 기록 조회](https://tokenearly.com/ko/developers/rest/list-events): 토픽별 과거 공지·뉴스·시그널 조회, 커서 페이지네이션. - [통일된 이벤트 형식](https://tokenearly.com/ko/developers/events): 고정 봉투 + 메시지 유형별 JSON Schema, 중·영·한 제목. - [AI 에이전트용](https://tokenearly.com/ko/developers/ai): 모든 페이지 Markdown 복사, OpenAPI·llms.txt·MCP 서버. ## 빠른 시작 ### 1. 키 받기 개발자 API가 포함된 플랜이면 [대시보드](https://tokenearly.com/dashboard?tab=developer-api)에서 키를 만드세요(한 번만 표시). 아직이라면 체험 키를 신청할 수 있습니다: 12시간 유효, 30일마다 최대 6회. ```bash export TOKENEARLY_API_KEY=te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ### 2. 첫 요청 보내기 모든 거래소 공지와 Odaily 뉴스를 합쳐 최근 이벤트 3건을 조회합니다(여러 토픽은 쉼표로 연결). 키를 넣고 보내기를 누르면 브라우저에서 실제 API를 호출합니다. **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. 스트림 연결 본인 키로 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) | | 체험 키 | 대시보드에서 신청, 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 계정의 원본·인용·답글·리트윗). 소스마다 하나의 토픽이며, 새로 추가된 거래소·뉴스 소스·시그널 소스는 [토픽 목록](https://tokenearly.com/ko/developers/topics)에 자동으로 나타납니다. X 계정 목록도 수시로 바뀌니 토픽 목록을 기준으로 하세요. ## FAQ **결제 전에 시험해 볼 수 있나요?** 네. 이메일 인증된 계정으로 로그인해 [대시보드 → 개발자 API](https://tokenearly.com/dashboard?tab=developer-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에 넘길 수도 있습니다. --- # 인증과 API 키 모든 요청에 API 키를 보냅니다. 서버 코드에서는 `Authorization: Bearer <키>` 헤더를 쓰고, 헤더를 설정할 수 없는 브라우저 WebSocket에서는 `api_key` 쿼리 파라미터를 씁니다. > Source: https://tokenearly.com/ko/developers/authentication · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 예시 아래 예시는 모두 `GET /v1/me`를 호출합니다. 키가 읽을 수 있는 토픽, 한도, IP 허용 목록을 돌려주므로 키가 제대로 동작하는지 확인하기 좋습니다. **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)); ``` 키가 없거나 잘못되면 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 전용(헤더 설정 불가) | ## 키 만들기 1. 로그인 후 [대시보드 → 개발자 API](https://tokenearly.com/dashboard?tab=developer-api)를 엽니다. 2. API 키 만들기를 눌러 이름을 정하고, 필요하면 IP 허용 목록을 넣습니다(선택). 3. 대화상자의 키를 복사하세요. 한 번만 표시되며 저희는 해시만 저장합니다. 계정당 기본 1개까지 키를 만들 수 있으며, 키를 바꾸려면 재설정을 누르세요. 키는 플랜이 여는 모든 토픽을 읽을 수 있으며, 요청이나 연결 시 `topics` 파라미터로 고릅니다. 실제 토픽은 [GET /v1/me](https://tokenearly.com/ko/developers/rest/me)로 언제든 확인하세요. 키는 계정에 속한 인증 수단입니다. 정식 키로 읽을 수 있는 토픽과 [내 알림](https://tokenearly.com/ko/developers/my-alerts)(스위치, 기록, 커서)은 계정에 남아 키를 바꿔도 그대로입니다. 스트림 구독 토픽은 클라이언트가 연결할 때마다 `topics`로 지정하며 키에 저장되지 않으므로 같은 파라미터로 다시 연결하면 됩니다. IP 허용 목록은 키별 설정입니다. 재설정하면 유지되고, 새로 만든 키에는 다시 입력해야 합니다. ### 키 재설정 키가 유출되었거나 잃어버렸거나 교체할 때는 대시보드에서 해당 키의 재설정을 누르세요(체험 키도 가능). 새 키가 발급되고 기존 키는 즉시 무효가 됩니다. REST와 MCP는 401 `invalid_api_key`를 반환하고, 기존 키로 열린 스트림은 `op = "error"`를 받은 뒤 4001로 닫힙니다. 자동 재연결하지 말고 새 키로 바꿔 연결하세요. 키 ID, 이름, IP 허용 목록, 한도, 만료 시각은 그대로이며, 체험 키를 재설정해도 신청 횟수가 줄거나 유효 기간이 늘지 않습니다. ### 키 유효 기간 정식 키는 자체 만료가 없으며 개발자 API가 포함된 멤버십이 유효한 동안 동작합니다. 멤버십이 만료되면 모든 정식 키가 403 `plan_required`(스트림은 4003)로 거부되고, 갱신하면 같은 키가 바로 다시 동작합니다. 만료 시각은 [GET /v1/me](https://tokenearly.com/ko/developers/rest/me)의 `access_expires_at` 또는 대시보드에서 확인하세요. 만료 7·3·1일 전과 만료 후에 이메일, 알림 채널 푸시, [변경 알림](https://tokenearly.com/ko/developers/rest/notices)(`access_expiring` / `access_expired`)으로 알려 드립니다. 체험 키는 멤버십과 무관하게 자체 `expires_at`(`access_expires_at`과 같음)에 만료되며, 만료 후에는 401 `key_expired`(스트림은 4001)를 받습니다. 갱신할 수 없으니 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. > 키는 비밀번호와 같습니다. 프런트엔드 코드에 넣거나 저장소에 커밋하지 마세요. 유출되면 대시보드에서 재설정하거나 폐기하세요. 기존 키는 즉시 무효가 되고 열린 스트림도 바로 끊깁니다. ## IP 허용 목록(선택) 대시보드에서 서버의 출구 IP를 키에 넣으면 그 주소에서만 키를 쓸 수 있어, 키가 유출돼도 다른 곳에서는 쓸 수 없습니다. 비워 두면 제한이 없습니다. 언제든 수정할 수 있으며 열린 스트림에는 1분 안에 반영됩니다. | 입력 | 의미 | |---|---| | `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의 키가 틀리면 `api_key`로 다시 시도하지 않고 4001 | | 소문자 `bearer`, 키 앞뒤 공백 | 허용 | ## 체험 키 개발자 API가 없는 계정은 대시보드에서 체험 키를 신청해 먼저 코드를 돌려 볼 수 있습니다. | 항목 | 체험 키 | |---|---| | 신청 조건 | 이메일 인증된 정식 계정(게스트 불가) | | 유효 기간 | 12시간, 이후 자동 만료 | | 횟수 | 계정당 30일마다 6회, 동시에 하나만 유효 | | 데이터 | 모든 토픽, 실시간; 기록 7일 | | 속도와 연결 | 정식 키 기본값과 같음: 3초에 1회, 동시 연결 1개 | | 만료 후 | REST는 401 `key_expired`, 실시간 연결은 종료 코드 4001로 닫힘 | > 체험 키는 개발·테스트 전용이며 운영이나 상업적 용도로 쓸 수 없습니다. 실제 연동은 구독 후 정식 키를 만드세요. --- # 속도 제한과 한도 기본적으로 계정당 API 키 1개, 키마다 동시 WebSocket 연결 1개, REST·MCP는 3초에 1회입니다. > Source: https://tokenearly.com/ko/developers/limits · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 한눈에 보기 | 항목 | 제한 | 초과 시 | |---|---|---| | API 키 | 계정당 1개 | 새 키를 만들 수 없음, 기존 키를 먼저 폐기 | | WebSocket 연결 | 키당 동시 1개 | 새 연결이 종료 코드 `4029`로 거부됨 | | REST와 MCP | 키당 3초에 1회(합산) | `429`, `Retry-After`만큼 대기 | | 기록 범위 | 플랜에 따름, `/v1/me`의 `limits.api_history_days` 참고 | 더 오래된 이벤트는 오류 없이 반환되지 않음 | 키가 필요 없는 엔드포인트(`/v1/topics`, `/v1/schema`, `/v1/health`)는 속도 제한에 포함되지 않습니다. > 위 표는 기본값입니다. 계정별·키별로 조정될 수 있으며(예: 특정 키에 더 높은 빈도나 더 많은 연결), 실제 적용 한도는 `GET /v1/me`의 `limits`에서 확인하세요. 한도가 바뀌면(기본값, 계정, 특정 키) 열려 있는 스트림에 이전 값과 새 값이 담긴 `op = "notice"` 메시지가 즉시 전송됩니다. 같은 기록은 [GET /v1/notices](https://tokenearly.com/ko/developers/rest/notices)와 대시보드 변경 기록에서도 볼 수 있습니다. ## REST 속도 제한 같은 키의 두 요청은 최소 3초 간격이어야 합니다. 키가 필요한 엔드포인트의 성공(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`(키 없음·잘못됨·만료), `403`(`ip_not_allowed`, `plan_required`) | 집계 안 됨 | | 파라미터 형식 오류 `400 invalid_parameter`(예: `limit` 범위 초과, 키 확인 전에 거부) | 집계 안 됨 | | 없는 경로(`404`) 또는 잘못된 메서드(`405`) | 집계 안 됨 | | `429`로 거부된 요청 | 집계 안 되며 다음 요청 가능 시각도 늦추지 않음 | | `/v1/topics`(키 유무 무관), `/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 연결 연결 수는 키 단위입니다. 키마다 실시간 스트림 연결을 최대 1개까지 열 수 있으며, 다 차면 새 연결은 `too_many_connections`를 받고 종료 코드 4029로 닫힙니다. 기존 연결을 먼저 닫으세요. 연결이 더 필요하면(예: 서버마다 하나) 키를 더 만들어 서버마다 따로 쓰세요. 정상 종료 없이 끊긴 연결은 하트비트가 끊기면 서버가 자동으로 정리하며 보통 1분을 넘지 않습니다. 처리가 느려 500건 넘게 밀리면 4008로 끊기며 `after`로 다시 연결하면 이어집니다. --- # 토픽: 구독 가능한 소스 토픽은 구독 단위로 <유형>.<소스> 형식입니다. 목록은 플랫폼 전역 레지스트리에서 생성되며 새 소스는 자동으로 나타납니다. > Source: https://tokenearly.com/ko/developers/topics · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 작성법 | 패턴 | 의미 | |---|---| | `announcement.binance` | 정확한 토픽 하나 | | `announcement.*` | 한 유형의 모든 소스 | | `*` | 모든 토픽 | | `announcement.binance,signal.*` | 쉼표로 조합 | 패턴은 요청마다 펼쳐지므로 새 소스가 추가돼도 구독을 바꿀 필요가 없습니다. 토픽 ID는 대소문자를 구분하지 않으며(`Announcement.Binance` = `announcement.binance`) 응답은 항상 소문자입니다. X 토픽은 `twitter.<계정의 X 숫자 ID>`이며 선정된 KOL 계정마다 하나입니다. 계정 이름이 바뀌어도 토픽 ID는 그대로이고, 계정은 수시로 추가·제외됩니다. `twitter.*`로 구독하면 목록 변화를 자동으로 따라갑니다. ## 현재 토픽 | 토픽 ID | 이름 | 유형 | |---|---|---| | `announcement.binance` | 바이낸스 | 거래소 공지 | | `announcement.okx` | OKX | 거래소 공지 | | `announcement.mexc` | MEXC | 거래소 공지 | | `announcement.bitget` | Bitget | 거래소 공지 | | `announcement.gate` | Gate.io | 거래소 공지 | | `announcement.huobi` | 후오비 | 거래소 공지 | | `announcement.bybit` | Bybit | 거래소 공지 | | `announcement.kucoin` | KuCoin | 거래소 공지 | | `announcement.upbit` | 업비트 | 거래소 공지 | | `announcement.bithumb` | 빗썸 | 거래소 공지 | | `news.odaily` | Odaily | 뉴스 | | `news.jinse` | 진세 파이낸스 | 뉴스 | | `news.theblockbeats` | 더블록비츠 | 뉴스 | | `news.foresight` | Foresight News | 뉴스 | | `news.panews` | PANews | 뉴스 | | `news.coinmarketcap` | CoinMarketCap | 뉴스 | | `news.wallstreetcn` | WallStreetCN | 뉴스 | | `news.theblock` | The Block | 뉴스 | | `signal.binance_alpha` | Binance Alpha | 시그널 | | `twitter.44196397` | @elonmusk (Elon Musk) | X(트위터) KOL 게시물 | | `twitter.902926941413453824` | @cz_binance (CZ 🔶 BNB) | X(트위터) KOL 게시물 | | `twitter.574032254` | @coinbase (Coinbase 🛡️) | X(트위터) KOL 게시물 | | `twitter.1422537905885442055` | @CoinbaseAssets (Coinbase Assets 🛡️) | X(트위터) KOL 게시물 | | `twitter.720487892670410753` | @CoinbaseMarkets (Coinbase Markets 🛡️) | X(트위터) KOL 게시물 | | `twitter.877807935493033984` | @binance (Binance) | X(트위터) KOL 게시물 | | `twitter.295218901` | @VitalikButerin (vitalik.eth) | X(트위터) KOL 게시물 | | `twitter.1003840309166366721` | @heyibinance (Yi He) | X(트위터) KOL 게시물 | | `twitter.902839045356744704` | @justinsuntron (H.E. Justin Sun 👨‍🚀 🌞) | X(트위터) KOL 게시물 | | `twitter.900935123968737281` | @hebi555 (何币) | X(트위터) KOL 게시물 | | `twitter.1403881130802225152` | @BTCdayu (大宇) | X(트위터) KOL 게시물 | | `twitter.2985599460` | @star_okx (Star_OKX) | X(트위터) KOL 게시물 | | `twitter.1533037218444476416` | @xincctnnq (币圈女菩萨|Pizza披萨🍕) | X(트위터) KOL 게시물 | | `twitter.25073877` | @realDonaldTrump (Donald J. Trump) | X(트위터) KOL 게시물 | | `twitter.1686901686185721857` | @TrumpDailyPosts (Commentary Trump Daily Posts) | X(트위터) KOL 게시물 | | `twitter.20736511` | @nayibbukele (Nayib Bukele) | X(트위터) KOL 게시물 | | `twitter.1844002277218242560` | @Plasma | X(트위터) KOL 게시물 | | `twitter.2414580907` | @pauliepunt (Paul) | X(트위터) KOL 게시물 | | `twitter.867617849208037377` | @okx (OKX) | X(트위터) KOL 게시물 | | `twitter.1138033434` | @Rewkang (Andrew Kang) | X(트위터) KOL 게시물 | | `twitter.1789908971953799168` | @Aster_DEX (Aster 🥷) | X(트위터) KOL 게시물 | | `twitter.1948234340556763136` | @zakk_okx (Zakk 🟪 OKX AI) | X(트위터) KOL 게시물 | | `twitter.357312062` | @Bitcoin | X(트위터) KOL 게시물 | | `twitter.973261472` | @blknoiz06 (Ansem 🐂🀄️) | X(트위터) KOL 게시물 | | `twitter.132749200` | @OxSunNFT (0xSun ❤️ Memecoin) | X(트위터) KOL 게시물 | | `twitter.844304603336232960` | @MustStopMurad (Murad 💹🧲) | X(트위터) KOL 게시물 | | `twitter.1195728139898376193` | @0xcryptowizard (0xWizard) | X(트위터) KOL 게시물 | | `twitter.992590209752629249` | @notEezzy (Eezzy 🧸) | X(트위터) KOL 게시물 | | `twitter.1800348208461205504` | @xiaomucrypto (新股神白毛股神) | X(트위터) KOL 게시물 | | `twitter.16228398` | @mcuban (Mark Cuban) | X(트위터) KOL 게시물 | | `twitter.1189381231198134272` | @CookerFlips (Cooker.hl \| 版本之子 \| (Theo Arc)) | X(트위터) KOL 게시물 | | `twitter.1279711663264894977` | @DekuKing1 (0x易经(刘彻版)) | X(트위터) KOL 게시물 | | `twitter.725984371946082304` | @XXAntiWar (XX) | X(트위터) KOL 게시물 | | `twitter.1462727797135216641` | @lookonchain (Lookonchain) | X(트위터) KOL 게시물 | | `twitter.1466673394649559040` | @huahuayjy (花花) | X(트위터) KOL 게시물 | | `twitter.1401718840535379970` | @hellosuoha (梭教授说) | X(트위터) KOL 게시물 | | `twitter.1453603581932687368` | @laofeiyyds (比特币老肥.btc(敏感肥)) | X(트위터) KOL 게시물 | | `twitter.1852674305517342720` | @aixbt_agent (aixbt) | X(트위터) KOL 게시물 | | `twitter.1279918106111025153` | @assetdash (Dash News) | X(트위터) KOL 게시물 | | `twitter.169686021` | @kanyewest (ye) | X(트위터) KOL 게시물 | | `twitter.1483495485889564674` | @bwenews (方程式新闻 BWEnews 🏎️) | X(트위터) KOL 게시물 | | `twitter.1052454006537314306` | @BNBCHAIN (BNB Chain) | X(트위터) KOL 게시물 | | `twitter.1451036242431262720` | @binancezh (币安Binance华语) | X(트위터) KOL 게시물 | | `twitter.1940360837547565056` | @aleabitoreddit (Serenity) | X(트위터) KOL 게시물 | 코드에서는 [GET /v1/topics](https://tokenearly.com/ko/developers/rest/topics)로 최신 목록을 가져오세요. --- # 이벤트 형식: 봉투와 메시지 필드 모든 메시지는 이벤트입니다: 고정 봉투, 고정 ID, 증가하는 리비전, 유형별 data. > Source: https://tokenearly.com/ko/developers/events · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 봉투 모든 이벤트는 같은 봉투를 공유하고 `data` 구조는 `type`에 따라 다릅니다. 스트림과 REST는 같은 함수로 이벤트를 만들어 필드가 완전히 같습니다. | 필드 | 타입 | 필수 | 설명 | |---|---|---|---| | `spec_version` | `"1.0"` | ✓ | 이벤트 형식 버전. 같은 메이저 버전 안에서는 필드가 추가만 되고 삭제·변경되지 않습니다. | | `id` | `string` | ✓ | 모든 리비전이 공유하는 고정 이벤트 ID(16진수 24자)로 바뀌지 않습니다. 최초 저장 시각 순으로 증가하며 문자열 비교로 크기를 비교할 수 있습니다. 페이지·이어 받기 커서로도 쓰입니다. | | `revision` | `integer` | ✓ | 1부터 시작해 번역이나 원문 링크가 채워지거나 게시물의 완전한 버전이 도착하면 증가합니다. (id, revision)으로 중복 제거하고 가장 큰 값을 유지하세요. | | `action` | `"created" \| "updated"` | ✓ | created = 최초 등장, updated = 같은 이벤트의 새 리비전. | | `topic` | `string` | ✓ | <유형>.<소스> 형식의 토픽 ID. 예: announcement.binance. X 계정은 숫자 ID를 씁니다(예: twitter.44196397). | | `type` | `"announcement" \| "news" \| "signal" \| "twitter"` | ✓ | 메시지 유형으로 data 구조를 결정합니다. | | `source` | `object` | ✓ | 소스: id는 토픽 접미사와 같고 name은 영문 표시명입니다(X는 @핸들과 표시 이름). (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)으로 중복 제거하고 가장 큰 리비전을 유지하세요. **중복 제거 예시** ```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입니다. **예시: 거래소 공지(실제 데이터)** ```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": "6b150bf2d0e4e92d8481211f", "revision": 1, "action": "created", "topic": "news.panews", "type": "news", "source": { "id": "panews", "name": "PANews" }, "published_at": 1796541408, "published_at_ms": 1796541408000, "detected_at_ms": 1796541426000, "data": { "titles": { "zh": "DWF Labs合伙人:比特币已挺过风暴,若Strategy没有崩盘,市场或已触底", "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed" }, "original_lang": "zh", "translated_langs": [], "summary": "PANews 12月6日消息,DWF Labs 合伙人 Andrei Grachev 发文预测,比特币已经受住这轮市场风暴,如果 Strategy 没有崩盘,那么市场可能已经触底。", "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169" } } ``` **번역 보완 후(같은 id, 더 큰 revision): 기계 번역 제목 추가** ```json { "spec_version": "1.0", "id": "6b150bf2d0e4e92d8481211f", "revision": 3, "action": "updated", "topic": "news.panews", "type": "news", "source": { "id": "panews", "name": "PANews" }, "published_at": 1796541408, "published_at_ms": 1796541408000, "detected_at_ms": 1796541426000, "data": { "titles": { "zh": "DWF Labs合伙人:比特币已挺过风暴,若Strategy没有崩盘,市场或已触底", "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed", "ko": "DWF Labs 파트너: 비트코인은 폭풍을 견뎌냈으며, 만약 Strategy가 붕괴되지 않았다면 시장은 이미 바닥에 도달했을 수 있다" }, "original_lang": "zh", "translated_langs": [ "ko" ], "summary": "PANews 12月6日消息,DWF Labs 合伙人 Andrei Grachev 发文预测,比特币已经受住这轮市场风暴,如果 Strategy 没有崩盘,那么市场可能已经触底。", "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169" } } ``` ## 시그널(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" ] } } ``` ## X(트위터) 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` | ✓ | 이미지·동영상 URL(최대 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 조회와 스트림 이어 받기도 이 범위까지만 가능합니다(플랜의 기록 보관 일수가 더 짧으면 그 기간). **예시: X 게시물(실제 데이터)** ```json { "spec_version": "1.0", "id": "6b150c67e70ade1bb493e0e2", "revision": 1, "action": "created", "topic": "twitter.44196397", "type": "twitter", "source": { "id": "44196397", "name": "@elonmusk (Elon Musk)" }, "published_at": 1796541539, "published_at_ms": 1796541539136, "detected_at_ms": 1796541543941, "data": { "kind": "quote", "tweet_id": "2129475674222317961", "author": { "id": "44196397", "screen_name": "elonmusk", "name": "Elon Musk" }, "text": "Yeah", "lang": "en", "url": "https://x.com/elonmusk/status/2129475674222317961", "referenced_tweet_id": "2129371437043483081", "conversation_id": null, "media": [], "complete": true } } ``` ## 호환성 - 같은 메이저 버전 안에서는 필드가 **추가**만 되며 삭제·이름 변경·타입 변경은 없습니다. 모르는 필드는 무시하세요. - 새 메시지 유형은 새 `type`으로 나타납니다. 처리하지 않는 유형은 무시하세요. - 전체 JSON Schema는 [GET /v1/schema](https://tokenearly.com/ko/developers/rest/schema)에 있습니다. --- # 내 알림 스트림 토픽별 전체 이벤트와 별도로, **실제로 나에게 보내진** 알림을 그대로 받을 수 있습니다. 웹에서 설정한 Bark·위챗 워크 등 채널이 받는 것과 같으며 소스·키워드·알림 언어로 필터링됩니다. 우리 알림을 직접 만든 봇이나 워크플로에 연결할 때 쓰세요. > Source: https://tokenearly.com/ko/developers/my-alerts · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## 두 가지 데이터 | | 토픽 이벤트(일반 스트림) | 내 알림(이 페이지) | |---|---|---| | 내용 | 구독 토픽의 **모든** 메시지, 개인 설정과 무관 | **나에게 보내진** 것만: 웹에서 설정한 소스 스위치, 키워드, 알림 언어, 플랜 지연으로 필터링 | | 채널과의 관계 | 무관 | Bark·위챗 워크 등 채널이 받는 것과 한 건씩 동일 | | 형식 | 구조화 이벤트, `op = "event"`([이벤트 형식](https://tokenearly.com/ko/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 키로 `wss://api.tokenearly.com/v1/stream?topics=my_alerts`에 연결하거나 [GET /v1/alerts](https://tokenearly.com/ko/developers/rest/alerts)를 호출합니다. 같은 계정의 모든 키가 같은 내 알림을 봅니다. `my_alerts`는 스트림에서만 특수 토픽이며, REST의 `GET /v1/events?topics=my_alerts`는 이를 없는 토픽으로 보고 `access.unknown`에 넣으므로 `GET /v1/alerts`를 쓰세요. > 내 알림은 계정의 플랜 지연을 따릅니다: 유료는 실시간, 무료는 다른 채널과 같이 지연 전송. ## 메시지 형식 스트림에서는 `{"op": "alert", "alert": {...}}`, REST는 `{"alerts": [...]}`이며 객체는 같습니다. | 필드 | 설명 | |---|---| | `id` | 내 알림 ID(24자리 16진수, 시간순 증가). `after` / `before` 커서로 사용하며 이벤트 ID와는 다릅니다. | | `category` | 알림 종류: `announcement` 공지, `news` 뉴스, `twitter` X, `signal` 시그널, `price_alert` 가격 알림, `contract_movement` 선물 급변동. | | `source` | `{id, name}`: 소스 ID(예: `binance`, `odaily`, X 계정 숫자 ID)와 표시 이름. | | `followup` | `true` = 이미 받은 알림의 추가 전송(예: 원문 뒤의 번역). | | `lang` | `text`의 언어(`zh` / `en` / `ko`), 공지·뉴스만 있고 그 외는 `null`. | | `label` | `original` = 원문이 설정한 알림 언어가 아니어서 원문을 먼저 보냄(이후 번역이 옴), `translation` = 기계 번역, `official_translation` = 출처(거래소 또는 뉴스 매체)가 나중에 공개한 해당 언어 공식판, `null` = 보낼 때 이미 내 언어(출처 원문이 그 언어이거나, 알림 전에 출처가 그 언어 공식판을 이미 공개한 경우)이거나 해당 없음(예: 가격 알림). `text` 첫 줄을 파싱하지 말고 `label`과 `lang` 필드로 판단하세요. 그 줄의 문구는 알림 언어에 따라 달라지고, 과거 알림은 이전 문구를 씁니다. | | `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일이며 그보다 오래된 것은 가져올 수 없습니다. ## 구독과 해제 | 동작 | 방법 | |---|---| | 내 알림만 | `?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/ko/developers/rest/list-events · Docs index: https://tokenearly.com/ko/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 키 필요** ## 파라미터 | 파라미터 | 위치 | 타입 | 필수 | 설명 | |---|---|---|---|---| | `topics` | query | string | | 쉼표로 구분하며 자유롭게 조합할 수 있습니다(예: `announcement.binance,news.*`). 각 항목은 토픽 또는 패턴: `announcement.binance`, `announcement.*`, `news.*`, `signal.*`, `twitter.*`, `*`. 생략하면 키가 읽을 수 있는 모든 토픽. | | `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일 수 있으니 `has_more`가 false가 될 때까지 `next_cursor`로 계속 넘기세요. | ## 요청 예시 **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": "6b150c67e70ade1bb493e0e2", "revision": 1, "action": "created", "topic": "twitter.44196397", "type": "twitter", "source": { "id": "44196397", "name": "@elonmusk (Elon Musk)" }, "published_at": 1796541539, "published_at_ms": 1796541539136, "detected_at_ms": 1796541543941, "data": { "kind": "quote", "tweet_id": "2129475674222317961", "author": { "id": "44196397", "screen_name": "elonmusk", "name": "Elon Musk" }, "text": "Yeah", "lang": "en", "url": "https://x.com/elonmusk/status/2129475674222317961", "referenced_tweet_id": "2129371437043483081", "conversation_id": null, "media": [], "complete": true } }, { "spec_version": "1.0", "id": "6b150bf2d0e4e92d8481211f", "revision": 3, "action": "updated", "topic": "news.panews", "type": "news", "source": { "id": "panews", "name": "PANews" }, "published_at": 1796541408, "published_at_ms": 1796541408000, "detected_at_ms": 1796541426000, "data": { "titles": { "zh": "DWF Labs合伙人:比特币已挺过风暴,若Strategy没有崩盘,市场或已触底", "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed", "ko": "DWF Labs 파트너: 비트코인은 폭풍을 견뎌냈으며, 만약 Strategy가 붕괴되지 않았다면 시장은 이미 바닥에 도달했을 수 있다" }, "original_lang": "zh", "translated_langs": [ "ko" ], "summary": "PANews 12月6日消息,DWF Labs 合伙人 Andrei Grachev 发文预测,比特币已经受住这轮市场风暴,如果 Strategy 没有崩盘,那么市场可能已经触底。", "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169" } }, { "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.panews", "signal.binance_alpha", "twitter.44196397" ], "denied": [], "unknown": [] } } ``` ## 오류 | 코드 | HTTP | 설명 | |---|---|---| | `missing_api_key` | 401 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `invalid_cursor` | 400 | after / before가 올바른 ID가 아니거나(이벤트는 이벤트 ID, 내 알림은 내 알림 ID) 둘 다 보냈거나, (이벤트만) updated_after와 before를 함께 썼습니다. | | `invalid_parameter` | 400 | 파라미터 타입이나 값이 잘못되었습니다(예: limit 범위 초과). | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(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` | OKX | 거래소 공지 | | `announcement.mexc` | MEXC | 거래소 공지 | | `announcement.bitget` | Bitget | 거래소 공지 | | `announcement.gate` | Gate.io | 거래소 공지 | | `announcement.huobi` | 후오비 | 거래소 공지 | | `announcement.bybit` | Bybit | 거래소 공지 | | `announcement.kucoin` | KuCoin | 거래소 공지 | | `announcement.upbit` | 업비트 | 거래소 공지 | | `announcement.bithumb` | 빗썸 | 거래소 공지 | | `news.odaily` | Odaily | 뉴스 | | `news.jinse` | 진세 파이낸스 | 뉴스 | | `news.theblockbeats` | 더블록비츠 | 뉴스 | | `news.foresight` | Foresight News | 뉴스 | | `news.panews` | PANews | 뉴스 | | `news.coinmarketcap` | CoinMarketCap | 뉴스 | | `news.wallstreetcn` | WallStreetCN | 뉴스 | | `news.theblock` | The Block | 뉴스 | | `signal.binance_alpha` | Binance Alpha | 시그널 | | `twitter.44196397` | @elonmusk (Elon Musk) | X(트위터) KOL 게시물 | | `twitter.902926941413453824` | @cz_binance (CZ 🔶 BNB) | X(트위터) KOL 게시물 | | `twitter.574032254` | @coinbase (Coinbase 🛡️) | X(트위터) KOL 게시물 | | `twitter.1422537905885442055` | @CoinbaseAssets (Coinbase Assets 🛡️) | X(트위터) KOL 게시물 | | `twitter.720487892670410753` | @CoinbaseMarkets (Coinbase Markets 🛡️) | X(트위터) KOL 게시물 | | `twitter.877807935493033984` | @binance (Binance) | X(트위터) KOL 게시물 | | `twitter.295218901` | @VitalikButerin (vitalik.eth) | X(트위터) KOL 게시물 | | `twitter.1003840309166366721` | @heyibinance (Yi He) | X(트위터) KOL 게시물 | | `twitter.902839045356744704` | @justinsuntron (H.E. Justin Sun 👨‍🚀 🌞) | X(트위터) KOL 게시물 | | `twitter.900935123968737281` | @hebi555 (何币) | X(트위터) KOL 게시물 | | `twitter.1403881130802225152` | @BTCdayu (大宇) | X(트위터) KOL 게시물 | | `twitter.2985599460` | @star_okx (Star_OKX) | X(트위터) KOL 게시물 | | `twitter.1533037218444476416` | @xincctnnq (币圈女菩萨|Pizza披萨🍕) | X(트위터) KOL 게시물 | | `twitter.25073877` | @realDonaldTrump (Donald J. Trump) | X(트위터) KOL 게시물 | | `twitter.1686901686185721857` | @TrumpDailyPosts (Commentary Trump Daily Posts) | X(트위터) KOL 게시물 | | `twitter.20736511` | @nayibbukele (Nayib Bukele) | X(트위터) KOL 게시물 | | `twitter.1844002277218242560` | @Plasma | X(트위터) KOL 게시물 | | `twitter.2414580907` | @pauliepunt (Paul) | X(트위터) KOL 게시물 | | `twitter.867617849208037377` | @okx (OKX) | X(트위터) KOL 게시물 | | `twitter.1138033434` | @Rewkang (Andrew Kang) | X(트위터) KOL 게시물 | | `twitter.1789908971953799168` | @Aster_DEX (Aster 🥷) | X(트위터) KOL 게시물 | | `twitter.1948234340556763136` | @zakk_okx (Zakk 🟪 OKX AI) | X(트위터) KOL 게시물 | | `twitter.357312062` | @Bitcoin | X(트위터) KOL 게시물 | | `twitter.973261472` | @blknoiz06 (Ansem 🐂🀄️) | X(트위터) KOL 게시물 | | `twitter.132749200` | @OxSunNFT (0xSun ❤️ Memecoin) | X(트위터) KOL 게시물 | | `twitter.844304603336232960` | @MustStopMurad (Murad 💹🧲) | X(트위터) KOL 게시물 | | `twitter.1195728139898376193` | @0xcryptowizard (0xWizard) | X(트위터) KOL 게시물 | | `twitter.992590209752629249` | @notEezzy (Eezzy 🧸) | X(트위터) KOL 게시물 | | `twitter.1800348208461205504` | @xiaomucrypto (新股神白毛股神) | X(트위터) KOL 게시물 | | `twitter.16228398` | @mcuban (Mark Cuban) | X(트위터) KOL 게시물 | | `twitter.1189381231198134272` | @CookerFlips (Cooker.hl \| 版本之子 \| (Theo Arc)) | X(트위터) KOL 게시물 | | `twitter.1279711663264894977` | @DekuKing1 (0x易经(刘彻版)) | X(트위터) KOL 게시물 | | `twitter.725984371946082304` | @XXAntiWar (XX) | X(트위터) KOL 게시물 | | `twitter.1462727797135216641` | @lookonchain (Lookonchain) | X(트위터) KOL 게시물 | | `twitter.1466673394649559040` | @huahuayjy (花花) | X(트위터) KOL 게시물 | | `twitter.1401718840535379970` | @hellosuoha (梭教授说) | X(트위터) KOL 게시물 | | `twitter.1453603581932687368` | @laofeiyyds (比特币老肥.btc(敏感肥)) | X(트위터) KOL 게시물 | | `twitter.1852674305517342720` | @aixbt_agent (aixbt) | X(트위터) KOL 게시물 | | `twitter.1279918106111025153` | @assetdash (Dash News) | X(트위터) KOL 게시물 | | `twitter.169686021` | @kanyewest (ye) | X(트위터) KOL 게시물 | | `twitter.1483495485889564674` | @bwenews (方程式新闻 BWEnews 🏎️) | X(트위터) KOL 게시물 | | `twitter.1052454006537314306` | @BNBCHAIN (BNB Chain) | X(트위터) KOL 게시물 | | `twitter.1451036242431262720` | @binancezh (币安Binance华语) | X(트위터) KOL 게시물 | | `twitter.1940360837547565056` | @aleabitoreddit (Serenity) | X(트위터) KOL 게시물 | 모든 토픽의 권한을 한 번에 보려면 키와 함께 [GET /v1/topics](https://tokenearly.com/ko/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/ko/developers/rest/get-event · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/events/{id}` 항상 현재 최신 리비전을 반환합니다. 토픽 범위 밖의 이벤트는 404를 반환합니다(없음과 권한 없음을 구분하지 않음). **API 키 필요** ## 파라미터 | 파라미터 | 위치 | 타입 | 필수 | 설명 | |---|---|---|---|---| | `id` | path | string | ✓ | 목록 엔드포인트가 반환한 이벤트 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 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `not_found` | 404 | 토픽 범위 안에 해당 이벤트가 없거나(GET /v1/events/{id}), 요청한 경로가 존재하지 않습니다(예: 엔드포인트 주소 오타). | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(REST와 MCP 합산, 간격은 `/v1/me`의 `limits.rest_interval_seconds`). Retry-After 초만큼 기다린 뒤 다시 시도하세요. | --- # 현재 키 정보 키가 읽을 수 있는 토픽, 한도, IP 허용 목록을 확인합니다. > Source: https://tokenearly.com/ko/developers/rest/me · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/me` `topics`는 실제 적용되는 토픽으로, 키에 설정한 범위와 플랜이 여는 소스의 교집합입니다. 연동 전에 한 번 호출해 범위를 확인하세요. **API 키 필요** ## 파라미터 파라미터가 없습니다. ## 요청 예시 **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 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(REST와 MCP 합산, 간격은 `/v1/me`의 `limits.rest_interval_seconds`). Retry-After 초만큼 기다린 뒤 다시 시도하세요. | --- # 변경 알림 한도 조정, 키 변경, API 업데이트 기록. > Source: https://tokenearly.com/ko/developers/rest/notices · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/notices` 이 키와 관련된 알림을 최신순으로 반환합니다: 전체 공지, 계정 변경, 이 키의 변경. 전체·계정 알림은 키 생성 시각으로 거르지 않으므로 새 키에서도 생성 전에 게시된 알림이 보이며, 키 단위 알림은 키를 만든 뒤부터 생깁니다. 스트림이 열려 있으면 같은 알림이 `op = "notice"`로 즉시 푸시되며, 오프라인 후에는 `since`로 따라잡습니다. **API 키 필요** ## 파라미터 | 파라미터 | 위치 | 타입 | 필수 | 설명 | |---|---|---|---|---| | `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 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `invalid_parameter` | 400 | 파라미터 타입이나 값이 잘못되었습니다(예: limit 범위 초과). | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(REST와 MCP 합산, 간격은 `/v1/me`의 `limits.rest_interval_seconds`). Retry-After 초만큼 기다린 뒤 다시 시도하세요. | ## 알림 종류 | kind | scope | 의미 | |---|---|---| | `defaults_changed` | `global` | 기본 한도 조정(이전 → 이후) | | `account_limits_changed` | `user` | 내 계정 한도 조정 | | `key_limits_changed` | `key` | 특정 키 한도 조정 | | `ip_allowlist_changed` | `key` | 특정 키 IP 허용 목록 변경(data.before / data.after) | | `key_reset` | `key` | 특정 키 재설정(data.old_prefix / data.prefix는 이전·새 접두사, 새 키로 전송되며 기존 키의 연결은 이미 끊김) | | `key_revoked` | `key` | 특정 키 폐기 | | `access_expiring` | `user` | API가 포함된 멤버십 만료 임박(7·3·1일 전 각 1회, data.expires_at은 만료 시각) | | `access_expired` | `user` | API가 포함된 멤버십 만료. 키는 403 plan_required / 4003으로 거부되며 갱신하면 같은 키가 바로 다시 동작 | | `api_update` | `global` | API 공지 | - `scope`: `global` = 전체, `user` = 내 계정, `key` = 특정 키(`key_id` 참고). - `data.changes`는 `{항목: [이전, 이후]}`이며 `null`은 기본값입니다. - `since`는 배타적(그 이후 알림만)이며 호출당 최대 200건, 커서는 없습니다. 마지막 알림의 `created_at`을 다음 `since`로 쓰세요. --- # 내 알림 Bark·위챗 워크 등 채널이 받는 것과 같은 푸시(웹 설정으로 필터링). > Source: https://tokenearly.com/ko/developers/rest/alerts · Docs index: https://tokenearly.com/ko/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/ko/developers/my-alerts) 참고. 먼저 웹의 전역 알림 관리 → 알림 채널에서 「개발자 API」 스위치를 켜야 새 내 알림이 생성되며, 응답의 `channel_enabled`가 스위치 상태입니다. 기본은 최신순이며 `before`로 페이지를 넘기고, 끊긴 뒤에는 `after=<마지막 알림 id>`로 오래된 순으로 따라잡습니다. 최근 7일분을 보관합니다. **API 키 필요** ## 파라미터 | 파라미터 | 위치 | 타입 | 필수 | 설명 | |---|---|---|---|---| | `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 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `invalid_cursor` | 400 | after / before가 올바른 ID가 아니거나(이벤트는 이벤트 ID, 내 알림은 내 알림 ID) 둘 다 보냈거나, (이벤트만) updated_after와 before를 함께 썼습니다. | | `invalid_parameter` | 400 | 파라미터 타입이나 값이 잘못되었습니다(예: limit 범위 초과). | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(REST와 MCP 합산, 간격은 `/v1/me`의 `limits.rest_interval_seconds`). Retry-After 초만큼 기다린 뒤 다시 시도하세요. | --- # 토픽 목록 구독 가능한 모든 토픽. 키를 보내면 읽기 가능 여부를 표시합니다. > Source: https://tokenearly.com/ko/developers/rest/topics · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/topics` 키가 필요 없고 속도 제한에 포함되지 않습니다. 새로 추가된 거래소, 뉴스 소스, 시그널 소스가 자동으로 나타나며, X 토픽은 저희가 선정한 KOL 계정 목록으로 수시로 바뀌니 이 목록을 기준으로 하세요. 키를 보내면 각 토픽에 키의 읽기 권한 여부를 나타내는 `accessible` 필드가 붙습니다. **공개 엔드포인트, 키 불필요(키를 보내면 정보가 더 붙음)** ## 파라미터 파라미터가 없습니다. ## 요청 예시 **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_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `ip_not_allowed` | 403 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | --- # 이벤트 JSON Schema 봉투와 data 유형별 JSON Schema(draft 2020-12). > Source: https://tokenearly.com/ko/developers/rest/schema · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/schema` 키가 필요 없고 속도 제한에 포함되지 않습니다. 수신 이벤트 검증이나 타입 생성에 바로 쓸 수 있습니다. **공개 엔드포인트, 키 불필요** ## 파라미터 파라미터가 없습니다. ## 요청 예시 **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/ko/developers/rest/health · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json `GET https://api.tokenearly.com/v1/health` 키가 필요 없고 속도 제한에 포함되지 않습니다. 자체 모니터링에 쓰기 좋습니다. **공개 엔드포인트, 키 불필요** ## 파라미터 파라미터가 없습니다. ## 요청 예시 **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 실시간 푸시 연결 하나를 유지하면 구독 토픽의 새 공지·뉴스·시그널을 감지하는 즉시 푸시합니다. 키당 동시 연결은 1개입니다. > Source: https://tokenearly.com/ko/developers/websocket · Docs index: https://tokenearly.com/ko/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` | 헤더를 설정할 수 없는 브라우저에서만 사용하세요. 서버 코드는 Authorization 헤더를 쓰세요. | 인증은 REST와 같습니다: `Authorization: Bearer <키>` 헤더, 브라우저에서는 `api_key` 쿼리 파라미터. > 키당 동시 연결은 최대 1개이며, 다 차면 새 연결은 4029로 거부됩니다. 필요한 토픽은 한 연결에서 `topics`나 `subscribe`로 모두 구독할 수 있고, 연결이 더 필요하면 키를 더 만드세요. ## 서버 메시지 모든 메시지는 JSON 객체이며 `op`로 유형을 구분합니다: ### op = "welcome" 연결 직후 첫 메시지. topics는 실제 적용된 토픽, denied는 요청했지만 권한 없는 토픽, unknown은 존재하지 않는 토픽(대개 오타), heartbeat_seconds는 하트비트 간격, my_alerts.subscribed는 이 연결이 내 알림을 받는지, my_alerts.channel_enabled는 웹의 「개발자 API」 스위치가 켜져 있는지, 체험 키는 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/ko/developers/my-alerts) 참고. 토픽 이벤트 `op = "event"`가 아니라 `op = "alert"`입니다. 오프라인 동안의 것은 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(특정 키), ip_allowlist_changed, key_reset, key_revoked, api_update(API 공지), access_expiring / access_expired(API가 포함된 멤버십 만료 임박 / 만료, 내 계정). scope: global = 전체, user = 내 계정, key = 특정 키(key_id). title / body는 3개 언어 설명, 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/ko/developers/events) 참고). 유형별 실제 메시지이며 파서 테스트에 그대로 쓸 수 있습니다: **거래소 공지(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": "6b150bf2d0e4e92d8481211f", "revision": 1, "action": "created", "topic": "news.panews", "type": "news", "source": { "id": "panews", "name": "PANews" }, "published_at": 1796541408, "published_at_ms": 1796541408000, "detected_at_ms": 1796541426000, "data": { "titles": { "zh": "DWF Labs合伙人:比特币已挺过风暴,若Strategy没有崩盘,市场或已触底", "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed" }, "original_lang": "zh", "translated_langs": [], "summary": "PANews 12月6日消息,DWF Labs 合伙人 Andrei Grachev 发文预测,比特币已经受住这轮市场风暴,如果 Strategy 没有崩盘,那么市场可能已经触底。", "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169" } } } ``` **뉴스(type = news): 번역 보완 후 다시 푸시** ```json { "op": "event", "event": { "spec_version": "1.0", "id": "6b150bf2d0e4e92d8481211f", "revision": 3, "action": "updated", "topic": "news.panews", "type": "news", "source": { "id": "panews", "name": "PANews" }, "published_at": 1796541408, "published_at_ms": 1796541408000, "detected_at_ms": 1796541426000, "data": { "titles": { "zh": "DWF Labs合伙人:比特币已挺过风暴,若Strategy没有崩盘,市场或已触底", "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed", "ko": "DWF Labs 파트너: 비트코인은 폭풍을 견뎌냈으며, 만약 Strategy가 붕괴되지 않았다면 시장은 이미 바닥에 도달했을 수 있다" }, "original_lang": "zh", "translated_langs": [ "ko" ], "summary": "PANews 12月6日消息,DWF Labs 合伙人 Andrei Grachev 发文预测,比特币已经受住这轮市场风暴,如果 Strategy 没有崩盘,那么市场可能已经触底。", "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169" } } } ``` **시그널(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" ] } } } ``` **X(트위터) KOL 게시물(type = twitter)** ```json { "op": "event", "event": { "spec_version": "1.0", "id": "6b150c67e70ade1bb493e0e2", "revision": 1, "action": "created", "topic": "twitter.44196397", "type": "twitter", "source": { "id": "44196397", "name": "@elonmusk (Elon Musk)" }, "published_at": 1796541539, "published_at_ms": 1796541539136, "detected_at_ms": 1796541543941, "data": { "kind": "quote", "tweet_id": "2129475674222317961", "author": { "id": "44196397", "screen_name": "elonmusk", "name": "Elon Musk" }, "text": "Yeah", "lang": "en", "url": "https://x.com/elonmusk/status/2129475674222317961", "referenced_tweet_id": "2129371437043483081", "conversation_id": null, "media": [], "complete": true } } } ``` `after`로 재연결해 재전송된 이벤트에는 `"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`)으로 중복 제거해 가장 큰 리비전을 남기세요. 새 항목인지는 `action`이 아니라 그 `id`를 본 적이 있는지로 판단하세요. 재연결 후 재전송에서는 새 항목도 이미 `revision = 2`(`action = "updated"`)일 수 있습니다. ## 이어 받기 1. 처리한 모든 `event`의 `event.id`를 저장합니다. 2. 끊기면 `after=<마지막 id>`로 다시 연결합니다. 3. 서버가 그 id 이후의 새 이벤트, 이어서 `after` 이벤트가 저장된 이후 생긴 새 리비전(`after` 이벤트 자신과 더 오래된 이벤트 포함, 모두 `replay: true`, 합계 최대 200건)을 재전송하고 `replay_done`을 보낸 뒤 실시간으로 이어갑니다. 이미 받은 리비전이 다시 올 수 있으니 반드시 (`id`, `revision`)으로 중복 제거하세요. 4. `replay_done.truncated = true`이면 공백이 한도를 넘은 것입니다. 연결을 끊고 REST의 `after`와 `updated_after`로 채운 뒤 재연결하세요. ## 하트비트 welcome의 `heartbeat_seconds` 동안 푸시된 이벤트, 내 알림, 변경 알림(`event` / `alert` / `notice`)이 없으면 서버가 `ping`을 보내므로, 이벤트가 없을 때는 `heartbeat_seconds`마다 옵니다. 시간은 `welcome` 이후(`after`로 연결하면 `replay_done` 이후)부터 세며, 보낸 메시지에 대한 서버 응답(`subscribed`, `pong`, `invalid_message` 오류)은 이 시간을 초기화하지 않으므로 `ping`이 이런 응답 바로 뒤에 올 수 있고 이는 정상입니다. 하트비트 두 주기 동안 아무것도 오지 않으면 연결이 끊긴 것으로 보고 다시 연결하세요. 재시도는 1, 2, 4…초(최대 60초)로 백오프하고, 종료 코드 4001 / 4003은 자동 재연결하지 말며, 4029 후에는 최소 5초 기다리세요. ## 종료 코드 | 코드 | 의미 | |---|---| | `4001` | 키가 없거나 잘못되었거나 재설정·폐기되었거나(체험 키) 만료(error.code = missing_api_key / invalid_api_key / key_expired). 자동 재연결하지 마세요. | | `4003` | 권한 없음: 플랜에 개발자 API가 없거나 만료(error.code = plan_required), 또는 IP가 허용 목록 밖(error.code = ip_not_allowed). 자동 재연결하지 말고 원인을 먼저 해결하세요. | | `4029` | 이 키의 연결 한도가 다 차서 새 연결이 거부됨. 기존 연결을 막 닫은 직후에는 슬롯 해제에 몇 초 걸릴 수 있으니 최소 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` 등 커서) 대소문자 | 구분하지 않음: 16진수 대소문자 모두 허용되며 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 에이전트 연동: Markdown 문서, llms.txt, OpenAPI, MCP 문서와 API 모두 AI용으로 준비되어 있습니다. 모든 페이지를 Markdown으로 복사할 수 있고, 규격은 기계 판독 가능하며, 에이전트는 MCP로 이벤트를 직접 조회할 수 있습니다. > Source: https://tokenearly.com/ko/developers/ai · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json ## MCP란 MCP(Model Context Protocol)는 AI 클라이언트가 외부 도구를 호출하는 공개 프로토콜입니다. 이것도 API이지만 호출하는 쪽이 AI입니다. Claude, Cursor 같은 클라이언트가 MCP 서버에 연결하면 도구 목록과 파라미터 설명을 자동으로 받아 대화 중에 필요할 때 조회하므로 요청 코드를 직접 짤 필요가 없습니다. | | REST | MCP | WebSocket | |---|---|---|---| | 호출 주체 | 직접 작성한 코드 | AI 클라이언트(Claude, Cursor…) | 직접 작성한 코드 | | 기능 | 기록 조회 | 기록 조회(같은 데이터) | 실시간 푸시 | | 인증 | 같은 API 키 | 같은 API 키 | 같은 API 키 | | 제한 | 3초에 1회 | REST와 공유 | 키당 동시 1개 | MCP 도구 호출(`get_events`, `get_event`, `get_alerts`, `whoami`)은 같은 키의 REST 제한을 공유해 합계 3초에 1회입니다. 초과하면 도구가 `rate_limited` 오류를 돌려주고 AI가 잠시 후 다시 시도합니다. `list_topics`와 `get_schema`는 포함되지 않습니다. ## MCP 서버 주소 `https://api.tokenearly.com/v1/mcp`(Streamable HTTP). `Authorization: Bearer <키>` 헤더로 인증하며 체험 키도 됩니다. 모든 도구는 읽기 전용입니다. **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` | 구독 가능한 모든 토픽(거래소 공지, 뉴스, 시그널, 선정된 X(트위터) KOL 계정)을 `id`, `type`, `source_id`, `names`와 함께 반환합니다. 키를 보내면 읽기 가능 여부 `accessible`이 붙습니다. REST `GET /v1/topics`와 같으며 속도 제한에 포함되지 않습니다. | | `get_events` | 구조화된 이벤트(거래소 공지, 뉴스, 시그널, 선정된 X(트위터) KOL 게시물)를 조회하며 기본은 최신순입니다. 파라미터는 REST `GET /v1/events`와 같고 `limit` 범위만 다릅니다. REST와 같은 키 속도 제한을 공유합니다. | | `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`와 같습니다. 키가 필요 없고 속도 제한에 포함되지 않습니다. | | `whoami` | 사용 중인 키의 실제 토픽, 한도, 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.*`, `*`. 생략하면 키가 읽을 수 있는 모든 토픽. | | `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일 수 있으니 `has_more`가 false가 될 때까지 `next_cursor`로 계속 넘기세요. | | `updated_after` | integer | | | ≥ 0 | 이 Unix 시간(초) 이후 새 리비전이 생긴 이벤트(이벤트 자체는 더 오래될 수 있음)를 이벤트 ID 순으로 반환합니다. 오프라인 동안 놓친 기존 이벤트의 업데이트를 받을 때 씁니다. 페이지를 넘길 때는 updated_after는 그대로 두고 이전 next_cursor를 after로 넘기세요. before와 함께 쓸 수 없습니다. 생략하거나 0을 넘기면 사용하지 않는 것으로 봅니다(일반 목록, 최신순). | ### `get_event` | 인자 | 타입 | 필수 | 기본값 | 범위 | 설명 | |---|---|---|---|---|---| | `id` | string | ✓ | | | 목록 엔드포인트가 반환한 이벤트 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/ko/developers/llms.txt): 문서 목차. AI가 먼저 훑어보고 필요한 것만 읽게 할 때. - [llms-full.txt](https://tokenearly.com/ko/developers/llms-full.txt): 전체 문서를 한 파일로, 한 번에 읽기. ## 기계 판독 파일: llms.txt, OpenAPI, AsyncAPI 문서 왼쪽 아래의 링크가 이 파일들입니다. 사람이 읽는 페이지가 아니라 프로그램과 AI가 쓰는 파일로, 도구에 가져와 요청·클라이언트 코드를 만들거나 AI가 API를 이해하게 합니다. | 파일 | 용도 | |---|---| | [llms.txt](https://tokenearly.com/ko/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/ko/developers/llms-full.txt 그다음 WebSocket으로 announcement.*를 구독하고, data.listing.is_listing이 true인 이벤트만 처리하며, (id, revision)으로 중복 제거하고, 재연결 시 after로 이어 받고, 제목을 내 Telegram 그룹으로 전달하는 Python 서비스를 작성해. 먼저 대시보드에서 받은 체험 키로 테스트해. ``` --- # 오류 코드와 처리 방법 REST 오류는 항상 `error` 객체를 반환합니다. `message` 문구가 아닌 `code`로 분기하세요. > Source: https://tokenearly.com/ko/developers/errors · Docs index: https://tokenearly.com/ko/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`이고, API 오류(키, 권한, 속도 제한 등)는 `isError: true`인 도구 결과로 오며 내용은 같은 `{"error": {"code", "message"}}`입니다. ## HTTP 오류 | code | HTTP | 의미와 처리 | |---|---|---| | `missing_api_key` | 401 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `key_expired` | 401 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `invalid_api_key` | 401 | 키가 없거나 재설정 또는 폐기되었습니다. | | `plan_required` | 403 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 403 | 키에 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 메서드는 지원하지 않습니다(예: POST /v1/events). REST 엔드포인트는 모두 GET이고 MCP만 POST를 씁니다. `Allow` 헤더에 지원 메서드가 있습니다. | | `rate_limited` | 429 | 이 키의 요청 빈도를 넘었습니다(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 | 키가 없습니다. `Authorization: Bearer <키>`를 쓰세요. | | `key_expired` | 4001 | 체험 키가 만료되었습니다. 새 체험 키를 신청하거나 구독 후 정식 키를 만드세요. | | `invalid_api_key` | 4001 | 키가 없거나 재설정 또는 폐기되었습니다. | | `plan_required` | 4003 | 현재 플랜에 개발자 API(또는 해당 기능)가 없습니다. | | `ip_not_allowed` | 4003 | 키에 IP 허용 목록이 설정되어 있고 요청 IP가 목록에 없습니다. | | `invalid_cursor` | 4400 | 연결 파라미터 after가 올바른 이벤트 ID가 아님. 4400으로 닫히며 고친 뒤 연결하세요. | | `too_many_connections` | 4029 | 이 키의 실시간 연결 한도가 다 찼습니다(`/v1/me`의 `limits.streams_per_key`). 새 연결은 거부됩니다. 기존 연결을 닫거나 다른 서버에는 다른 키를 쓰세요. | | `invalid_message` | 유지 | WebSocket 클라이언트 메시지 오류: JSON 객체가 아님, 문자열 op 없음, 알 수 없는 op, 또는 topics가 비었거나 문자열 목록이 아님. 연결은 유지되니 고쳐서 다시 보내세요. | | `slow_consumer` | 4008 | 처리가 느려 미전송 이벤트가 쌓였습니다. after로 다시 연결하면 이어집니다. | ## 언제 재시도할까 - `429`: `Retry-After`초 기다린 뒤 재시도. - `5xx`와 네트워크 오류: 지수 백오프로 재시도(1, 2, 4…초, 상한 설정). - `401` / `403` / `400`: 재시도하지 말고 키·플랜·파라미터를 먼저 고치세요.