Crypto Market News

Blockchain & Cryptocurrency News

Binance websocket api example

Release time:2026-02-22 18:32:48

Recommend exchange platforms

Binance WebSocket API Example: Real-Time Market Data with Python


In the world of cryptocurrency trading, real-time market data is crucial for making informed decisions and executing trades quickly. Binance, one of the largest cryptocurrency exchanges by volume, offers an extensive set of APIs, including a WebSocket API that provides live updates on order book changes, trade history, account balances, and more. In this article, we will explore how to use Python to connect to the Binance WebSocket API and retrieve real-time market data.


Understanding Binance's WebSocket API


Binance's WebSocket API is a powerful tool that allows developers to access live updates on various aspects of the exchange, such as order book changes, trade history, account balances, and more. The API uses JSON-RPC v2 over WebSockets for communication, which means it can send and receive messages in real time without requiring periodic polling.


To use the Binance WebSocket API, you need to create an API key by signing up on the Binance website and navigating to the "API/Web" tab. Once you have your API credentials (including secret key), you are ready to connect to the WebSocket.


Setting Up a Connection with Python


To interact with the Binance WebSocket API using Python, we will use the `websocket` library. First, ensure you have it installed by running:


```bash


pip install websockets


```


Now, let's write a simple script to connect to the Binance WebSocket API and subscribe to real-time updates on the BTCUSDT trading pair's order book.


```python


import asyncio


import websockets


import json


Your API credentials (replace with your own)


API_KEY = "your_api_key"


SECRET_KEY = "your_secret_key"


CHANNEL = "all" # Subscribe to all events, can be 'spot/all' or specific symbols like 'spot/BTCUSDT'


def sign(data):


"""Sign a message with secret key."""


from time import time


now = int(time())


s = '%s%s%s' % (json.dumps(data), CHANNEL, API_KEY)


sig = json.loads(base64.b64encode(hashlib.sha256(s.encode('utf-8')).hexdigest().encode()).decode())


return sig + '%s' % now


async def connect():


"""Connect to WebSocket and subscribe to a channel."""


url = 'wss://fstream.binance.com/stream?'


subscribe_msg = {


"method": "SUBSCRIBE",


"params": [CHANNEL],


}


sig_send = sign(json.dumps(subscribe_msg))


headers = {


'Authorization': 'FapiSig %s %s' % (API_KEY, sig_send),


'Content-Type': 'application/json;charset=UTF-8',


}


async with websockets.connect(url, extra_headers=headers) as websocket:


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


while True:


resp = await websocket.recv()


print('Received message:', resp)


if __name__ == '__main__':


loop = asyncio.get_event_loop()


try:


loop.run_until_complete(connect())


except KeyboardInterrupt:


pass


```


This script demonstrates the basic flow to connect to Binance's WebSocket API and print incoming messages on standard output (stdout) for demonstration purposes. However, you can process these messages as per your requirements, such as updating a dashboard or executing trades based on market movements.


Key Components:


The `connect` function is an asynchronous coroutine that establishes a connection to the WebSocket endpoint and subscribes to the desired channel using Binance's signature method for secure authentication.


The `sign` function generates a signature required by the API, based on the current time, message data, secret key, and the chosen channel.


The `websockets` library is used to manage connections and communication with the WebSocket server.


Connecting to Specific Symbols or Events


You can modify the script to connect to specific symbols or event types by changing the value of the `CHANNEL` variable. For example, if you want real-time updates on the BTCUSDT trading pair's order book and trade history, use:


```python


CHANNEL = 'spot/BTCUSDT@depth' # Order book depth level 5 for BTCUSDT symbol


CHANNEL = 'spot/BTCUSDT@ticker' # Trade history updates for BTCUSDT symbol


```


Error Handling and Optimization


This example script does not include comprehensive error handling or optimizations, such as connection retries and message rate limiting. Depending on your application's requirements, you may need to add additional layers of complexity.


Conclusion


Binance WebSocket API provides a versatile way for developers to access real-time market data for their applications. By leveraging Python with the `websockets` library and understanding Binance's authentication process, it is possible to create robust trading bots, real-time analytics dashboards, or any other application that requires continuous updates on cryptocurrency markets.


Remember, as with all API keys, handle them securely and responsibly. Never share your key with unauthorized individuals and ensure it does not remain in your codebase after deployment or testing.

Recommended articles