Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Read the Live Order Book with OpenAlgo Market Depth

10 min read

OpenAlgo market depth: two uneven stacks of blank tiles facing a narrow gap on a navy field

A price chart tells you where trades happened. The order book tells you who is still waiting: the buy orders resting below the last price, the sell orders resting above it, and how much quantity sits at each step. OpenAlgo market depth gives you that book in two ways: a one-shot REST snapshot, and a live stream over its WebSocket.

In this tutorial you will use both from Python, record live five-level depth for three NSE stocks during the last half hour of a trading session, and turn it into two simple numbers: the spread and the order book imbalance.

A quick disclosure: OpenAlgo is an open source project created by the founder of Marketcalls.

OpenAlgo Desktop: algo trading on your own computer

WINDOWS, MAC AND LINUX

OpenAlgo Desktop: algo trading on your own computer

Install, sign in, connect your broker and trade. No server to set up and no Python to install.

  • Same API and screens as OpenAlgo web
  • Strategy module, charting and scalping terminals
  • Keys stay encrypted on your machine

What you need

  • A running OpenAlgo server with your broker logged in. The REST API listens on port 5000 and the WebSocket on port 8765 by default.
  • Your OpenAlgo API key, kept in an environment variable rather than in the script.
  • Python with the OpenAlgo SDK. This run used openalgo 2.3.0 on Python 3.13.
pip install -U openalgo pandas plotly kaleido
export OPENALGO_API_KEY="your_api_key"

Everything here is read-only. No order is placed. Our server was in Analyze (sandbox) mode the whole time, and that is fine: Analyze mode simulates your orders and positions, but prices and depth still come live from the connected broker.

Step 1: Take a depth snapshot

The quickest way to see the book is client.depth(). It returns the top five bids and asks, plus the day’s open, high, low, last price and volume.

import os
from openalgo import api

client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
             host="http://127.0.0.1:5000")

r = client.depth(symbol="RELIANCE", exchange="NSE")
book = r["data"]
print("Best bid:", book["bids"][0])
print("Best ask:", book["asks"][0])
print("Visible buy qty:", book["totalbuyqty"], " sell qty:", book["totalsellqty"])

At 14:59:52 IST on 26 November, our snapshot for RELIANCE came back with the best bid at Rs 1,399.90 for 227 shares and the best ask at Rs 1,400.00 for 1,048 shares. That gap of Rs 0.10 is the spread.

One detail worth checking on your own setup: on this run, totalbuyqty (9,210) and totalsellqty (6,220) were exactly the sum of the five visible levels. The docs example shows larger totals, so what these fields cover can depend on the broker feed. Print both and compare before you rely on them.

A snapshot suits a dashboard refresh or a quick check. After market hours, a REST depth snapshot does not return a usable book. The five bid and ask slots are still there, but most levels come back at price 0 with quantity 0, and any leftover row is one-sided and stale. Take the snapshot while the session is open, or record the WebSocket stream during market hours.

The book also changes many times a second, and polling REST in a loop is the wrong tool for that. The WebSocket is the right one.

Step 2: Stream the live OpenAlgo market depth

OpenAlgo runs one WebSocket for every broker it supports, with the same message format for all of them. The SDK wraps it in three calls: connect(), subscribe_depth() and unsubscribe_depth().

import os, json, time
from openalgo import api

client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
             host="http://127.0.0.1:5000",
             ws_url="ws://127.0.0.1:8765")

instruments = [{"exchange": "NSE", "symbol": "RELIANCE"},
               {"exchange": "NSE", "symbol": "HDFCBANK"},
               {"exchange": "NSE", "symbol": "INFY"}]

out = open("depth_ticks.jsonl", "a")

def on_depth(msg):
    # Keep callbacks short: just save the update
    out.write(json.dumps(msg) + "\n")

print("connected:", client.connect())
client.subscribe_depth(instruments, on_data_received=on_depth)
try:
    time.sleep(25 * 60)          # record for 25 minutes
finally:
    client.unsubscribe_depth(instruments)
    client.disconnect()
    out.close()

Each update arrives as a small dictionary: the symbol and exchange, mode 3 (depth), and a data block holding ltp, a timestamp in epoch milliseconds, and depth with five buy and five sell levels. Every level has a price, a quantity and the number of orders behind it.

Two notes from the docs. First, connect() returning True means you are connected and authenticated, and subscribe_depth() returning True means the request was sent. Neither guarantees every symbol was accepted, so check that ticks are arriving. Second, the SDK keeps only ltp, timestamp and depth in its depth messages. If you need extra fields from the raw frame, or more than five levels where your broker offers them, talk to the WebSocket protocol directly.

