# Real-Time Multi-Exchange Order Book Depth for an ERC-20 Token

## Real-Time Multi-Exchange Order Book Depth for an ERC-20 Token

This tutorial shows how to build a small Node.js app that streams real-time order book updates for the same ERC-20 token across multiple exchanges using the CoinAPI Market Data WebSocket.

By the end, the app will:

* connect to the WebSocket feed
* subscribe to `book` updates for one token pair across several exchanges
* maintain the latest order book for each symbol in memory
* handle both full snapshots and incremental updates
* display:
  * top of book per exchange
  * aggregated top of book across exchanges
  * aggregated top 5 bid and ask levels

This is useful for demos involving:

* liquidity comparison across venues
* synthetic aggregated depth
* exchange filtering
* cross-venue monitoring for the same asset

In the stream, some messages provide a full snapshot of the current book, while others contain only updates to specific levels. For example, your GATEIO sample is a snapshot with `is_snapshot: true`, `sequence: 1`, and a full set of bid and ask levels for `GATEIO_SPOT_LINK_USDT`.



## What you will build

For this tutorial, the app will subscribe to these symbols:

* `GATEIO_SPOT_LINK_USDT`
* `BINANCE_SPOT_LINK_USDT`
* `OKEX_SPOT_LINK_USDT`
* `BYBITSPOT_SPOT_LINK_USDT`

You can replace them later with other ERC-20 USDT symbols if needed.

## How book messages are handled

Each incoming `book` message belongs to one `symbol_id`.

There are two message types to handle:

### Snapshot message

When `is_snapshot` is `true`:

* clear the stored bids and asks for that symbol
* insert all levels from the message
* store the sequence number

### Incremental update

When `is_snapshot` is `false`:

* keep the existing stored book
* update only the price levels present in the message
* remove a price level if its incoming `size` is `0`
* store the new sequence number

This lets the application maintain the latest book state for each symbol over time.

## Prerequisites

You need:

* Node.js installed
* a CoinAPI API key
* terminal access

This tutorial uses the Market Data WebSocket endpoint:

```
wss://ws.coinapi.io/v1/
```

## Step 1 — Create the project folder

Open your terminal and run:

```sh
mkdir multi-exchange-orderbook-demo
cd multi-exchange-orderbook-demo
```

## Step 2 — Create `package.json`

Create a new file named `package.json` and paste this into it:

```json
{
  "name":"multi-exchange-orderbook-demo",
  "version":"1.0.0",
  "description":"Real-time multi-exchange order book depth demo using CoinAPI",
  "main":"index.js",
  "type":"commonjs",
  "dependencies": {
    "dotenv":"^16.4.5",
    "ws":"^8.18.0"
  }
}
```

Save the file.

## Step 3 — Install dependencies

Run:

```sh
npm install
```

This installs:

* `ws` for the WebSocket client
* `dotenv` for loading your API key from a `.env` file

## Step 4 — Create `.env`

Create a new file named `.env` and paste this into it:

```
COINAPI_KEY=YOUR_API_KEY_HERE
```

Replace YOUR_API_KEY_HERE with your actual API key, then save the file.

## Step 5 — Create `index.js`

Create a new file named `index.js` and paste the full script below.

