Crypto Market News

Blockchain & Cryptocurrency News

how do i access binance websocket api user data streams example

Release time:2026-11-25 17:45:19

Recommend exchange platforms

Accessing Binance WebSocket API: User Data Streams Example


Binance, one of the world's largest cryptocurrency exchanges, offers a comprehensive set of APIs that allow users to interact with its services and data in various ways. Among these, the WebSocket API for User Data Streams is particularly useful for real-time market data and order book updates. This API allows users to subscribe to trade events, order book depth changes, kline (candlestick) update events, and more, without any need to request historical data or continuously poll the Binance servers for fresh information. In this article, we'll explore how to access these user-data streams using WebSockets in Python as an example.


Understanding User Data Streams (UDS)


The User Data Stream API provides real-time updates on specific market events that are relevant to the account of the requesting user. It is designed for mobile and web applications, allowing developers to get price updates without having to continuously poll Binance's APIs. For instance, it can be used in a trading bot or any other application requiring immediate notification when certain conditions (like order fills) occur on the exchange.


Setting Up Your Environment


Before we dive into coding, ensure you have Python 3 installed and set up your environment with `pip` to install necessary packages. You will also need to sign up on Binance and obtain a trading account API key and access token. For testing purposes, it's essential to have some balance in the account.


Authentication


To use the WebSocket API, you first need to authenticate your account by obtaining an API Key and Access Token from Binance's dashboard. The process involves enabling the required permissions for the WebSockets on live trading data. After that, follow these steps:


1. Create a signature using SHA256 with base64 encoding of your timestamp (in seconds) concatenated with API key and passphrase separated by colons (":"). This is crucial as Binance uses this for authentication.


2. Use the Access Token to connect to the WebSocket URL.


3. Send a JSON-formatted message to start receiving streams.


Coding Example: Connecting to User Data Streams


Let's break down how to use Python and the `websockets` package for this task. This example focuses on subscribing to trade events, which means you will receive real-time updates whenever a trade occurs in the market specified by symbol.


```python


import asyncio


import websockets


import hashlib


import base64


import time


API_KEY = 'your_api_key'


SECRET_KEY = 'your_secret_key'


ACCESS_TOKEN = 'your_access_token' # obtained from Binance


SYMBOL = 'BTCUSDT'


def create_message(server, message):


"""Creates a WebSocket API payload."""


timestamp = int(time.time() * 1000)


message['event'] = 'MESSAGE' # or any other event type as per Binance docs


data = {'command': 'subscribe', 'symbol': SYMBOL}


payload = {


"method": message["method"], "params": [data, timestamp]


}


return payload


def generate_sign(server, message):


"""Generates the signature used for WebSocket API authentication."""


payload = create_message(server, message)


message_str = str(payload['params'][1]) + ':' + server + ":" + payload['method']


signature = hashlib.sha256(base64.b64encode(hashlib.sha256(message_str.encode()).digest())).hexdigest()


return signature


async def user_data_stream():


"""Connects to the User Data Stream API and processes messages."""


server = "wss://fapi.binance.com/ws"


message = {'method': 'SUBSCRIBE', 'params': [SYMBOL], 'id': 1}


signature = generate_sign(server, message)


token = ACCESS_TOKEN # Use this for authentication in the headers


url = f"{server}?access_key={API_KEY}&signature={signature}×tamp={int(time.time()*1000)}&BINANCE_CALLBACK={token}"


async with websockets.connect(url) as websocket:


await websocket.send(json.dumps(message))


while True:


raw_msg = await websocket.recv()


print(f"Received from Binance: {raw_msg}")


if __name__ == "__main__":


asyncio.run(user_data_stream())


```


Understanding the Code


1. The `create_message` function generates a payload for WebSocket API authentication and usage. It's crucial to include all required fields as per Binance's documentation, especially when subscribing or requesting market data.


2. The `generate_sign` function calculates the SHA256 hash of a concatenation of time, server URL, and method name. This signature is essential for authenticating your WebSocket connection to Binance.


3. The `user_data_stream` coroutine sets up and manages the WebSocket connection. It sends an initial message to subscribe to trade events for the specified symbol ('BTCUSDT' in this example). After that, it enters a loop receiving updates as they come.


4. Finally, running the `user_data_stream` coroutine initiates everything, ensuring the WebSocket connection is established and messages are processed asynchronously without blocking the main thread.


Conclusion


Accessing Binance's User Data Stream API with Python and WebSockets provides a powerful way to receive real-time market data and updates for your trading or analysis applications. The process involves proper authentication, setting up a WebSocket connection, and processing incoming messages. This example serves as a foundational approach, but remember to adapt it according to your specific application's needs and always refer to Binance's API documentation for the most accurate usage guidelines.

Recommended articles