# My alerts

Besides every event of the topics you subscribe to, the API can hand you **exactly the alerts pushed to you**: identical to what your Bark, WeCom and other channels set up in the dashboard receive, filtered by your sources, keywords and alert language. Use it to wire our alerts into your own bots and workflows.

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

## Two kinds of data

|  | Topic events (general stream) | My alerts (this page) |
|---|---|---|
| What you get | **Every** message of the subscribed topics, untouched by personal settings | Only what is **pushed to you**: filtered by your source switches, keywords, alert language and plan delay set in the dashboard |
| Relation to channels | None | The same alerts your Bark, WeCom and other channels receive, one for one |
| Format | Structured events, `op = "event"` (see [Event format](https://tokenearly.com/en/developers/events)) | Alert text plus a few structured fields, `op = "alert"` |
| Languages | zh / en / ko titles in one event; filled-in titles arrive as a new revision | In your alert language: if the original is in another language you get it first (`label = "original"`), then one follow-up with the translation (`followup = true`) |
| How to subscribe | `topics=announcement.binance,news.*` etc. (comma-separated, any combination) | `topics=my_alerts` (a special topic; `*` does not include it) |
| After a disconnect | Reconnect with `after` and the server replays | The stream does not replay; catch up with `GET /v1/alerts?after=` |
| Retention | Your plan's history days | Last 7 days |

> Both can share one WebSocket connection (`topics=my_alerts,announcement.*`); tell them apart by `op`: `event` is a topic event, `alert` a my alert. The same announcement can arrive as an event and as an alert; their ids differ and `ref.event_id` points to the event.

## Turning it on

1. In the dashboard, open Global Notification Management → Notification channels and turn on “Developer API”. While it is off no new notifications are produced (`welcome.my_alerts.channel_enabled` and `channel_enabled` in REST responses tell you).
2. Set up sources, keywords and alert language in the dashboard as usual. Notifications follow those settings exactly; you do not need to tick “Developer API” per source: whenever an alert is pushed to you, the API gets a copy.
3. Connect to `wss://api.tokenearly.com/v1/stream?topics=my_alerts` with any of your API keys, or call [GET /v1/alerts](https://tokenearly.com/en/developers/rest/alerts). Every key of the account sees the same notifications. `my_alerts` is special only on the stream; over REST, `GET /v1/events?topics=my_alerts` treats it as an unknown topic (listed in `access.unknown`), so use `GET /v1/alerts` instead.

> Notifications follow your account's plan delay: real time on paid plans, delayed like your other channels on the free tier.

## Message format

On the stream each one is `{"op": "alert", "alert": {...}}`; REST returns `{"alerts": [...]}` with identical objects.

| Field | Description |
|---|---|
| `id` | Notification id (24 hex digits, grows with time). Use it as the `after` / `before` cursor; not the same as event ids. |
| `category` | Kind of alert: `announcement`, `news`, `twitter`, `signal`, `price_alert`, `contract_movement`. |
| `source` | `{id, name}`: source id (e.g. `binance`, `odaily`, an X account's numeric id) and display name. |
| `followup` | `true` = a follow-up to an alert you already received (e.g. the translation after the original). |
| `lang` | Language of `text` (`zh` / `en` / `ko`) for announcements and news; `null` otherwise. |
| `label` | `original` = sent in the original language because it is not your alert language (a translation follows); `translation` = machine translation; `official_translation` = the source's own version in your language (exchange or news outlet), published later; `null` = already in your language when sent (the source is in that language, or the source had already published its own version in your language before the alert went out), or not applicable (e.g. price alerts). Rely on the `label` and `lang` fields rather than parsing the first line of `text`: the wording of that line follows your alert language, and older alerts use an earlier wording. |
| `title` | Title as shown on your channels, in your alert language: `【币安(BINANCE)】` for Chinese, `[BINANCE]` or `[WallStreetCN]` for English and Korean. |
| `text` | Plain text identical to the body your Bark or WeCom received (with line breaks and the original / translation label line). Only titles are translated: a news summary stays in the source's language unless the source publishes its own version in your language. |
| `url` | The link in the alert; for announcements and news the official page in `lang`. |
| `titles` | Titles available at send time by language (announcements and news), else `null`. |
| `ref` | The topic event this alert is about, `{type, topic, event_id}` (announcements and news); fetch structured data with `GET /v1/events/{event_id}`. `null` for other categories. |
| `created_at` | When it was sent (Unix seconds). |

### Example: the original first (your alert language is Chinese, the announcement is in English)

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

### Example: the follow-up translation (same announcement)

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

The original and the translation of one announcement are two alerts (different `id`) with the same `ref.event_id`. Each language is followed up at most once; if translation fails there is no follow-up (you already have the original). If the original is already in your alert language there is only one, with `label = null`.

### Example: REST response

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

## Catching up after a disconnect

1. Store the `id` of every alert you process.
2. After reconnecting and receiving `welcome`, call `GET /v1/alerts?after=<last id>` (oldest first); while `has_more = true`, continue from the last `id`.
3. The catch-up and live pushes can overlap: dedupe on `id`. Notifications are kept for 7 days; anything older is gone.

## Subscribing and unsubscribing

| Action | How |
|---|---|
| My alerts only | `?topics=my_alerts` |
| My alerts plus topic events | `?topics=my_alerts,announcement.*,news.odaily` |
| Subscribe / unsubscribe later | `{"op":"subscribe","topics":["my_alerts"]}` / `{"op":"unsubscribe","topics":["my_alerts"]}` |
| `unsubscribe` `["*"]` | Removes topic events only; alerts stay (unsubscribe `my_alerts` explicitly to stop them) |

`my_alerts.subscribed` in the `subscribed` reply is the connection's current state.

## 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}"}
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();
```