Our recording started at 14:58:27 IST on 26 November and collected 6,140 depth updates across the three stocks, roughly three to four updates per second each.

Step 3: Check that the data is fresh

A stream that is still sending messages is not always sending fresh prices. The docs advise checking timestamps and freshness, and our recording shows why.

import pandas as pd

last_change = {}
prev = {}
for line in open("depth_ticks.jsonl"):
    m = json.loads(line)
    s, ltp = m["symbol"], m["data"]["ltp"]
    if prev.get(s) != ltp:
        last_change[s] = pd.to_datetime(m["data"]["timestamp"], unit="ms",
                                        utc=True).tz_convert("Asia/Kolkata")
        prev[s] = ltp
print(last_change)

For all three stocks, the last traded price stopped changing at 15:14:59 IST. Depth messages kept coming, but the prices in them barely moved, and a REST quote at 15:25 IST showed the same frozen last prices. So we kept only the live window, 14:58:27 to 15:14:59 IST: 5,475 updates, about 1,800 per stock. Build a check like this into anything that reads a stream.

Step 4: Draw the book

Here is RELIANCE’s book at one moment from that recording, the first update at or after 15:10:00 IST. Green bars are buy orders waiting below the market, red bars are sell orders waiting above it.

At that moment the best bid was Rs 1,396.40 and the best ask Rs 1,396.50, a spread of Rs 0.10. The five buy levels held 11,554 shares against 3,113 on the sell side. One sell level held just 3 shares from 2 orders, while the deepest buy level held 5,171 shares from 46 orders. A few seconds later this picture had already changed.

The order counts matter as much as the quantities. A big level built from one order can be cancelled with one click. A level built from dozens of orders is usually more stable.

Step 5: Turn depth into two numbers

Ladders are hard to compare over time, so we boil each update down to two numbers.

  • Spread: best ask minus best bid. A tight spread means it costs little to cross the book.
  • Top-5 imbalance: (bid quantity minus ask quantity) divided by (bid quantity plus ask quantity), using the five visible levels. It runs from -1 (all quantity on the sell side) to +1 (all on the buy side).
rows = []
for line in open("depth_ticks.jsonl"):
    m = json.loads(line)
    buy, sell = m["data"]["depth"]["buy"], m["data"]["depth"]["sell"]
    bid_qty = sum(l["quantity"] for l in buy)
    ask_qty = sum(l["quantity"] for l in sell)
    if not buy or not sell or bid_qty == 0 or ask_qty == 0:
        continue                 # skip empty or partial books
    rows.append({
        "symbol": m["symbol"],
        "ts": pd.to_datetime(m["data"]["timestamp"], unit="ms", utc=True)
                .tz_convert("Asia/Kolkata"),
        "spread": sell[0]["price"] - buy[0]["price"],
        "imbalance": (bid_qty - ask_qty) / (bid_qty + ask_qty),
    })

df = pd.DataFrame(rows)
df = df[df["ts"] < "2026-11-26 15:15:00+05:30"]   # live window only
print(df.groupby("symbol").agg(median_spread=("spread", "median"),
                                avg_imbalance=("imbalance", "mean")))

# 15-second averages for charting
imb = (df.set_index("ts").groupby("symbol")["imbalance"]
         .resample("15s").mean().dropna())

Skipping empty books is not optional. Indices have no tradable depth, and a feed can briefly send a side with zero quantity. Counting those as real readings would distort every average.

Here is how the three stocks looked over the live window.

StockUpdatesMedian spreadMedian spread (bps)Average imbalanceUpdates leaning to bids
HDFCBANK1,855Rs 0.101.16+0.0352%
INFY1,797Rs 0.201.69-0.0544%
RELIANCE1,823Rs 0.201.43+0.0960%

A basis point (bps) is a hundredth of a percent, which makes spreads comparable across stocks with very different prices. All three were trading with spreads of under two basis points, which is what you expect from large, liquid names.

And this is the imbalance in 15-second averages.

Even after averaging over 15 seconds, the sign flipped 14 to 19 times per stock in under 17 minutes. RELIANCE leaned to the buy side in 47 of the 67 buckets, yet its last price slipped from Rs 1,399.20 to Rs 1,396.00 over the window. INFY leaned to the sell side more often than not and still ended higher, from Rs 1,176.20 to Rs 1,181.20.

What depth can and cannot tell you

