↗

WebSocket 실시간 푸시

연결 하나를 유지하면 구독 토픽의 새 공지·뉴스·시그널을 감지하는 즉시 푸시합니다. 키당 동시 연결은 1개입니다.

바로 실행 · WebSocket
체험 키 신청
연결 안 됨

API 키(정식 키 또는 대시보드에서 신청한 체험 키)를 넣으면 실제 API를 호출합니다. 키는 브라우저에만 저장됩니다.

연결

wss://api.tokenearly.com/v1/stream?topics=announcement.binance,news.*,my_alerts&after=<last_event_id>

무엇을 구독하나

topics는 무엇이든 조합할 수 있습니다: 쉼표로 구분하며 각 항목은 특정 토픽, 패턴(news.*, *), 또는 특수 값 my_alerts(내 알림)입니다. 연결 후에도 subscribe / unsubscribe로 언제든 늘리거나 줄일 수 있습니다.

원하는 것topics받는 것
읽을 수 있는 모든 토픽 이벤트생략 또는 *op = "event"
한 종류announcement.*모든 거래소 공지
몇몇 소스announcement.binance,news.odaily,twitter.44196397해당 소스만
내 알림만my_alertsop = "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 초)도 포함.

{
  "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가 붙습니다.

{
  "op": "event",
  "event": {
    "id": "…",
    "revision": 1,
    "topic": "announcement.binance",
    "…": "…"
  }
}

op = "alert"

내 알림 한 건(my_alerts를 구독한 연결만 수신): Bark·위챗 워크가 받는 것과 같은 푸시이며 필드는 내 알림 스트림 참고. 토픽 이벤트 op = "event"가 아니라 op = "alert"입니다. 오프라인 동안의 것은 GET /v1/alerts?after=로 따라잡으세요(스트림은 내 알림을 재전송하지 않음).

{
  "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)로 먼저 채운 뒤 재연결하세요.

{
  "op": "replay_done",
  "count": 3,
  "truncated": false
}

op = "subscribed"

subscribe / unsubscribe 후 새로 적용된 토픽(빈 목록일 수 있음)을 반환합니다. denied는 welcome과 같고, unknown은 이번 메시지에서 존재하지 않는 토픽입니다.

{
  "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로 따라잡으세요.

{
  "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이 이런 응답 바로 뒤에 올 수 있습니다. 응답 불필요하며 하트비트 두 주기 동안 아무것도 없으면 연결이 끊긴 것이니 재연결하세요.

{
  "op": "ping",
  "ts": 1794208744
}

op = "pong"

클라이언트 ping에 대한 응답.

{
  "op": "pong",
  "ts": 1794208744
}

op = "error"

오류 설명. 인증·권한·파라미터 오류 뒤에는 연결이 닫히며(종료 코드 표 참고), code = invalid_message(잘못된 클라이언트 메시지)일 때는 연결이 유지됩니다.

{
  "op": "error",
  "code": "invalid_api_key",
  "message": "This API key does not exist or has been revoked."
}

전체 메시지 예시

스트리밍 중 메시지는 JSON 객체 하나이며 op = "event", event에 전체 이벤트가 들어 있습니다(필드는 이벤트 형식 참고). 유형별 실제 메시지이며 파서 테스트에 그대로 쓸 수 있습니다:

거래소 공지(type = announcement): 첫 푸시(원문만)
{
  "op": "event",
  "event": {
    "spec_version": "1.0",
    "id": "6b0ff643d0e4e92d84810499",
    "revision": 1,
    "action": "created",
    "topic": "announcement.gate",
    "type": "announcement",
    "source": {
      "id": "gate",
      "name": "Gate.io"
    },
    "published_at": 1796208195,
    "published_at_ms": 1796208195000,
    "detected_at_ms": 1796208195896,
    "data": {
      "titles": {
        "zh": "Gate 已上线 RITUAL 合约交易、杠杆借贷交易、交易机器人、跟单、闪兑、定投功能",
        "en": "Gate Now Supports RITUAL for Futures Trading, Margin Loans, Bots, Copy, Convert, and Auto-Invest"
      },
      "original_lang": "zh",
      "translated_langs": [],
      "url": "https://www.gate.io/article/103112",
      "exchange_category": "listing",
      "listing": {
        "is_listing": true,
        "market": "futures"
      },
      "symbols": []
    }
  }
}
거래소 공지(type = announcement): 번역 보완 후 다시 푸시
{
  "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): 첫 푸시(원문만)
{
  "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): 번역 보완 후 다시 푸시
{
  "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)
{
  "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)
{
  "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"

토픽 추가 구독(패턴 허용).

{
  "op": "subscribe",
  "topics": [
    "announcement.okx",
    "signal.*"
  ]
}

op = "unsubscribe"

토픽 구독 해제(패턴 허용, ["*"]는 모든 토픽을 해제하며 연결은 유지되고 하트비트, 변경 알림, 구독 중인 내 알림만 옵니다. 내 알림은 my_alerts를 따로 해제하세요).

{
  "op": "unsubscribe",
  "topics": [
    "announcement.okx"
  ]
}

op = "ping"

클라이언트 하트비트. 서버가 pong으로 응답합니다.

{
  "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를 여러 번 지정마지막 값만 사용

전체 예제

import asyncio, json, os, time
import requests    # pip install requests
import websockets  # pip install websockets

KEY = os.environ["TOKENEARLY_API_KEY"]
H = {"Authorization": f"Bearer {KEY}"}
TOPICS = "announcement.*,news.*,signal.*,twitter.*"
STREAM = "wss://api.tokenearly.com/v1/stream?topics=" + TOPICS
EVENTS = "https://api.tokenearly.com/v1/events"
FATAL = {4001, 4003}                        # bad / expired key, no permission: fix it, do not retry

last_id = None                              # last event id: resume cursor (store it durably in production)
live_at = int(time.time())                  # last moment the stream was live: `updated_after` for a REST catch-up

def handle(ev):
    global last_id
    if not last_id or ev["id"] > last_id:   # ids grow with time; only move the cursor forward
        last_id = ev["id"]
    data = ev["data"]                       # same envelope for every type; `data` depends on ev["type"]
    if ev["type"] == "twitter":             # X posts: text as published, no titles
        text = "@" + data["author"]["screen_name"] + ": " + data["text"]
    else:
        text = data["titles"].get("en") or next(iter(data["titles"].values()), "")
    print(ev["type"], ev["topic"], ev["revision"], text)   # dedupe on (id, revision) in production

def rest_get(params):
    while True:
        r = requests.get(EVENTS, params=dict(params, topics=TOPICS, limit=200), headers=H, timeout=10)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "3")))
            continue
        r.raise_for_status()
        time.sleep(int(r.headers.get("X-RateLimit-Reset", "3")))   # respect the per-key interval
        return r.json()

def catch_up():
    """replay_done.truncated: the gap is too big for the stream, so fill it over REST."""
    while True:                             # 1) new events after the cursor, oldest first
        page = rest_get({"after": last_id})
        for ev in page["events"]:
            handle(ev)
        if not page["has_more"]:
            break
    params = {"updated_after": live_at}     # 2) older events that got a new revision while away
    while True:
        page = rest_get(params)
        for ev in page["events"]:
            handle(ev)
        if not page["has_more"]:
            break
        params = {"updated_after": live_at, page["cursor_param"]: page["next_cursor"]}

async def main():
    global live_at, last_id
    delay = 1
    while True:
        url = STREAM + (f"&after={last_id}" if last_id else "")
        truncated = False
        try:
            async with websockets.connect(url, additional_headers=H) as ws:
                async for raw in ws:
                    msg = json.loads(raw)
                    op = msg["op"]
                    if op == "welcome":
                        delay = 1
                    elif op == "event":
                        handle(msg["event"])
                    elif op == "replay_done" and msg["truncated"]:
                        truncated = True    # 1) close, 2) catch up over REST, 3) reconnect with the new cursor
                        break
                    elif op == "notice":
                        print("notice:", msg["notice"]["kind"], msg["notice"]["body"].get("en"))
                    elif op == "error":
                        print("server error:", msg["code"], msg["message"])
                    if op == "ping" or (op == "event" and not msg.get("replay")):
                        live_at = int(time.time())   # live traffic only comes after the replay
        except websockets.ConnectionClosed as e:
            if e.rcvd and e.rcvd.code in FATAL:
                raise SystemExit(f"stopped: close code {e.rcvd.code}")
            if e.rcvd and e.rcvd.code == 4029:
                delay = max(delay, 5)       # slot not free yet
            if e.rcvd and e.rcvd.code == 4400:
                print("stored cursor rejected; reconnecting without it")
                last_id = None              # never retry the same invalid `after`
        except Exception as e:
            print("disconnected:", e)
        if truncated:
            await asyncio.to_thread(catch_up)   # blocking HTTP off the event loop
            continue                            # reconnect right away with after=<new last_id>
        await asyncio.sleep(delay)
        delay = min(delay * 2, 60)          # exponential backoff

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

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

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

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

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

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

	"github.com/coder/websocket"
)

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