# WebSocket push

Keep one connection open and every new announcement, news item or signal on your topics is pushed to you as soon as we detect it. Each key may hold 1 connection(s) at a time.

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

## Connecting

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

### What to subscribe to

`topics` can combine anything: comma-separated items, each a specific topic, a pattern (`news.*`, `*`) or the special value `my_alerts` (my alerts). After connecting you can add or remove topics at any time with `subscribe` / `unsubscribe`.

| You want | topics | You receive |
|---|---|---|
| Every readable topic event | omit it, or `*` | `op = "event"` |
| One category | `announcement.*` | All exchange announcements |
| A few sources | `announcement.binance,news.odaily,twitter.44196397` | Just those sources |
| My alerts only | `my_alerts` | `op = "alert"` |
| My alerts plus topic events | `my_alerts,announcement.*,news.*` | Both, told apart by `op` |

> The “Developer API” switch in the dashboard's notification channels only controls whether my alerts are produced; it does not affect topic events. A connection that does not subscribe to `my_alerts` receives exactly the same data with the switch on or off. `*` does not include `my_alerts`; name it explicitly.

| Query parameter | Description |
|---|---|
| `topics` | Topics to subscribe, comma-separated, patterns allowed. Omit for all readable topics. Add the special value `my_alerts` for your my-alerts stream (never included by `*`; it must be named); `my_alerts` alone = my alerts only, no topic events. |
| `after` | Id of the last event you received. The server first replays what came after it (up to 200), then goes live. |
| `api_key` | Pass the key here only where you cannot set headers (browsers); server code should use the Authorization header. |

Authentication is the same as REST: the `Authorization: Bearer <key>` header, or the `api_key` query parameter in browsers.

> Each key may hold up to 1 connection(s); when they are in use, new ones are refused with 4029. One connection can subscribe to everything you need with `topics` or `subscribe`; if you really need more connections, create more keys.

## Server messages

Every message is a JSON object; `op` tells you the type:

### op = "welcome"

First message after connecting: `topics` are the effective topics; `denied` the requested ones you have no access to; `unknown` requested topics that do not exist (usually a typo); `heartbeat_seconds` the heartbeat interval; `my_alerts.subscribed` tells whether this connection receives your my alerts and `my_alerts.channel_enabled` whether the “Developer API” switch is on in the dashboard; trial keys also get `expires_at` (Unix seconds).

```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"

One event. Replayed past events carry `"replay": true`.

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

### op = "alert"

One my alert (only on connections subscribed to `my_alerts`): the same push your Bark or WeCom receives; fields in [My alerts](https://tokenearly.com/en/developers/my-alerts). Note it is `op = "alert"`, not a topic event `op = "event"`; catch up on ones missed while offline with GET /v1/alerts?after= (the stream does not replay my alerts).

```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"

Marks the end of the catch-up when you connected with `after`; everything after it is live. `count` is the number replayed; `truncated = true` means the gap exceeded the replay limit, so catch up over REST (`after` and `updated_after`) and reconnect.

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

### op = "subscribed"

Returned after subscribe / unsubscribe with the new effective topics (possibly an empty list); `denied` as in welcome; `unknown` lists topics in this frame that do not exist.

```json
{
  "op": "subscribed",
  "topics": [
    "announcement.binance"
  ],
  "denied": [],
  "unknown": [],
  "my_alerts": {
    "subscribed": false,
    "channel_enabled": true
  }
}
```

### op = "notice"

A change notice. `kind`: defaults_changed (default limits, everyone), account_limits_changed (your account), key_limits_changed (one key), ip_allowlist_changed, key_reset, key_revoked, api_update (API announcement), access_expiring / access_expired (the membership that includes the API is about to expire / has expired; your account). `scope`: global = everyone, user = your account, key = one key (`key_id`). `title` / `body` explain it in three languages; `data.changes` is {field: [old, new]} where null means 'the default'. Catch up on notices missed while offline with 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"

Server heartbeat, sent when no event, my alert or notice (`event` / `alert` / `notice`) has been pushed for `heartbeat_seconds`, so every `heartbeat_seconds` while there are no events; `ts` is Unix seconds. The timer starts after `welcome` (after `replay_done` when you connect with `after`); replies to your own frames (`subscribed`, `pong`, `invalid_message` errors) do not restart it, so a ping can arrive right after one of those replies. No reply needed; if nothing arrives for two heartbeat periods, the connection is dead and you should reconnect.

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

### op = "pong"

Reply to a client ping.

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

### op = "error"

An error. Authentication, permission and parameter errors are followed by the connection closing (see close codes); with `code = invalid_message` (a bad client frame) the connection stays open.

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

## Full message examples