Depth is a view of intentions, not commitments. Orders can be added, modified or pulled at any moment, and a five-level view is only the edge of the full book. Imbalance flips sign often, as the chart shows, and on its own it is not a trading signal. Treat it as context: a way to see how thick or thin the book is around the last price and how fast that changes.

Where this gets useful is in your own tooling. You can log spreads to see when a stock is cheapest to trade, flag moments when the book thins out, or feed the numbers into a strategy you test properly before it goes anywhere near the market. Your First Backtest with the OpenAlgo Python SDK: EMA Crossover and Build Smarter Backtest Signals with OpenAlgo Indicators walk through that testing path, and Supertrend Backtest on SBIN with the OpenAlgo Python SDK is another complete example. For a contribution-style backtest rather than a signal-based one, see Backtest Any SIP with the OpenAlgo SIP Backtester.

Wrapping up

You have seen both doors into OpenAlgo market depth: client.depth() for a quick snapshot, and subscribe_depth() on the WebSocket for a live stream with the same format across brokers. From there, spread and imbalance are a few lines of pandas.

Next, try subscribing to a stock you follow, record a full session, and see how its spread behaves at the open compared with the last hour.

Full code

Here is the complete script. It reads your API key and host from environment variables (OPENALGO_API_KEY, OPENALGO_HOST, and optionally OPENALGO_WS_URL), records raw depth messages to a JSONL file, then builds the spread, the imbalance and the two charts shown above. Set RECORD_SECONDS=0 to skip recording and only analyse an existing file.

# Read the live order book with OpenAlgo market depth
# Read-only: no orders are placed.
# Set OPENALGO_API_KEY in your environment. Optionally set OPENALGO_HOST
# (default http://127.0.0.1:5000) and OPENALGO_WS_URL (default is derived
# from the host, port 8765).
#
# RECORD_SECONDS  how long to record (default 1500 = 25 minutes).
#                 Set 0 to skip recording and only analyse an existing file.
# TICK_FILE       JSONL path for raw depth messages (one SDK msg per line).
# CUTOFF          drop updates at or after this clock time, IST (default 15:15:00).
# LADDER_TIME     clock time, IST, for the ladder snapshot (default 15:10:00).
import os
import json
import time
from urllib.parse import urlparse

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from openalgo import api

API_KEY = os.getenv("OPENALGO_API_KEY", "your_api_key")
HOST = os.getenv("OPENALGO_HOST", "http://127.0.0.1:5000")


def default_ws_url(host):
    parsed = urlparse(host)
    scheme = "wss" if parsed.scheme == "https" else "ws"
    hostname = parsed.hostname or "127.0.0.1"
    return f"{scheme}://{hostname}:8765"


WS_URL = os.getenv("OPENALGO_WS_URL", default_ws_url(HOST))
RECORD_SECONDS = int(os.getenv("RECORD_SECONDS", str(25 * 60)))
CUTOFF = os.getenv("CUTOFF", "15:15:00")
LADDER_TIME = os.getenv("LADDER_TIME", "15:10:00")
LADDER_SYMBOL = os.getenv("LADDER_SYMBOL", "RELIANCE")

HERE = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else os.getcwd()
if os.path.basename(HERE) == "scripts":
    DATA = os.path.join(HERE, "..", "data")
    IMG = os.path.join(HERE, "..", "images")
else:
    DATA = os.path.join(HERE, "data") if os.path.isdir(os.path.join(HERE, "data")) else HERE
    IMG = os.path.join(HERE, "images")
os.makedirs(DATA, exist_ok=True)
os.makedirs(IMG, exist_ok=True)
TICK_FILE = os.getenv("TICK_FILE", os.path.join(DATA, "depth_ticks.jsonl"))

client = api(api_key=API_KEY, host=HOST, ws_url=WS_URL)

instruments = [{"exchange": "NSE", "symbol": "RELIANCE"},
               {"exchange": "NSE", "symbol": "HDFCBANK"},
               {"exchange": "NSE", "symbol": "INFY"}]

# --- REST snapshot (often an empty or hollow book after market hours) ---
r = client.depth(symbol="RELIANCE", exchange="NSE")
book = r["data"]
bids, asks = book.get("bids") or [], book.get("asks") or []
live_bids = [row for row in bids if row.get("price") and row.get("quantity")]
live_asks = [row for row in asks if row.get("price") and row.get("quantity")]
print("REST snapshot bids:", live_bids[:1], "asks:", live_asks[:1])
if not live_bids or not live_asks:
    print("REST depth snapshot is empty or one-sided. After market hours the "
          "five bid and ask slots are still returned, but most levels come "
          "back at price 0 with quantity 0. Record the stream during market hours.")

