# Trade Flow Imbalance Detector

## Trade Flow Imbalance Detector

## Overview

This tutorial shows how to build a real-time **Trade Flow Imbalance Detector** using CoinAPI’s Market Data WebSocket trade stream.

The application will:

* connect to the WebSocket feed
* subscribe to live `trade` messages
* track trades in a rolling window
* calculate buy and sell pressure using `taker_side`
* apply filters so the signal is more reliable
* compare pressure against recent price movement
* print a live signal in the terminal

By the end, the script will help users answer questions like:

* Are buyers or sellers dominating right now?
* Is the pressure strong enough to matter?
* Is price moving in the same direction as the flow?
* Is the signal persistent or only temporary?

### What this detector measures

Each trade includes:

* `price`
* `size`
* `taker_side`

The script uses those fields to calculate:

* **Buy Volume** = sum of sizes where `taker_side = BUY`
* **Sell Volume** = sum of sizes where `taker_side = SELL`
* **Net Imbalance** = `Buy Volume - Sell Volume`
* **Imbalance Ratio** = `(Buy Volume - Sell Volume) / (Buy Volume + Sell Volume)`

A positive ratio means buyer-initiated trades dominate.

A negative ratio means seller-initiated trades dominate.

To make the output more useful, this tutorial adds:

* a minimum trade count
* a signal persistence rule
* price confirmation

### What you will build

This tutorial uses one active symbol to keep the output readable:

* `BINANCE_SPOT_AAVE_USDT`

You can replace it later with another symbol.

