Crypto Market News

Blockchain & Cryptocurrency News

Binance websocket api example python

Release time:2026-02-25 10:32:54

Recommend exchange platforms

Binance WebSocket API Example in Python: Real-Time Trading Data Streaming


Binance, one of the world's largest cryptocurrency exchanges by volume traded, offers a comprehensive set of APIs for developers and traders alike. Among these, the WebSocket API is particularly useful for real-time streaming of order book and trade data. In this article, we will explore how to use Python to connect to Binance's WebSocket API and start receiving live trading updates in near-zero latency.


Introduction


The WebSocket API provided by Binance offers two types of subscriptions:


1. Subscribe to the Order Book (Depth): Provides real-time update notifications for a specific symbol's order book data at a specified level depth.


2. Subscribe to Recent Trades: Receive live updates on recent trade events for a particular symbol.


Prerequisites


To follow along with this tutorial, you need:


1. A Binance account.


2. Python 3 installed on your machine.


3. Basic understanding of Python and its syntax.


4. Knowledge of the WebSocket protocol.


5. An IDE or text editor for writing code.


Step-by-Step Guide


Step 1: Authentication


First, you need to obtain an API Key and Secret from Binance's trading interface. Go to `https://www.binance.com/en/trade` and click on "API Trading" in the top right corner under your account name. From there, click "Create API Key" to create a new key pair.


Step 2: Install Requests Library


Before starting, ensure you have `requests` library installed by running `pip install requests` in your terminal if it's not already installed.


Step 3: Connecting to the WebSocket API


To connect to Binance's WebSocket API, we will use Python's `websockets` package for establishing a connection and passing data back and forth between our script and the server. If you haven't already, install it with `pip install websockets` command.


```python


import asyncio


import websockets


from binance.client import Client


api_key = "your_api_key"


api_secret = "your_api_secret"


Define a function that will be called when connected to the WebSocket


async def callback(message):


print(f'Received message: {message}')


client = Client(api_key, api_secret)


Connecting to order book snapshot data for BTCUSDT market every 500ms


await client.ws_authenticate_demo(callback=callback, symbols=['BTCUSDT'], diffusion=True)


```


Step 4: Subscribing to Order Book and Trade Updates


Now that we have established a connection with the WebSocket API, let's start receiving order book updates. To do this, you need to subscribe to the "@depth" event for your desired market (symbol pair). Here is an example of how to do it:


```python


async def trade_listener(websocket):


Subscribing to 'btcusdt@ticker' and 'btcusdt@bookTicker' events


await websocket.send(json.dumps({


"event": "subscribe",


"params": ["btcusdt@ticker"]}))


await websocket.send(json.dumps({


"event": "subscribe",


"params": ["btcusdt@bookTicker"]}))


while True:


resp = await websocket.recv()


print('Received: ' + resp)


```


In this example, we are subscribing to both `'btcusdt@ticker'` and `'btcusdt@bookTicker'` events which provide real-time updates on the latest trade price (tickers) for BTC/USDT pair.


Step 5: Running Your WebSocket Connection


Finally, you need to start your connection by running an asynchronous event loop until it's done or interrupted manually.


```python


start_server = websockets.serve(trade_listener, "localhost", 8080)


asyncio.get_event_loop().run_until_complete(start_server)


asyncio.get_event_loop().run_forever()


```


This will create a WebSocket server on your local machine listening on `localhost:8080` and start receiving order book data for BTC/USDT market pairs in real-time, printing out the received updates to your console.


Conclusion


By following these steps, you can now connect to Binance's WebSocket API using Python and receive live trading updates with minimal latency. This is just a basic example; there are many other events and symbols that you can subscribe to depending on your needs for analysis or automated trading strategies. Remember to always stay updated with any changes in the API documentation as it evolves over time.

Recommended articles