# --- Record the live WebSocket stream as raw SDK messages (one JSON object per line) ---
if RECORD_SECONDS > 0:
    out = open(TICK_FILE, "a")

    def on_depth(msg):
        # Keep callbacks short: just save the update
        out.write(json.dumps(msg) + "\n")

    print("connected:", client.connect())
    print("subscribe sent:", client.subscribe_depth(instruments, on_data_received=on_depth))
    try:
        time.sleep(RECORD_SECONDS)
    finally:
        client.unsubscribe_depth(instruments)
        client.disconnect()
        out.close()
    print("recorded to", TICK_FILE)

# --- Analyse the raw JSONL and draw the charts ---
if not os.path.exists(TICK_FILE) or os.path.getsize(TICK_FILE) == 0:
    print("No ticks in", TICK_FILE, "- nothing to analyse.")
    raise SystemExit(0)

last_change = {}
prev = {}
rows = []
with open(TICK_FILE) as fh:
    for line in fh:
        line = line.strip()
        if not line:
            continue
        m = json.loads(line)
        s, ltp = m["symbol"], m["data"]["ltp"]
        if prev.get(s) != ltp:
            last_change[s] = pd.to_datetime(m["data"]["timestamp"], unit="ms",
                                            utc=True).tz_convert("Asia/Kolkata")
            prev[s] = ltp
        buy, sell = m["data"]["depth"]["buy"], m["data"]["depth"]["sell"]
        bid_qty = sum(level["quantity"] for level in buy)
        ask_qty = sum(level["quantity"] for level in sell)
        if not buy or not sell or bid_qty == 0 or ask_qty == 0:
            continue  # skip empty or partial books
        ts = pd.to_datetime(m["data"]["timestamp"], unit="ms",
                            utc=True).tz_convert("Asia/Kolkata")
        rows.append({
            "symbol": m["symbol"],
            "ts": ts,
            "ltp": ltp,
            "spread": sell[0]["price"] - buy[0]["price"],
            "imbalance": (bid_qty - ask_qty) / (bid_qty + ask_qty),
            "bid_qty": bid_qty,
            "ask_qty": ask_qty,
            "buy": buy,
            "sell": sell,
        })

print("last LTP change:", last_change)

df = pd.DataFrame(rows)
if df.empty:
    print("No usable depth rows to chart.")
    raise SystemExit(0)

day = df.ts.iloc[0].strftime("%Y-%m-%d")
cutoff_ts = pd.Timestamp(f"{day} {CUTOFF}", tz="Asia/Kolkata")
df = df[df["ts"] < cutoff_ts]
print(df.groupby("symbol").agg(updates=("spread", "size"),
                               median_spread=("spread", "median"),
                               avg_imbalance=("imbalance", "mean")))

# 15-second averages for charting
imb = (df.set_index("ts").groupby("symbol")["imbalance"]
         .resample("15s").mean().dropna())

FONT = dict(family="Georgia, 'Times New Roman', serif", size=24, color="#1f2933")
BG = "#fbfaf7"


def mark(fig, y=1.11):
    fig.add_annotation(text="openalgo.in", xref="paper", yref="paper", x=1.0, y=y,
                       xanchor="right", yanchor="bottom", showarrow=False,
                       font=dict(size=20, color="#7b8794"))


def lab(qty, orders):
    return f"{qty:,}  ({orders} order{'' if orders == 1 else 's'})"


# Chart 1: the 5-level ladder at the first tick at or after LADDER_TIME
g = df[df.symbol == LADDER_SYMBOL]
t = pd.Timestamp(f"{day} {LADDER_TIME}", tz="Asia/Kolkata")
snap = g[g.ts >= t].iloc[0] if (g.ts >= t).any() else g.iloc[-1]
bids = pd.DataFrame(snap.buy)
asks = pd.DataFrame(snap.sell)
ymax_qty = float(max(bids.quantity.max(), asks.quantity.max()))
# Short bars would otherwise place their quantity label on top of the price tick.
# Keep every label at least this far into the plot so tiny levels stay readable.
min_label_x = max(400.0, ymax_qty * 0.08)

price_order = [f"{p:,.2f}" for p in list(bids.price[::-1]) + list(asks.price)]
fig = go.Figure()
fig.add_trace(go.Bar(y=[f"{p:,.2f}" for p in asks.price[::-1]], x=asks.quantity[::-1],
                     orientation="h", name="Sell orders (asks)",
                     marker_color="#d64545"))
