Streaming price chart representing real-time WebSocket market data

Blog ·

WebSocket Market Data Streaming: Real-Time Prices Without Polling

Polling asks "has anything changed?" again and again. WebSocket market data streaming turns that around: you subscribe once and the server pushes each new price the moment it changes. Less traffic, lower latency, simpler code.

How the stream works

  1. Connect to wss://api.marketapi.app/v1/stream with your API key.
  2. Send a subscribe message with the symbols you want.
  3. Receive quote messages with bid, ask, time and status.

Python client

import asyncio, json, os, websockets

async def main():
    url = "wss://api.marketapi.app/v1/stream"
    headers = {"Authorization": "Bearer " + os.environ["API_KEY"]}
    async with websockets.connect(url, additional_headers=headers) as ws:
        await ws.send(json.dumps({"action": "subscribe", "symbols": ["EURUSD", "XAUUSD"]}))
        async for raw in ws:
            m = json.loads(raw)
            if m["type"] == "quote":
                print(m["symbol"], m["bid"], m["ask"], m["time"])

asyncio.run(main())

Node.js client

const WebSocket = require("ws");
const ws = new WebSocket("wss://api.marketapi.app/v1/stream",
  { headers: { Authorization: "Bearer " + process.env.API_KEY } });
ws.on("open", () => ws.send(JSON.stringify({ action: "subscribe", symbols: ["EURUSD"] })));
ws.on("message", raw => console.log(JSON.parse(raw)));

Best practices

  • Reconnect with back-off after network drops; do not retry after authentication or balance errors.
  • Check the status field and ignore quotes that are not LIVE if you trade.
  • Keep keys on servers, never in browser code.

When to use REST instead

Streaming shines for screens that stay open and bots that react instantly. For a page that loads once, a report or a nightly job, a single REST request is simpler and cheaper. Many apps combine both: REST for the first render, WebSocket for updates.

Scaling a streaming client

  • Use one connection with many symbols rather than many connections.
  • Fan out to your own users from your backend instead of giving each user a direct connection with your key.
  • Keep a heartbeat: if no message arrives for a while, reconnect.
  • Unsubscribe from symbols nobody is watching to save credits.

How fast are updates?

Quotes are pushed as soon as the platform receives them; symbols that customers stream are refreshed about every second at the source.

What happens when my balance runs out?

The stream closes with a clear code; top up and reconnect.

Streaming is billed per subscribed symbol per minute; see pricing. Full protocol in the documentation.

Try the market price API

1000 free credits after sign-up.

Get a free API key

More articles