```javascript
require("dotenv").config();
const WebSocket = require("ws");
const fs = require("fs");

const API_KEY = process.env.COINAPI_KEY;
const WS_URL = "wss://ws.coinapi.io/v1/";

if (!API_KEY) {
  console.error("Missing COINAPI_KEY in .env file");
  process.exit(1);
}

// Symbols to subscribe to.
const SUBSCRIBED_SYMBOLS = [
  "GATEIO_SPOT_LINK_USDT",
  "BINANCE_SPOT_LINK_USDT",
  "OKEX_SPOT_LINK_USDT",
  "BYBITSPOT_SPOT_LINK_USDT"
];

// Exchanges to include in the aggregated output.
const ENABLED_EXCHANGES = ["GATEIO", "BINANCE", "OKEX", "BYBITSPOT"];

// Optional snapshot logging.
const SAVE_SNAPSHOTS_TO_FILE = true;
const SNAPSHOT_FILE = "orderbook_snapshots.jsonl";
const SNAPSHOT_INTERVAL_MS = 5000;

// One in-memory reconstructed book per symbol_id.
const booksBySymbol = {};

function getExchangeId(symbolId) {
  return symbolId.split("_")[0];
}

function ensureBook(symbolId) {
  if (!booksBySymbol[symbolId]) {
    booksBySymbol[symbolId] = {
      exchange_id: getExchangeId(symbolId),
      symbol_id: symbolId,
      sequence: 0,
      bids: {},
      asks: {},
      last_time_exchange: null,
      last_time_coinapi: null
    };
  }
}

function applyLevels(levels, sideStore) {
  if (!Array.isArray(levels)) return;

  for (const level of levels) {
    const price = String(level.price);
    const size = Number(level.size);

    if (size === 0) {
      delete sideStore[price];
    } else {
      sideStore[price] = size;
    }
  }
}

function processBookMessage(msg) {
  const symbolId = msg.symbol_id;
  ensureBook(symbolId);

  const book = booksBySymbol[symbolId];

  // Ignore duplicate or older messages.
  if (msg.sequence <= book.sequence) {
    return;
  }

  // Snapshot messages replace the stored state for this symbol.
  if (msg.is_snapshot === true) {
    book.bids = {};
    book.asks = {};
  }

  // Apply the incoming changes.
  applyLevels(msg.bids, book.bids);
  applyLevels(msg.asks, book.asks);

  book.sequence = msg.sequence;
  book.last_time_exchange = msg.time_exchange || null;
  book.last_time_coinapi = msg.time_coinapi || null;
}

function toSortedBidArray(book) {
  return Object.entries(book.bids)
    .map(([price, size]) => ({ price: Number(price), size: Number(size) }))
    .filter((level) => level.size > 0)
    .sort((a, b) => b.price - a.price);
}

function toSortedAskArray(book) {
  return Object.entries(book.asks)
    .map(([price, size]) => ({ price: Number(price), size: Number(size) }))
    .filter((level) => level.size > 0)
    .sort((a, b) => a.price - b.price);
}

function getTopOfBook(book) {
  const bids = toSortedBidArray(book);
  const asks = toSortedAskArray(book);

  return {
    best_bid: bids[0] || null,
    best_ask: asks[0] || null
  };
}

function getFilteredBooks() {
  return Object.values(booksBySymbol).filter((book) =>
    ENABLED_EXCHANGES.includes(book.exchange_id)
  );
}

function aggregateBooks(books) {
  const aggregatedBids = {};
  const aggregatedAsks = {};

  for (const book of books) {
    for (const level of toSortedBidArray(book)) {
      const key = String(level.price);
      aggregatedBids[key] = (aggregatedBids[key] || 0) + level.size;
    }

    for (const level of toSortedAskArray(book)) {
      const key = String(level.price);
      aggregatedAsks[key] = (aggregatedAsks[key] || 0) + level.size;
    }
  }

  const bids = Object.entries(aggregatedBids)
    .map(([price, size]) => ({ price: Number(price), size: Number(size) }))
    .filter((level) => level.size > 0)
    .sort((a, b) => b.price - a.price);

  const asks = Object.entries(aggregatedAsks)
    .map(([price, size]) => ({ price: Number(price), size: Number(size) }))
    .filter((level) => level.size > 0)
    .sort((a, b) => a.price - b.price);

  return { bids, asks };
}

function printHeader() {
  console.log("=== Real-Time Multi-Exchange Order Book Depth Demo ===");
  console.log("Subscribed symbols:");
  for (const symbol of SUBSCRIBED_SYMBOLS) {
    console.log(`- ${symbol}`);
  }
}

function printPerExchangeTopOfBook(books) {
  console.log("\n=== PER EXCHANGE TOP OF BOOK ===");

  if (books.length === 0) {
    console.log("No book data received yet.");
    return;
  }

  for (const book of books) {
    const top = getTopOfBook(book);

    const bidText = top.best_bid
      ? `${top.best_bid.price} (${top.best_bid.size})`
      : "-";

    const askText = top.best_ask
      ? `${top.best_ask.price} (${top.best_ask.size})`
      : "-";

    console.log(`${book.exchange_id} | Bid: ${bidText} | Ask: ${askText}`);
  }
}

function printAggregatedTopOfBook(aggregated) {
  console.log("\n=== AGGREGATED TOP OF BOOK ===");
  console.log("Best Bid:", aggregated.bids[0] || null);
  console.log("Best Ask:", aggregated.asks[0] || null);
}

function printDepth(levels, label, count = 5) {
  console.log(`\n=== ${label} ===`);

  if (levels.length === 0) {
    console.log("No levels available.");
    return;
  }

  for (const level of levels.slice(0, count)) {
    console.log(`${level.price} | ${level.size}`);
  }
}

function getLatestCoinapiTime(books) {
  const times = books
    .map((book) => book.last_time_coinapi)
    .filter(Boolean)
    .sort();

  return times.length > 0 ? times[times.length - 1] : null;
}

function printLastUpdateTime(books) {
  const latest = getLatestCoinapiTime(books);
  if (!latest) return;

  console.log(`\nLast CoinAPI update time: ${latest}`);
}

function saveSnapshotToFile() {
  const filteredBooks = getFilteredBooks();
  if (filteredBooks.length === 0) return;

  const aggregated = aggregateBooks(filteredBooks);

  const snapshot = {
    saved_at: new Date().toISOString(),
    books: filteredBooks.map((book) => ({
      exchange_id: book.exchange_id,
      symbol_id: book.symbol_id,
      sequence: book.sequence,
      last_time_exchange: book.last_time_exchange,
      last_time_coinapi: book.last_time_coinapi,
      top_of_book: getTopOfBook(book)
    })),
    aggregated_top_of_book: {
      best_bid: aggregated.bids[0] || null,
      best_ask: aggregated.asks[0] || null
    },
    aggregated_top_5_bids: aggregated.bids.slice(0, 5),
    aggregated_top_5_asks: aggregated.asks.slice(0, 5)
  };

  fs.appendFileSync(SNAPSHOT_FILE, JSON.stringify(snapshot) + "\n");
}

function render() {
  const filteredBooks = getFilteredBooks();
  const aggregated = aggregateBooks(filteredBooks);

  console.clear();
  printHeader();
  printPerExchangeTopOfBook(filteredBooks);
  printAggregatedTopOfBook(aggregated);
  printDepth(aggregated.bids, "AGGREGATED TOP 5 BIDS", 5);
  printDepth(aggregated.asks, "AGGREGATED TOP 5 ASKS", 5);
  printLastUpdateTime(filteredBooks);
  console.log("\nPress CTRL + C to stop.");
}

if (SAVE_SNAPSHOTS_TO_FILE) {
  setInterval(() => {
    saveSnapshotToFile();
  }, SNAPSHOT_INTERVAL_MS);
}

const ws = new WebSocket(WS_URL);

ws.on("open", () => {
  console.log("Connected to CoinAPI WebSocket");

  const helloMessage = {
    type: "hello",
    apikey: API_KEY,
    subscribe_data_type: ["book"],
    subscribe_filter_symbol_id: SUBSCRIBED_SYMBOLS
  };

  ws.send(JSON.stringify(helloMessage));
  console.log("Subscription sent");
  console.log("Waiting for live book messages...");
});

ws.on("message", (raw) => {
  try {
    const msg = JSON.parse(raw.toString());

    if (msg.type !== "book") {
      return;
    }

    processBookMessage(msg);
    render();
  } catch (error) {
    console.error("Failed to parse incoming message:", error.message);
  }
});

ws.on("error", (error) => {
  console.error("WebSocket error:", error.message);
});

ws.on("close", () => {
  console.log("WebSocket connection closed");
});
```