fig.add_trace(go.Bar(y=[f"{p:,.2f}" for p in bids.price], x=bids.quantity,
                     orientation="h", name="Buy orders (bids)",
                     marker_color="#1b9e52"))
for price, qty, orders in zip(list(asks.price[::-1]) + list(bids.price),
                              list(asks.quantity[::-1]) + list(bids.quantity),
                              list(asks.orders[::-1]) + list(bids.orders)):
    fig.add_annotation(x=max(float(qty), min_label_x), y=f"{price:,.2f}",
                       text=lab(int(qty), int(orders)), showarrow=False,
                       xanchor="left", xshift=8, font=dict(size=20, color="#1f2933"))
fig.update_layout(template="plotly_white", font=FONT, paper_bgcolor=BG,
                  plot_bgcolor=BG, width=1600, height=1000,
                  title=dict(text=(f"{LADDER_SYMBOL} five-level order book at "
                                   f"{snap.ts:%H:%M:%S} IST, {snap.ts:%d %b %Y}"),
                             font=dict(size=32), x=0.02, y=0.97),
                  xaxis_title="Quantity (shares)", yaxis_title="Price (Rs)", bargap=0.25,
                  legend=dict(orientation="h", y=1.0, x=0.0, yanchor="bottom"),
                  margin=dict(l=160, r=60, t=170, b=90))
fig.update_yaxes(type="category", categoryorder="array", categoryarray=price_order,
                 tickfont=dict(size=22))
fig.update_xaxes(gridcolor="#e4e7eb", tickformat=",",
                 range=[0, ymax_qty * 1.35])
fig.add_annotation(text=f"Spread Rs {snap.spread:.2f}   |   Top-5 imbalance {snap.imbalance:+.2f}",
                   xref="paper", yref="paper", x=0.98, y=0.5, xanchor="right",
                   showarrow=False, font=dict(size=24, color="#3e4c59"),
                   bgcolor="#ffffff", bordercolor="#cbd2d9", borderwidth=1, borderpad=10)
mark(fig)
ladder_path = os.path.join(IMG, "order_book_ladder.png")
fig.write_image(ladder_path)
print("ladder snapshot:", LADDER_SYMBOL, snap.ts, "ltp=", snap.ltp,
      "spread=", f"{snap.spread:.2f}", "imb=", f"{snap.imbalance:+.3f}")
print("buy=", snap.buy)
print("sell=", snap.sell)

# Chart 2: 15-second average imbalance per symbol
syms = sorted(df.symbol.unique())
fig2 = make_subplots(rows=len(syms), cols=1, shared_xaxes=True,
                     vertical_spacing=0.06, subplot_titles=syms)
for i, symbol in enumerate(syms, 1):
    series = imb[symbol] if symbol in imb.index.get_level_values(0) else (
        df[df.symbol == symbol].set_index("ts")["imbalance"].resample("15s").mean().dropna()
    )
    # imb is a Series with MultiIndex (symbol, ts) after groupby resample
    if isinstance(imb.index, pd.MultiIndex):
        series = imb.xs(symbol)
    fig2.add_trace(go.Bar(x=series.index, y=series.values,
                          marker_color=["#1b9e52" if v > 0 else "#d64545" for v in series.values],
                          name=symbol, showlegend=False), row=i, col=1)
    fig2.add_hline(y=0, line_color="#52606d", line_width=1.5, row=i, col=1)
    fig2.update_yaxes(range=[-1, 1], tickvals=[-1, -0.5, 0, 0.5, 1],
                      gridcolor="#e4e7eb", tickfont=dict(size=20), row=i, col=1)
fig2.update_layout(template="plotly_white", font=FONT, paper_bgcolor=BG,
                   plot_bgcolor=BG, width=1600, height=1100,
                   title=dict(text="Top-5 order book imbalance, 15-second averages (green: more resting buy quantity)",
                              font=dict(size=28), x=0.02, y=0.98),
                   bargap=0.1, margin=dict(l=100, r=40, t=150, b=80))
fig2.update_xaxes(showgrid=False, tickformat="%H:%M", tickfont=dict(size=20))
for annotation in fig2.layout.annotations:
    annotation.font = dict(size=24)
    annotation.x = 0.0
    annotation.xanchor = "left"
mark(fig2, y=1.06)
timeline_path = os.path.join(IMG, "imbalance_timeline.png")
fig2.write_image(timeline_path)
print("charts written:", ladder_path, timeline_path)
Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More