# Latency Comparison Between Exchanges

## Latency Comparison Between Exchanges

## Overview

This tutorial shows how to measure and compare **data latency across exchanges** using CoinAPI’s Market Data WebSocket.

By the end, you will build a Node.js script that:

* connects to the WebSocket stream
* subscribes to real-time data from multiple exchanges
* calculates latency per message using:
  * `time_exchange` (when the event happened at the exchange)
  * `time_coinapi` (when CoinAPI processed it)
* aggregates latency per exchange
* displays:
  * latest latency
  * average latency
  * min / max latency

#### What latency means in this context

Each message includes:

* `time_exchange` → timestamp from the exchange
* `time_coinapi` → timestamp when CoinAPI processed the data

#### Latency calculation:

Latency = time_coinapi - time_exchange  


This measures:

* exchange → CoinAPI ingestion delay
* normalization / processing delay

👉 It does **NOT** include your local network latency.

#### What you will build

You will compare latency across exchanges for BTC:

* `BINANCE_SPOT_BTC_USDT`
* `OKEX_SPOT_BTC_USDT`
* `BYBIT_SPOT_BTC_USDT`

These are highly active markets, which makes them ideal for observing latency behavior.

## Prerequisites

* Node.js installed
* CoinAPI API key
* Terminal access

WebSocket endpoint:

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

## Step 1 — Create project folder

```sh
mkdir latency-comparison-demo
cd latency-comparison-demo
```

## Step 2 — Create `package.json`

```json
{
  "name":"latency-comparison-demo",
  "version":"1.0.0",
  "description":"Latency comparison across exchanges using CoinAPI WebSocket",
  "main":"index.js",
  "type":"commonjs",
  "dependencies": {
    "dotenv":"^16.4.5",
    "ws":"^8.18.0"
  }
}
```

## Step 3 — Install dependencies

```sh
npm install
```

## Step 4 — Create `.env`

```
COINAPI_KEY=YOUR_API_KEY_HERE
```

## Step 5 — Create index.js

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

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

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

// -------------------------------------
// CONFIG
// -------------------------------------

const SYMBOLS = [
  "BINANCE_SPOT_BTC_USDT",
  "OKEX_SPOT_BTC_USDT",
  "BYBIT_SPOT_BTC_USDT"
];

const RENDER_INTERVAL_MS = 1000;

// -------------------------------------
// STORAGE
// -------------------------------------

const exchangeStats = {};

// -------------------------------------
// HELPERS
// -------------------------------------

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

function ensureExchange(exchange) {
  if (!exchangeStats[exchange]) {
    exchangeStats[exchange] = {
      count: 0,
      totalLatency: 0,
      minLatency: Infinity,
      maxLatency: -Infinity,
      lastLatency: null
    };
  }
}

function calculateLatency(msg) {
  const tExchange = Date.parse(msg.time_exchange);
  const tCoinapi = Date.parse(msg.time_coinapi);

  if (!tExchange || !tCoinapi) return null;

  return tCoinapi - tExchange;
}

function updateStats(exchange, latency) {
  ensureExchange(exchange);

  const stats = exchangeStats[exchange];

  stats.count += 1;
  stats.totalLatency += latency;
  stats.lastLatency = latency;

  if (latency < stats.minLatency) stats.minLatency = latency;
  if (latency > stats.maxLatency) stats.maxLatency = latency;
}

function getAverageLatency(stats) {
  if (stats.count === 0) return 0;
  return stats.totalLatency / stats.count;
}

// -------------------------------------
// RENDER
// -------------------------------------

function render() {
  process.stdout.write("\x1Bc");

  console.log("=== Exchange Latency Comparison (BTC) ===\n");

  for (const [exchange, stats] of Object.entries(exchangeStats)) {
    const avg = getAverageLatency(stats);

    console.log(`${exchange}`);
    console.log(`  Last Latency: ${stats.lastLatency?.toFixed(2)} ms`);
    console.log(`  Avg Latency:  ${avg.toFixed(2)} ms`);
    console.log(`  Min Latency:  ${stats.minLatency.toFixed(2)} ms`);
    console.log(`  Max Latency:  ${stats.maxLatency.toFixed(2)} ms`);
    console.log(`  Messages:     ${stats.count}`);
    console.log("");
  }

  console.log("Press CTRL + C to stop.");
}

// -------------------------------------
// WEBSOCKET
// -------------------------------------

const ws = new WebSocket(WS_URL);

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

  ws.send(JSON.stringify({
    type: "hello",
    apikey: API_KEY,
    subscribe_data_type: ["trade"],
    subscribe_filter_symbol_id: SYMBOLS
  }));

  console.log("Subscribed to BTC markets");
});

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

    if (msg.type !== "trade") return;

    const latency = calculateLatency(msg);
    if (latency === null) return;

    const exchange = getExchange(msg.symbol_id);
    updateStats(exchange, latency);

  } catch (err) {
    console.error("Error:", err.message);
  }
});

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

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

setInterval(render, RENDER_INTERVAL_MS);
```

## Step 6 — Run the script

```sh
node index.js
```

## Step 7 — Sample output

```
=== Exchange Latency Comparison (BTC) ===

BINANCE
  Last Latency: 15.00 ms
  Avg Latency:  18.40 ms
  Min Latency:  10.00 ms
  Max Latency:  40.00 ms
  Messages:     320

OKEX
  Last Latency: 32.00 ms
  Avg Latency:  38.75 ms
  Min Latency:  20.00 ms
  Max Latency:  85.00 ms
  Messages:     290

BYBIT
  Last Latency: 25.00 ms
  Avg Latency:  29.10 ms
  Min Latency:  18.00 ms
  Max Latency:  65.00 ms
  Messages:     305

Press CTRL + C to stop.
```

## Step 8 — What this shows

Using BTC improves:

* message frequency (more data points)
* stability of averages
* clearer comparison between exchanges

You can now easily see:

* which exchange has the lowest latency
* which has spikes (max latency)
* which is most consistent

## Step 9 — Optional improvements

You can extend this by:

* adding latency percentiles (p95, p99)
* plotting latency over time
* detecting spikes automatically
* comparing different data types (`trade`, `quote`, `book`)

## Congratulations!

You now have a real-time BTC-based latency comparison tool.

You were able to:

* stream high-frequency BTC trade data
* calculate latency using timestamps
* aggregate metrics per exchange
* compare performance across venues

This is especially useful for:

* evaluating data quality
* monitoring exchange performance
* identifying latency anomalies