> ## Documentation Index
> Fetch the complete documentation index at: https://sonar-cf3aeac7.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream large trades and wallet activity

> Use the multi-events stream to alert on trades over $100,000 and on trades by watched wallets across Ethereum and Base, with resumable cursors.

This guide builds an alert feed with the [multi-events stream](https://sonar-cf3aeac7.mintlify.site/streams/overview.md). It sends you every trade on Ethereum and Base that is worth \$100,000 or more, **or** that was sent by a wallet on your watch list. It shows the token symbols, works out whether each trade was a buy or a sell, and resumes after a disconnect without missing trades.

You need Node.js 22 or later (for the built-in `WebSocket`), or Python 3 with the `websockets` package.

## 1. Choose the subscription

```json theme={null}
{
  "op": "subscribe",
  "id": "alerts",
  "channel": "multi-events",
  "params": {
    "chains": ["evm:1", "evm:8453"],
    "events": ["swap-enriched"],
    "filters": {
      "or": [
        { "gte": ["tokenAmountUsd", 100000] },
        { "in": ["sender", [
          "0x6121f0e92f2514beaa3d73c671cc3ba246724895",
          "0x5582745e183cfc16288678e29f7a1ae4ad8b00ad"
        ]] }
      ]
    }
  }
}
```

* `chains` uses the `evm:<chainId>` form. Bare numbers are rejected.
* `swap-enriched` adds `baseTokenData` and `quoteTokenData` with name, symbol, decimals and logo, so you don't need a separate token lookup. It contains every field of `swap`, so there is no reason to request both.
* `tokenAmountUsd` checks the trade's `amountUSD`. Comparisons need a JSON number, not a string.
* `sender` checks the trade's `initiator`: the wallet that sent the transaction. Up to 500 wallets fit in one `in` list.

See [Subscribing](https://sonar-cf3aeac7.mintlify.site/streams/subscribing.md) and [Filters](https://sonar-cf3aeac7.mintlify.site/streams/filters.md) for every option.

### What it costs

The connection budget is 100 cost units. This subscription has two pairs, `swap-enriched|evm:1` and `swap-enriched|evm:8453`, and each costs **10**, for a total of **20**.

Each pair is chain-wide because of the `or`. A filter that only names wallets would cost 1 per pair, since the server only has to look at those wallets' trades. But the `gte` branch doesn't name any address, so the server must check every trade on the chain against the threshold, and an `or` with one such branch is chain-wide as a whole.

Splitting it into two subscriptions doesn't make it cheaper: a threshold subscription costs 2 × 10 = 20 and a wallet subscription 2 × 1 = 2, total 22. Split it only if you want each rule under its own subscription id. Adding the plain `swap` kind would double the cost to 40. See [Limits and subscription cost](https://sonar-cf3aeac7.mintlify.site/streams/limits-and-cost.md).

## 2. Read the trades

Each match arrives as an `event`. With two pairs, the event has a `pair` field and a `cursor`:

```json theme={null}
{
  "type": "event",
  "id": "alerts",
  "channel": "multi-events",
  "pair": "swap-enriched|evm:1",
  "cursor": "26745120-0:3",
  "data": {
    "event": "swap-enriched",
    "chainId": "evm:1",
    "blockNumber": 26745120,
    "timestamp": 1796306723000,
    "hash": "0xbb7ce5c3afbaa8efb27bf846d21168e4cb76fd20607a4077cb81a211c0b0059b",
    "pool": "0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640",
    "poolType": "uniswap-v3",
    "initiator": "0x6121f0e92f2514beaa3d73c671cc3ba246724895",
    "token0": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    "token1": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
    "rawAmount0": "250000000000",
    "rawAmount1": "-71428571428571428571",
    "amount0": 250000,
    "amount1": -71.42857142857143,
    "priceUSD0": 1,
    "priceUSD1": 3500,
    "amountUSD": 250000,
    "baseToken": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
    "baseTokenData": { "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "name": "Wrapped Ether", "symbol": "WETH", "decimals": 18, "logo": null, "priceUSD": 3500 },
    "quoteTokenData": { "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "name": "USD Coin", "symbol": "USDC", "decimals": 6, "logo": null, "priceUSD": 1 },
    "...": "other swap fields"
  }
}
```

The payload has no buy or sell field. Work it out from the base token's raw amount: positive means the token went into the pool, so the trader **sold** it; otherwise the trader **bought** it. Then:

* **Amount:** the absolute value of `amount0` or `amount1` on the base token's side.
* **Price:** `baseTokenData.priceUSD`, which is the price at this trade. If `baseTokenData` is `null`, use `priceUSD0` or `priceUSD1`.
* **USD value:** `amountUSD`.
* **Symbol:** `baseTokenData.symbol`. Token data can be `null` when the token isn't known yet or the lookup was slow, so fall back to the address.

The example above reads: *Ethereum: 0x6121…4895 bought 71.43 WETH for $250,000 at $3,500.*

See [Event payloads](https://sonar-cf3aeac7.mintlify.site/streams/event-payloads.md) for every field.

## 3. Keep cursors and resume

Store the newest cursor of each pair. Cursors arrive in three places:

* `subscribed` has a `cursors` map with the starting cursor of each pair.
* Every `event` has a `cursor` for its `pair`.
* Every 30 seconds, a `cursor` message moves each pair forward, even when nothing matched. A rare filter like this one depends on these checkpoints to resume after a quiet period.

After a disconnect, subscribe again with the same `params` and a `since` map:

```json theme={null}
{
  "op": "subscribe",
  "id": "alerts",
  "channel": "multi-events",
  "params": { "...": "same params as before" },
  "since": {
    "swap-enriched|evm:1": "26745135-0",
    "swap-enriched|evm:8453": "55410388-0:12"
  }
}
```

The server replays the matching trades you missed, then continues live with no duplicates. History is kept for about 10 minutes. If a cursor is older, the whole subscription is refused with `RESUME_EXPIRED`, and `details.pairs` lists the expired pairs. Drop those pairs from `since` and subscribe again. See [Cursors and resuming](https://sonar-cf3aeac7.mintlify.site/streams/cursors-and-resume.md).

## Full example

The client below prints alerts, saves cursors to `cursors.json` so it can resume after a restart, and reconnects with backoff.

```js JavaScript theme={null}
// Save as alerts.mjs and run with: node alerts.mjs
import { existsSync, readFileSync, writeFileSync } from "node:fs";

const URL = "wss://api.example.com/streams/v1/ws";
const WATCHED = [
  "0x6121f0e92f2514beaa3d73c671cc3ba246724895",
  "0x5582745e183cfc16288678e29f7a1ae4ad8b00ad",
];
const THRESHOLD_USD = 100_000;
const CHAIN_NAMES = { "evm:1": "Ethereum", "evm:8453": "Base" };

const params = {
  chains: ["evm:1", "evm:8453"],
  events: ["swap-enriched"],
  filters: {
    or: [
      { gte: ["tokenAmountUsd", THRESHOLD_USD] },
      { in: ["sender", WATCHED] },
    ],
  },
};

const FILE = "cursors.json";
const cursors = existsSync(FILE) ? JSON.parse(readFileSync(FILE, "utf8")) : {};
const save = () => writeFileSync(FILE, JSON.stringify(cursors));

function subscribe(ws) {
  const since = Object.keys(cursors).length > 0 ? cursors : undefined;
  ws.send(JSON.stringify({ op: "subscribe", id: "alerts", channel: "multi-events", params, since }));
}

function alert(s) {
  const base = s.baseToken;
  const isToken0 = base === s.token0;
  const raw = BigInt(isToken0 ? s.rawAmount0 : s.rawAmount1);
  const side = raw > 0n ? "sold" : "bought";
  const amount = Math.abs(isToken0 ? s.amount0 : s.amount1);
  const price = s.baseTokenData?.priceUSD ?? (isToken0 ? s.priceUSD0 : s.priceUSD1);
  const symbol = s.baseTokenData?.symbol ?? base;
  const reasons = [];
  if (s.amountUSD >= THRESHOLD_USD) reasons.push("large trade");
  if (WATCHED.includes(s.initiator)) reasons.push("watched wallet");
  console.log(
    `[${reasons.join(", ")}] ${CHAIN_NAMES[s.chainId] ?? s.chainId}: ${s.initiator} ${side} ` +
    `${amount.toLocaleString()} ${symbol} for $${Math.round(s.amountUSD).toLocaleString()} ` +
    `at $${price} (tx ${s.hash})`,
  );
}

let attempt = 0;
function connect() {
  const ws = new WebSocket(URL);
  ws.onopen = () => subscribe(ws);
  ws.onmessage = ({ data }) => {
    const msg = JSON.parse(data);
    switch (msg.type) {
      case "subscribed":
        attempt = 0;
        Object.assign(cursors, msg.cursors);
        save();
        break;
      case "event":
        alert(msg.data);
        cursors[msg.pair] = msg.cursor;
        save();
        break;
      case "cursor":
        cursors[msg.pair] = msg.cursor;
        save();
        break;
      case "gap":
        console.warn(`${msg.pair}: blocks ${msg.fromBlock}-${msg.toBlock} were skipped by the stream`);
        break;
      case "error":
        if (msg.code === "RESUME_EXPIRED") {
          for (const pair of Object.keys(msg.details.pairs)) delete cursors[pair];
          save();
          subscribe(ws);
        } else {
          console.error(msg.code, msg.message, msg.details);
        }
        break;
    }
  };
  ws.onclose = () => setTimeout(connect, Math.min(30_000, 1000 * 2 ** attempt++));
}

connect();
```

```python Python theme={null}
# pip install websockets
import asyncio, json, os
import websockets

URL = "wss://api.example.com/streams/v1/ws"
WATCHED = [
    "0x6121f0e92f2514beaa3d73c671cc3ba246724895",
    "0x5582745e183cfc16288678e29f7a1ae4ad8b00ad",
]
THRESHOLD_USD = 100_000
CHAIN_NAMES = {"evm:1": "Ethereum", "evm:8453": "Base"}
PARAMS = {
    "chains": ["evm:1", "evm:8453"],
    "events": ["swap-enriched"],
    "filters": {"or": [
        {"gte": ["tokenAmountUsd", THRESHOLD_USD]},
        {"in": ["sender", WATCHED]},
    ]},
}

FILE = "cursors.json"
cursors = json.load(open(FILE)) if os.path.exists(FILE) else {}

def save():
    with open(FILE, "w") as f:
        json.dump(cursors, f)

def subscribe_message():
    msg = {"op": "subscribe", "id": "alerts", "channel": "multi-events", "params": PARAMS}
    if cursors:
        msg["since"] = cursors
    return json.dumps(msg)

def alert(s):
    is_token0 = s["baseToken"] == s["token0"]
    raw = int(s["rawAmount0"] if is_token0 else s["rawAmount1"])
    side = "sold" if raw > 0 else "bought"
    amount = abs(s["amount0"] if is_token0 else s["amount1"])
    data = s.get("baseTokenData")
    price = data["priceUSD"] if data else (s["priceUSD0"] if is_token0 else s["priceUSD1"])
    symbol = data["symbol"] if data else s["baseToken"]
    reasons = []
    if s["amountUSD"] >= THRESHOLD_USD:
        reasons.append("large trade")
    if s["initiator"] in WATCHED:
        reasons.append("watched wallet")
    chain = CHAIN_NAMES.get(s["chainId"], s["chainId"])
    print(f"[{', '.join(reasons)}] {chain}: {s['initiator']} {side} {amount:,.4f} {symbol} "
          f"for ${s['amountUSD']:,.0f} at ${price} (tx {s['hash']})")

async def run():
    delay = 1
    while True:
        try:
            async with websockets.connect(URL) as ws:
                await ws.send(subscribe_message())
                async for raw in ws:
                    msg = json.loads(raw)
                    kind = msg["type"]
                    if kind == "subscribed":
                        delay = 1
                        cursors.update(msg.get("cursors", {}))
                        save()
                    elif kind == "event":
                        alert(msg["data"])
                        cursors[msg["pair"]] = msg["cursor"]
                        save()
                    elif kind == "cursor":
                        cursors[msg["pair"]] = msg["cursor"]
                        save()
                    elif kind == "gap":
                        print(f"{msg['pair']}: blocks {msg['fromBlock']}-{msg['toBlock']} were skipped")
                    elif kind == "error":
                        if msg["code"] == "RESUME_EXPIRED":
                            for pair in msg["details"]["pairs"]:
                                cursors.pop(pair, None)
                            save()
                            await ws.send(subscribe_message())
                        else:
                            print("error", msg["code"], msg["message"], msg.get("details"))
        except (websockets.WebSocketException, OSError):
            pass
        await asyncio.sleep(delay)
        delay = min(delay * 2, 30)

asyncio.run(run())
```

The example saves after every message to keep it short. In production, save every few seconds or on shutdown; at worst you replay a few alerts you already handled. Deduplicate by `hash` and `logIndex` if that matters.

If you change the chains or event kinds, delete the saved cursors for pairs that no longer exist. Sending a pair the new params don't produce fails with `Unknown pairs in since`.

## Optional: backfill a gap or an expired resume

Two situations leave holes in the feed:

* A `gap` message: the stream skipped the listed blocks on that chain, inclusive, and won't send their trades.
* `RESUME_EXPIRED`: you were disconnected for longer than the stream's history.

[`GET /trades`](https://sonar-cf3aeac7.mintlify.site/api-reference/trades/get-trades) reads trades from storage and can fill a hole when you know **which token or pool** to look at. It takes a token or pool `address`, a `chain`, and a time window in Unix milliseconds (`from`, `to`), not block numbers. Use the `timestamp` of your last trade before the hole and of the first one after it.

```bash theme={null}
curl "https://api.example.com/api/v1/trades?chain=evm:1&address=0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640&from=1796306400000&to=1796306760000&order=asc&limit=100"
```

* Pages hold up to 100 trades. For the next page, pass the `cursor` of the last trade with the same query, and stop when a page has fewer than `limit` trades.
* The REST trade shape differs from the stream payload: it is oriented to one token and has `tokenAmountUsd`, `type` (`buy` or `sell`) and `sender` fields. Apply your threshold and wallet list to those fields.
* For a token address, only the token's two most active pools are searched. Query by pool address when you can.

There is no REST endpoint that lists all trades of a chain or all trades of a wallet, so a chain-wide threshold or a wallet list can't be fully backfilled. Keep your client connected and resume within the history window to avoid holes.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.