Contents
Binance Websocket streams give real-time crypto market data with low delay. They are useful for traders, bot developers, and analysts who need live price updates instead of slow REST polling.
This guide explains how Binance Websocket streams work, how to connect, which streams to use, and how to handle data in a stable way.
What Is a Binance Websocket Stream?
A Binance Websocket stream is a continuous data feed sent over a WebSocket connection. After you connect once, Binance pushes new data to you without extra requests. This saves bandwidth and reduces delay for time-sensitive tasks such as scalping, market-making, or alert systems.
Public streams give market data, while private streams send account and order updates. Both use similar WebSocket technology but different endpoints and authentication steps.
Public vs Private Streams
Before building anything, decide what type of data you need. This choice decides which endpoints and messages you must handle.
Public Websocket Streams
Public streams do not need authentication. They stream market data that anyone can read. A few common examples are useful in most projects.
- Trade streams: Real-time trades for a symbol (for example,
btcusdt@trade). - Kline (candlestick) streams: OHLCV candles for timeframes such as 1m, 5m, 1h.
- Ticker streams: Price changes, best bid/ask, 24h stats.
- Depth (order book) streams: Live bids and asks for each symbol.
These streams are enough for dashboards, price widgets, and many kinds of trading bots that do not need account data.
Private Websocket Streams
Private streams send account-specific data. They use a user data stream and a listen key. The API generates this key through a signed REST request. After that, the WebSocket connection uses this listen key.
Private streams can send new order updates, trade fills, canceled orders, and balance changes. They are critical if a bot needs quick reaction to fills or needs to keep a local account state in sync with Binance.
Key Binance Websocket Endpoints
Binance exposes different base URLs for different products. Use the right one based on your market type. The table below shows the main public endpoints used in most setups.
| Market Type | Base WebSocket URL | Example Stream |
|---|---|---|
| Spot | wss://stream.binance.com:9443/ws |
wss://stream.binance.com:9443/ws/btcusdt@trade |
| USDT-M Futures | wss://fstream.binance.com/ws |
wss://fstream.binance.com/ws/btcusdt@ticker |
| Coin-M Futures | wss://dstream.binance.com/ws |
wss://dstream.binance.com/ws/btcusd_perp@depth |
Always check the official Binance API documentation for the latest endpoints, as futures and margin markets use slightly different URLs and stream names.
Basic Structure of a Stream URL
Each stream URL has two parts: the base endpoint and the stream path. For single streams, the pattern is simple. For example, a BTCUSDT trade stream on spot uses:
wss://stream.binance.com:9443/ws/btcusdt@trade
Here, btcusdt is the symbol in lowercase, and @trade is the stream type. Other common stream suffixes include @kline_1m, @ticker, and @depth.
How to Connect to a Binance Websocket Stream
Most languages have WebSocket clients that follow similar steps. The full process stays almost the same for JavaScript, Python, or any other modern language.
Step-by-Step Connection Flow
Use a simple sequence to open a connection, consume messages, and handle errors. This suits basic bots and small tools.
- Build the stream URL for the market and symbol you need.
- Create a WebSocket client and connect to the URL.
- Wait for the connection to open, then start reading messages.
- Parse each incoming JSON message.
- Use the data in your logic (update UI, update local order book, trigger orders).
- Detect errors or disconnects, then reconnect when needed.
For example, a simple script could connect to btcusdt@trade, print each incoming trade price and quantity, and reconnect if the socket closes.
Example: JavaScript Spot Trade Stream
Here is a simple JavaScript snippet that connects to the BTCUSDT trade stream in a browser or Node.js environment.
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Trade price:', data.p, 'Qty:', data.q);
};
ws.onclose = () => {
console.log('Socket closed, consider reconnect logic here');
};
The same logic applies in Python, C#, or Go. Only the client library syntax changes. JSON fields like p for price and q for quantity remain the same.
Subscribing to Multiple Streams
For more advanced setups, you can subscribe to several streams over a single connection. Binance provides both combined streams via URL and dynamic subscriptions via WebSocket messages.
Combined Streams by URL
A combined stream merges multiple streams into one connection. You use the /stream endpoint and pass a list of streams in the query string. Streams are joined by a slash character.
Example combined stream URL for BTCUSDT and ETHUSDT trades on spot:
wss://stream.binance.com:9443/stream?streams=btcusdt@trade/ethusdt@trade
Each incoming message then includes a stream field that tells you which symbol and type it came from, plus a data field with the payload.
Dynamic Subscriptions with JSON Payloads
Some Binance WebSocket endpoints accept subscription messages after the connection opens. You send a JSON object that includes the method and params. This is useful if you want to add or remove symbols on the fly without reconnecting.
Typical subscribe message structure:
{
"method": "SUBSCRIBE",
"params": ["btcusdt@trade", "ethusdt@trade"],
"id": 1
}
You then receive a response that confirms the subscription, followed by live data messages for these streams.
Using Private User Data Streams
Private user data streams require API keys and a short REST call before the WebSocket connection. This listen key acts like a temporary token for the WebSocket feed.
How to Get and Use a Listen Key
Most workflows for private streams follow the same pattern. The sequence below shows the main steps for a spot user data stream.
- Send a signed REST POST request to
/api/v3/userDataStreamusing your API key to get alistenKey. - Receive the
listenKeyfrom the response (for example,abc123...). - Open a WebSocket connection to
wss://stream.binance.com:9443/ws/<listenKey>. - Read order updates, trade executions, and balance updates from incoming messages.
- Ping the REST endpoint to keep the listen key alive within the required time window.
After the connection is live, you receive events such as executionReport (for order status) and outboundAccountPosition (for balances). A bot can react to a fill event in a fraction of a second instead of polling every few seconds.
Parsing Common Stream Payloads
Each stream has its own JSON structure. Learning the key fields is essential, especially for trade, ticker, and depth data that feed most trading logic or dashboards.
Trade Stream Fields
For a standard trade stream (for example, btcusdt@trade), expect fields like:
p– trade price.q– trade quantity.T– trade time (timestamp in milliseconds).m–trueif the buyer is market maker.
A script can use this data to update last traded price, trade tape, or volume counters with very low delay.
Depth Stream Fields
Depth streams send order book changes in the form of bid and ask updates. Typical fields include:
bids– array of [price, quantity] pairs for updated bid levels.asks– array of [price, quantity] pairs for updated ask levels.U,u– update IDs used to apply updates in sequence.
To keep a local order book, first get a REST snapshot, then apply each depth update in the right order using the update IDs. This is vital for any serious order book based strategy.
Handling Disconnects, Rate Limits, and Errors
Live streams sometimes break due to network issues, server resets, or client crashes. A stable WebSocket client detects and recovers from such issues without manual input.
Practical Stability Tips
Use simple rules in your client to stay connected and respect Binance rules. This protects your strategy and reduces missing data windows.
- Implement automatic reconnect with a backoff delay (for example, 1s, 2s, 5s, 10s).
- Limit the number of streams per connection, as Binance sets caps.
- Use combined streams instead of many separate sockets if you track many symbols.
- Monitor error codes and close reasons sent by the server or your library.
For depth streams, always resync with a fresh REST snapshot after a disconnect because some updates may be lost during the downtime.
Example Use Cases for Binance Websocket Streams
Real-time WebSocket data supports many practical setups, from simple dashboards to full algo trading engines. Even a small script benefits from immediate data instead of delayed REST calls.
Common Real-World Scenarios
A few typical examples show how developers often apply these streams in projects of different sizes.
- Price alert tool: Subscribe to
@tickeror@trade, and send a push notification when BTCUSDT crosses a given price. - Scalping bot: Use depth and trade streams to track micro structure and send orders the moment certain patterns appear.
- Portfolio monitor: Combine a private user data stream with public tickers to track account value and show live PnL.
- Order book visualizer: Keep a local order book from depth streams and show a real-time depth chart in a web app.
Each of these examples uses the same building blocks: stable WebSocket connections, correct parsing of JSON fields, and clear logic that reacts to events in real time.
Best Practices Before Going Live
Before a script or bot runs 24/7 against real funds, it should pass through tests on testnet or with small size. Websocket logic often reveals small bugs only after hours or days of runtime.
Create a basic checklist for any production client:
- Test connection and reconnection logic under slow or unstable network conditions.
- Verify parsing of all fields you use, such as price, quantity, and timestamps.
- Confirm that your app handles out-of-order or missing updates for depth streams.
- Log errors and close events, and review them after long sessions.
- Use API keys with correct permissions and keep them secure.
A small amount of upfront testing pays off later by avoiding wrong trades, stale quotes, or broken dashboards during high volatility.
Conclusion
Binance Websocket streams give fast, push-based access to market and account data. With a single WebSocket connection, a trader or developer can track prices, watch the order book, and react to order events in real time. By choosing the right endpoints, handling reconnects, and parsing messages with care, it is possible to build stable trading tools and dashboards that stay in sync with Binance markets.
Coin Matrix Journal 