Save the file.

## Step 6 — Run the script

Run:

```sh
node index.js
```

## Step 7 — What happens when the script runs

The script will:

1. connect to the Market Data WebSocket
2. subscribe to the configured symbols
3. receive `book` messages in real time
4. rebuild the latest order book for each symbol in memory
5. print:
  * top of book per exchange
  * aggregated best bid and best ask
  * aggregated top 5 bids and asks

If file logging is enabled, it will also append periodic snapshots to `orderbook_snapshots.jsonl`.

## Step 8 — Sample terminal output

Because this is live data, your output will differ. A sample output might look like this:

```
=== Real-Time Multi-Exchange Order Book Depth Demo ===
Subscribed symbols:
- GATEIO_SPOT_LINK_USDT
- BINANCE_SPOT_LINK_USDT
- OKEX_SPOT_LINK_USDT
- BYBITSPOT_SPOT_LINK_USDT

=== PER EXCHANGE TOP OF BOOK ===
GATEIO | Bid: 8.48 (14.2) | Ask: 8.52 (18.7)
BINANCE | Bid: 8.49 (3250.44) | Ask: 8.51 (2811.03)
OKEX | Bid: 8.47 (422.18) | Ask: 8.53 (390.26)
BYBITSPOT | Bid: 8.48 (611.55) | Ask: 8.52 (704.31)

=== AGGREGATED TOP OF BOOK ===
Best Bid: { price: 8.49, size: 3250.44 }
Best Ask: { price: 8.51, size: 2811.03 }

=== AGGREGATED TOP 5 BIDS ===
8.49 | 3250.44
8.48 | 625.75
8.47 | 422.18
8.46 | 980.5
8.45 | 150.2

=== AGGREGATED TOP 5 ASKS ===
8.51 | 2811.03
8.52 | 723.01
8.53 | 390.26
8.54 | 505.6
8.55 | 118.3

Last CoinAPI update time: 2026-03-30T14:00:24.4474047Z

Press CTRL + C to stop.
```

