DEV Community

Emily
Emily

Posted on

🛠️ Build a Real-Time API Order Book Imbalance Indicator for Gold and Silver

Hey devs! If you’re crafting a robo-advisor or a trading dashboard for precious metals, you’ve probably hit that moment where users say, “I need to feel the market’s momentum before the candle closes.” That’s your cue to look beyond price and into the order book. In this hands-on walkthrough, I’ll show you how to stream live depth, calculate order book imbalance, and shape it into a feature your users will lean on.

What your users are really asking for
They want order-flow intelligence. Not just the last traded price, but a real-time sense of whether aggressive buyers are stacking beneath the market or whether sellers are building a ceiling. This is microstructural alpha, and it’s entirely within reach with a lightweight computation.

Where typical setups stumble
Grabbing best bid/ask via REST every 200ms is a recipe for whipsaw. You miss the fleeting depth changes that happen between polls, and a single level tells you almost nothing. I once traced a silver bounce where ask₁ was paper-thin, but ask₃ held over 500 lots—a massive hidden resistance. A poll-based design never saw it.

Streaming depth and crunching the numbers
Switch to a WebSocket that pushes depth updates continuously. I’m using the AllTick market data API for gold and silver because it delivers real-time book snapshots without the polling headaches. With the data flowing, you aggregate the total bid and ask volume across multiple levels and compute the Order Book Imbalance (OBI):

OBI = (Total Bid Vol - Total Ask Vol) / (Total Bid Vol + Total Ask Vol)

Simple ratio, rich insight. The table below maps values to market behavior:

State OBI Sign Interpretation
Bids heavier Positive Accumulation zone; possible support building
Asks heavier Negative Distribution zone; overhead resistance growing
Neutral ≈0 Equilibrium; waiting for a catalyst

Here’s a ready-to-run Python snippet. It connects to the WebSocket, extracts the aggregated volumes, and prints the OBI in real time. You can extend it to push the value into a database, a WebSocket broadcast, or a frontend dashboard.

import websocket
import json


def on_message(ws, message):
    data = json.loads(message)

    symbol = data.get("symbol")
    bid_volume = float(data.get("bidVolume", 0))
    ask_volume = float(data.get("askVolume", 0))

    total = bid_volume + ask_volume

    if total > 0:
        imbalance = (bid_volume - ask_volume) / total
    else:
        imbalance = 0

    print(
        symbol,
        "Order Book Imbalance:",
        round(imbalance, 4)
    )


def on_open(ws):
    subscribe_data = {
        "action": "subscribe",
        "symbol": "XAUUSD",
        "type": "depth",
        "id": 1
    }

    ws.send(json.dumps(subscribe_data))


ws = websocket.WebSocketApp(
    "wss://apis.alltick.co/websocket-api/stock-websocket-interface-api/transaction-quote-subscription",
    on_open=on_open,
    on_message=on_message
)

ws.run_forever()
Enter fullscreen mode Exit fullscreen mode

Transforming your app with depth intelligence
Now, think product. Take the OBI stream and build a “depth momentum” widget that shows a smoothed, color-coded gauge. Trigger in-app notifications when the imbalance breaches +0.3 or drops below -0.3. But remember: raw tick-level OBI is noisy. I compute a 10-second rolling mean and only change the displayed state after a sustained shift. Also, buffer incoming ticks and evaluate on a timer so your pipeline doesn’t choke. Keep timestamps consistent—UTC everywhere. With these guardrails, your platform stops being a passive chart viewer and becomes an active market interpreter. Users will start to trust your app’s “sixth sense” because it’s backed by real depth dynamics. Happy building!

Top comments (0)