During streaming each message is one JSON object: `op = "event"` with the full event in `event` (fields in [Event format](https://tokenearly.com/en/developers/events)). Real messages of every type, ready to use as parser fixtures:

**Exchange announcement (type = announcement): first push (original language only)**

```json
{
  "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": []
    }
  }
}
```

**Exchange announcement (type = announcement): pushed again after translation**

```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": []
    }
  }
}
```

**News (type = news): first push (original language only)**

```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"
    }
  }
}
```

**News (type = news): pushed again after translation**

```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"
    }
  }
}
```

**Signal (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 (Twitter) KOL post (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
    }
  }
}
```

Events replayed after reconnecting with `after` carry an extra `"replay": true`; everything else is identical.

## Client messages

### op = "subscribe"

Add topics (patterns allowed).

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

### op = "unsubscribe"

Remove topics (patterns allowed; `["*"]` removes every topic and the connection stays open with heartbeats, notices and, if subscribed, my alerts; unsubscribe `my_alerts` explicitly to stop those).

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

### op = "ping"

Client heartbeat; the server answers with pong.

```json
{
  "op": "ping"
}
```

## Why the same item can arrive twice

The first push is the item as detected (`revision = 1`). If its zh/en/ko titles or original link are filled in later (for posts: when the complete version arrives), it is pushed again with the same `id`, a higher `revision` and `action = "updated"`. Deduplicate on (`id`, `revision`) and keep the highest. To decide whether an item is new, check whether you have seen its `id` before rather than relying on `action`: after a reconnect a new item can already be at `revision = 2` (`action = "updated"`).

## Resuming

1. Store `event.id` for every `event` you process.
2. After a disconnect, reconnect with `after=<last id>`.
3. The server first replays new events after that id, then new revisions made after the `after` event was first stored (including the `after` event itself and older events; all marked `replay: true`, up to 200 in total), sends `replay_done`, then continues live. Replays can repeat revisions you already have, so always deduplicate on (`id`, `revision`).
4. `replay_done.truncated = true` means the gap was larger than the limit: disconnect, catch up with REST `after` and `updated_after`, then reconnect.

## Heartbeat

The server sends `ping` when it has pushed no event, my alert or notice (`event` / `alert` / `notice`) for `heartbeat_seconds` (from welcome), so every `heartbeat_seconds` while there are no events (a personal `alert` also restarts the timer). The timer starts after `welcome` (after `replay_done` when you connect with `after`); the server's replies to your own frames (`subscribed`, `pong`, `invalid_message` errors) do not restart it, so a `ping` can arrive right after one of those replies, which is normal. If nothing arrives for two heartbeat periods, treat the connection as dead and reconnect. Back off 1, 2, 4… seconds (up to 60) between attempts; do not reconnect automatically on close codes 4001 / 4003, and after 4029 wait 5 seconds or longer.

## Close codes

| Code | Meaning |
|---|---|
| `4001` | Key missing, invalid, reset, revoked or (trial key) expired (error.code = missing_api_key / invalid_api_key / key_expired). Do not reconnect automatically. |
| `4003` | Not permitted: the plan does not include the Developer API or has expired (error.code = plan_required), or the IP is outside the allowlist (error.code = ip_not_allowed). Do not reconnect automatically; fix the cause first. |
| `4029` | This key's connection allowance is in use; the new connection is refused. Right after closing an old connection the slot can take a few seconds to free up: wait at least 5 seconds before reconnecting and back off exponentially. |
| `4400` | Bad connection parameter: `after` is not a valid event id (error.code = invalid_cursor). Fix it before reconnecting; do not retry unchanged. |
| `4008` | Disconnected as a slow consumer; reconnect with `after`. |
| `1000` | Normal closure. |
| `1001 / 1006 / 1011 / 1012 / 1013` | Server restart, network drop or server error. Reconnect with `after=<last event id>`, backing off 1, 2, 4… seconds up to 60. |

## Edge cases

| Case | Server behaviour |
|---|---|
| Frame is not a JSON object, has no `op`, or an unknown `op` | Replies `{"op":"error","code":"invalid_message"}`; the connection stays open |
| `topics` in subscribe / unsubscribe is empty or not a list of strings | Same `invalid_message` reply; `topics` may also be a comma-separated string |
| `unsubscribe` `["*"]` | Removes every topic (`subscribed.topics = []`); the connection stays open and from then on carries only heartbeats, notices and my alerts if still subscribed (`*` does not include `my_alerts`; unsubscribe `my_alerts` explicitly to stop them) |
| Subscribing to a topic that does not exist | No error; it is listed in `welcome.unknown` / `subscribed.unknown` |
| `topics` empty or omitted when connecting | Subscribes to every readable topic |
| Connecting with only unknown (or only denied) topics | The connection opens with `welcome.topics = []` and those topics listed in `welcome.unknown` (or `welcome.denied`); it receives only heartbeats and notices until you `subscribe` to something |
| Upper / lower case in topic ids | Ignored: `Announcement.Binance` is the same as `announcement.binance` (connection parameter, `subscribe` and REST alike); responses always use lower case |
| Upper / lower case in event ids (`after` and other cursors) | Ignored: hex digits are accepted in either case, as are REST `after` / `before` and `GET /v1/events/{id}`; returned ids are always lower case |
| `after` is not a valid event id | Sends `error` (`invalid_cursor`) and closes with 4400 |
| `after` is well-formed but no such event exists (e.g. past retention) | Replays from that id's position in time, exactly as if it existed |
| `after=` (empty) | Same as no `after`: no replay and no `replay_done` |
| `after` given more than once | Only the last one is used |

## Full examples

**Python**

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

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

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

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

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

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

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

asyncio.run(main())
```

**Node.js**

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

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

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

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

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

**Go**

```go
package main

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

	"github.com/coder/websocket"
)

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