## Step 9 — Where the data comes from

You do not need to copy JSON into files manually.

The script receives live messages directly from the WebSocket stream in this handler:

```javascript
ws.on("message", (raw) => {
  const msg = JSON.parse(raw.toString());
  ...
})
```

Those messages are processed in memory as they arrive.

## Step 10 — Where the data is saved

There are two outputs:

### Terminal output

The latest view is printed in the terminal continuously.

### Optional file output

If `SAVE_SNAPSHOTS_TO_FILE` is set to `true`, the script also saves snapshots to:

```
orderbook_snapshots.jsonl
```

Each line in that file is a JSON object.

If you do not want file output, change:

```javascript
const SAVE_SNAPSHOTS_TO_FILE = true;
```

to:

```javascript
const SAVE_SNAPSHOTS_TO_FILE = false;
```

## Step 11 — How to stop the script

The script runs continuously because it listens to a live WebSocket stream.

To stop it, press:

```
CTRL+ C
```

## Step 13 — Change the symbols later

To test a different ERC-20 asset, edit this block in `index.js`:

```javascript
const SUBSCRIBED_SYMBOLS = [
  "GATEIO_SPOT_LINK_USDT",
  "BINANCE_SPOT_LINK_USDT",
  "OKEX_SPOT_LINK_USDT",
  "BYBITSPOT_SPOT_LINK_USDT"
];
```

For example, to use UNI instead:

```javascript
const SUBSCRIBED_SYMBOLS = [
  "GATEIO_SPOT_UNI_USDT",
  "BINANCE_SPOT_UNI_USDT",
  "OKEX_SPOT_UNI_USDT",
  "BYBIT_SPOT_UNI_USDT"
];
```

Then save the file and run.

## Step 14 — Change which exchanges are included in aggregation

To exclude an exchange from the aggregated output, edit this line:

```javascript
const ENABLED_EXCHANGES = ["GATEIO", "BINANCE", "OKEX", "BYBITSPOT"];
```

For example:

```javascript
const ENABLED_EXCHANGES = ["BINANCE", "OKEX", "BYBITSPOT"];
```

This will keep the script subscribed to all configured symbols, but the aggregated output will only include the exchanges listed here.

## Step 15 — Troubleshooting

### Missing API key

If you see:

```
Missing COINAPI_KEY in .env 
```

check that:

* the file name is `.env`
* the key is written as `COINAPI_KEY=...`
* the file is saved

### No book output appears

Possible reasons:

* one or more symbol IDs are not active
* the symbols are not covered in your environment
* there have not been recent updates yet

Try a different base asset such as UNI or CRV.

### A side of the book looks empty

This can happen briefly at startup before both sides have been initialized for all symbols. Once snapshot and update messages arrive, the book should fill in.

### Old values overwrite new ones

This script avoids that by checking the sequence number and ignoring older or duplicate messages.



## See It in Action

Below is a short example of the script running with two exchanges.

This shows how order book updates arrive in real time and how the aggregated view updates continuously.

👉 [Watch the demo here.](https://drive.google.com/file/d/1wMhXmnCcSDBL9ncNUTHbrzM0ND6jcJxh/view?usp=sharing)

> Note: For demonstration purposes, the video uses 2 symbols only to keep updates readable.

## Congratulations!

You now have a working, real-time, multi-exchange order book depth application.

In this tutorial, you were able to:

* connect to the CoinAPI Market Data WebSocket
* subscribe to live `book` updates across multiple exchanges
* handle both snapshot and incremental messages correctly
* maintain a continuously updated order book in memory per symbol
* compute and display top-of-book per exchange
* build an aggregated view of bid/ask depth across venues
* optionally persist snapshots for further analysis

This setup reflects how real-world systems consume and process streaming market data. Instead of relying on static responses, your application continuously updates its state based on incoming events, allowing you to monitor liquidity and pricing across exchanges in real time.

From here, you can extend this further by:

* visualizing depth with charts
* tracking spread differences across exchanges
* detecting arbitrage opportunities
* estimating slippage for different trade sizes
* storing historical snapshots in a database

You now have a solid foundation for building more advanced market data applications on top of real-time streams.