### 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 trade-flow-imbalance-demo
cd trade-flow-imbalance-demo
```

## Step 2 — Create `package.json`

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

```json
{
  "name":"trade-flow-imbalance-demo",
  "version":"1.0.0",
  "description":"Real-time trade flow imbalance detector using CoinAPI WebSocket",
  "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 `.env`

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

// -------------------------------------
// CONFIGURATION
// -------------------------------------

// Start with one symbol to keep the output easy to read.
const SUBSCRIBED_SYMBOLS = [
  "BINANCE_SPOT_AAVE_USDT"
];

// Rolling trade window.
const WINDOW_MS = 30_000;

// Require at least this many trades in the current window
// before showing a directional signal.
const MIN_TRADES_IN_WINDOW = 20;

// Require the same directional condition to hold
// for this many consecutive render cycles before
// escalating to a stronger signal.
const REQUIRED_PERSISTENCE_CYCLES = 3;

// Re-render terminal every second even if no new trades arrive.
// This keeps the rolling window current.
const RENDER_INTERVAL_MS = 1000;

// -------------------------------------
// IN-MEMORY STATE
// -------------------------------------

const trades = [];
const signalHistory = [];

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

function parseTradeTime(msg) {
  const parsed = Date.parse(msg.time_coinapi || msg.time_exchange);
  return Number.isNaN(parsed) ? null : parsed;
}

function addTrade(msg) {
  const timeMs = parseTradeTime(msg);
  if (timeMs === null) return;

  trades.push({
    symbol_id: msg.symbol_id,
    time_ms: timeMs,
    price: Number(msg.price),
    size: Number(msg.size),
    taker_side: msg.taker_side,
    sequence: msg.sequence
  });
}

function pruneOldTrades(nowMs) {
  const cutoff = nowMs - WINDOW_MS;

  while (trades.length > 0 && trades[0].time_ms < cutoff) {
    trades.shift();
  }
}

function calculateMetrics() {
  let buyVolume = 0;
  let sellVolume = 0;
  let buyCount = 0;
  let sellCount = 0;
  let firstPrice = null;
  let lastPrice = null;
  let buyNotional = 0;
  let sellNotional = 0;

  for (const trade of trades) {
    if (firstPrice === null) {
      firstPrice = trade.price;
    }
    lastPrice = trade.price;

    const notional = trade.price * trade.size;

    if (trade.taker_side === "BUY") {
      buyVolume += trade.size;
      buyCount += 1;
      buyNotional += notional;
    } else if (trade.taker_side === "SELL") {
      sellVolume += trade.size;
      sellCount += 1;
      sellNotional += notional;
    }
  }

  const totalVolume = buyVolume + sellVolume;
  const totalTrades = buyCount + sellCount;
  const netImbalance = buyVolume - sellVolume;
  const imbalanceRatio = totalVolume > 0 ? netImbalance / totalVolume : 0;

  const priceChange = firstPrice !== null && lastPrice !== null
    ? lastPrice - firstPrice
    : 0;

  const priceChangePct = firstPrice !== null && firstPrice !== 0
    ? (priceChange / firstPrice) * 100
    : 0;

  return {
    buyVolume,
    sellVolume,
    buyCount,
    sellCount,
    totalTrades,
    totalVolume,
    netImbalance,
    imbalanceRatio,
    firstPrice,
    lastPrice,
    priceChange,
    priceChangePct,
    buyNotional,
    sellNotional
  };
}

function getRawPressureDirection(metrics) {
  if (metrics.totalTrades < MIN_TRADES_IN_WINDOW) {
    return "INSUFFICIENT_DATA";
  }

  if (metrics.imbalanceRatio >= 0.25) return "STRONG_BUY";
  if (metrics.imbalanceRatio >= 0.10) return "BUY";
  if (metrics.imbalanceRatio <= -0.25) return "STRONG_SELL";
  if (metrics.imbalanceRatio <= -0.10) return "SELL";
  return "BALANCED";
}

function updateSignalHistory(rawDirection) {
  signalHistory.push(rawDirection);

  if (signalHistory.length > REQUIRED_PERSISTENCE_CYCLES) {
    signalHistory.shift();
  }
}

function hasPersistentDirection(direction) {
  if (signalHistory.length < REQUIRED_PERSISTENCE_CYCLES) {
    return false;
  }

  return signalHistory.every((value) => value === direction);
}

function getFlowComment(metrics, rawDirection) {
  const priceUp = metrics.priceChangePct > 0.02;
  const priceDown = metrics.priceChangePct < -0.02;

  if (rawDirection === "INSUFFICIENT_DATA") {
    return "Not enough trades in the current window yet.";
  }

  if (rawDirection === "STRONG_BUY" || rawDirection === "BUY") {
    if (priceUp) return "Buy pressure is aligned with rising price.";
    if (priceDown) return "Buy pressure is present, but price is falling. Possible absorption or lag.";
    return "Buy pressure is present, but price is mostly flat.";
  }

  if (rawDirection === "STRONG_SELL" || rawDirection === "SELL") {
    if (priceDown) return "Sell pressure is aligned with falling price.";
    if (priceUp) return "Sell pressure is present, but price is rising. Possible absorption or lag.";
    return "Sell pressure is present, but price is mostly flat.";
  }

  return "Trade flow is relatively balanced.";
}

function getFinalSignal(metrics) {
  const rawDirection = getRawPressureDirection(metrics);
  updateSignalHistory(rawDirection);

  if (rawDirection === "INSUFFICIENT_DATA") {
    return {
      rawDirection,
      label: "Insufficient Data",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  if (rawDirection === "BALANCED") {
    return {
      rawDirection,
      label: "Balanced Flow",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  // Require persistence before keeping the stronger classifications.
  if (!hasPersistentDirection(rawDirection)) {
    if (rawDirection === "STRONG_BUY" || rawDirection === "BUY") {
      return {
        rawDirection,
        label: "Buy Pressure (Unconfirmed)",
        comment: "Buy pressure is present, but it has not persisted long enough yet."
      };
    }

    if (rawDirection === "STRONG_SELL" || rawDirection === "SELL") {
      return {
        rawDirection,
        label: "Sell Pressure (Unconfirmed)",
        comment: "Sell pressure is present, but it has not persisted long enough yet."
      };
    }
  }

  if (rawDirection === "STRONG_BUY") {
    return {
      rawDirection,
      label: "Strong Buy Pressure",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  if (rawDirection === "BUY") {
    return {
      rawDirection,
      label: "Buy Pressure",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  if (rawDirection === "STRONG_SELL") {
    return {
      rawDirection,
      label: "Strong Sell Pressure",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  if (rawDirection === "SELL") {
    return {
      rawDirection,
      label: "Sell Pressure",
      comment: getFlowComment(metrics, rawDirection)
    };
  }

  return {
    rawDirection,
    label: "Balanced Flow",
    comment: getFlowComment(metrics, rawDirection)
  };
}

function render() {
  const nowMs = Date.now();
  pruneOldTrades(nowMs);

  const metrics = calculateMetrics();
  const signal = getFinalSignal(metrics);

  process.stdout.write("\x1Bc");
  console.log("=== Trade Flow Imbalance Detector ===");
  console.log("Subscribed symbols:");
  for (const symbol of SUBSCRIBED_SYMBOLS) {
    console.log(`- ${symbol}`);
  }

  console.log(`\nRolling window: last ${WINDOW_MS / 1000} seconds`);
  console.log(`Minimum trades required: ${MIN_TRADES_IN_WINDOW}`);
  console.log(`Trades in window: ${metrics.totalTrades}`);
  console.log(`Window start price: ${metrics.firstPrice ?? "-"}`);
  console.log(`Window last price:  ${metrics.lastPrice ?? "-"}`);

  console.log("\n=== VOLUME ===");
  console.log(`Buy Volume:   ${metrics.buyVolume.toFixed(8)}`);
  console.log(`Sell Volume:  ${metrics.sellVolume.toFixed(8)}`);
  console.log(`Total Volume: ${metrics.totalVolume.toFixed(8)}`);

  console.log("\n=== TRADE COUNT ===");
  console.log(`Buy Trades:   ${metrics.buyCount}`);
  console.log(`Sell Trades:  ${metrics.sellCount}`);

  console.log("\n=== PRICE CONTEXT ===");
  console.log(`Price Change:     ${metrics.priceChange.toFixed(8)}`);
  console.log(`Price Change %:   ${metrics.priceChangePct.toFixed(4)}%`);

  console.log("\n=== IMBALANCE ===");
  console.log(`Net Imbalance:    ${metrics.netImbalance.toFixed(8)}`);
  console.log(`Imbalance Ratio:  ${metrics.imbalanceRatio.toFixed(4)}`);
  console.log(`Signal:           ${signal.label}`);
  console.log(`Interpretation:   ${signal.comment}`);

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

const ws = new WebSocket(WS_URL);

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

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

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

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

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

    addTrade(msg); // only store data
  } catch (error) {
    console.error("Failed to parse message:", error.message);
  }
});

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

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

// Render on a timer so the rolling window remains accurate
// even during quieter periods.
setInterval(render, RENDER_INTERVAL_MS);
```

Save the file.

## Step 6 — Understand the incoming trade message

A trade message from CoinAPI includes fields like:

```json
{
  "type": "trade",
  "symbol_id": "BITSTAMP_SPOT_BTC_USD",
  "sequence": 2323346,
  "time_exchange": "2013-09-28T22:40:50.0000000Z",
  "time_coinapi": "2013-09-28T22:40:52.3763342Z",
  "uuid": "770C7A3B-7258-4441-8182-83740F3E2457",
  "price": 770.000000000,
  "size": 0.050000000,
  "taker_side": "BUY"
}
```

CoinAPI’s docs and examples show this same trade event structure, including `taker_side`, `price`, `size`, `symbol_id`, timestamps, and `sequence`.

For this tutorial:

* `size` is the amount traded
* `taker_side` decides whether the trade counts as buy flow or sell flow
* `time_coinapi` is used for the rolling window
* `price` is shown as the latest price in the terminal

## Step 7 — Run the script

In your project folder, run:

```sh
node index.js
```

You should see:

```
Connected to CoinAPI WebSocket
Subscription sent
Waiting for live trade messages...
```

After trades begin streaming, the terminal will update continuously.

## Step 8 — What the script does in real time

Once running, the script:

1. connects to the WebSocket endpoint
2. subscribes to `trade` data for your selected symbol
3. receives trades as they happen
4. stores them temporarily in memory
5. removes trades outside the rolling window
6. calculates:
  * buy volume
  * sell volume
  * trade counts
  * price change within the window
  * imbalance ratio
7. evaluates the signal using:
  * minimum trade threshold
  * persistence check
  * price context
8. prints a live summary every second

## Step 9 — Sample terminal output

Because this uses live data, your output will vary. A sample might look like:

```
=== Trade Flow Imbalance Detector ===
Subscribed symbols:
- BINANCE_SPOT_AAVE_USDT

Rolling window: last 30 seconds
Minimum trades required: 20
Trades in window: 58
Window start price: 96.52
Window last price:  96.34

=== VOLUME ===
Buy Volume:   132.88000000
Sell Volume:  241.19000000
Total Volume: 374.07000000

=== TRADE COUNT ===
Buy Trades:   21
Sell Trades:  37

=== PRICE CONTEXT ===
Price Change:     -0.18000000
Price Change %:   -0.1864%

=== IMBALANCE ===
Net Imbalance:    -108.31000000
Imbalance Ratio:  -0.2896
Signal:           Strong Sell Pressure
Interpretation:   Sell pressure is aligned with falling price.

Press CTRL + C to stop.
```

This output shows:

* more sell trades than buy trades
* higher sell volume
* negative imbalance ratio
* price moving downward

Together, these indicate consistent sell-side pressure.

## Step 10 — How the rolling window works

The script only considers trades within a recent time window:

```javascript
const WINDOW_MS = 30_000;
```

This means:

* only trades from the last **30 seconds** are used
* older trades are removed continuously

This keeps the signal focused on **recent activity**.

#### Why this matters

* short window → faster but noisier
* longer window → smoother but slower

## Step 11 — Why minimum trade count is used

The script requires a minimum number of trades:

```javascript
const MIN_TRADES_IN_WINDOW = 20;
```

#### Purpose

* avoids signals based on very few trades
* prevents misleading results on low activity

If the number of trades is below this threshold, the signal will show:

```
Signal: Insufficient Data
```

##   
Step 12 — Why persistence is used

The script checks whether the same directional signal appears repeatedly before confirming it.

```javascript
const REQUIRED_PERSISTENCE_CYCLES = 3;
```

#### Purpose

* avoids reacting to brief spikes
* ensures the signal is sustained

Without this, a single burst of trades could incorrectly appear as a strong signal.

## Step 13 — Why price context is included

The script compares:

* first price in the window
* last price in the window

This allows it to determine whether:

* pressure aligns with price movement
* or if there is divergence

#### Examples

* sell pressure + price dropping → strong confirmation
* sell pressure + price rising → possible absorption
* buy pressure + flat price → weak signal

This adds important context to the imbalance.

## Step 14 — Change the symbol

To use a different asset, edit this section:

```javascript
const SUBSCRIBED_SYMBOLS = [
  "BINANCE_SPOT_AAVE_USDT"
];
```

Example:

```javascript
const SUBSCRIBED_SYMBOLS = [
  "BINANCE_SPOT_BTC_USDT"
];
```

## Step 15 — Adjust sensitivity

You can tune the detector depending on your needs.

#### Faster, more reactive

```javascript
const WINDOW_MS = 10_000;
```

#### More stable

```javascript
const WINDOW_MS = 60_000;
```

#### Lower activity markets

```javascript
const MIN_TRADES_IN_WINDOW = 10;
```

#### High-confidence signals

```javascript
const MIN_TRADES_IN_WINDOW = 30;
```

#### Stricter persistence

```javascript
const REQUIRED_PERSISTENCE_CYCLES = 5;
```

## Step 16 — Troubleshooting

#### No trades appearing

* try a more active symbol
* check symbol format

#### Signal stuck at “Insufficient Data”

* lower minimum trade threshold
* or increase window size

#### Output updates too quickly

* increase window size
* increase persistence cycles

## Step 17 — Project structure

Your folder should look like:

trade-flow-imbalance-demo/  
├── .env  
├── index.js  
├── package-lock.json  
└── package.json  


## Congratulations!

You now have a real-time Trade Flow Imbalance Detector that goes beyond basic volume tracking.

You were able to:

* stream live trade data using WebSocket
* classify trades into buy and sell pressure
* calculate imbalance in a rolling time window
* filter out weak signals using minimum trade thresholds
* confirm signals using persistence
* interpret pressure using price movement

This creates a more reliable and practical signal that can be used for:

* short-term market monitoring
* momentum confirmation
* identifying potential turning points

From here, you can extend this by:

* adding charts for visualization
* tracking multiple symbols separately
* triggering alerts when strong pressure persists
* combining this with order book data for deeper analysis

You now have a solid foundation for building real-time trade flow analytics.