Crypto Market News

Blockchain & Cryptocurrency News

python binance websocket code

Release time:2026-08-07 03:55:58

Recommend exchange platforms

Python Binance WebSocket Code: Real-Time Market Data Streaming


Binance, one of the world's largest cryptocurrency exchanges by trading volume, provides APIs for interacting with its platform. Among these APIs are WebSockets, which offer real-time updates without constant polling or requests. This makes them perfect tools for applications that need up-to-date market data in milliseconds, such as bots and charting platforms.


This article will explore how to create a Python script that utilizes Binance's WebSocket API to receive live market data updates. We'll cover setting up the connection, handling messages from the socket, and displaying some of the data received.


Setting Up the Environment


To start coding with Binance’s WebSockets in Python, you need a working environment that includes `python` installed on your machine along with `websockets` package. This can be installed using pip:


```bash


pip install websockets


```


For this example, we'll create a simple application to connect to Binance WebSocket and print the data received in real-time. We are going to stream `ticker’s update for BTCUSDT` which includes 24hr ticker statistics like price change and trading volume.


Step By Step Guide:


Importing Required Libraries


```python


import websockets, asyncio


from binance.websocket import BinanceSocketManager


from binance.client import Client


```


Setting Up WebSocket Connection


First, we need to set up our connection by creating a `Client` object and then passing this client into the `BinanceSocketManager`:


```python


async def trade_callback(ws, event):


"""Callback for handling received events from Binance websocket."""


print(event) # Just print received data to console


client = Client(api_key="YOUR_API_KEY", api_secret="YOUR_SECRET_KEY")


bm = BinanceSocketManager(client=client)


trade_ws = bm.trade('BTCUSDT') # Subscribe to BTC/USDT trade updates


```


Please replace `YOUR_API_KEY` and `YOUR_SECRET_KEY` with your actual API key and secret, respectively.


Handling the WebSocket Connection


In Python 3.7+, you can use async functions for handling the WebSocket connection in an asynchronous manner using the `websockets` library:


```python


async def listen_forever():


"""Listen forever on the trade socket and print messages."""


uri = f'wss://stream.binance.com/stream?streams={"@".join([trade_ws.queue[0]])}&symbol=BTCUSDT'


async with websockets.connect(uri) as connection: # Connect to Binance WebSocket


while True:


msg = await connection.recv()


print('Received message:', msg)


```


The `listen_forever()` function is called when you run the script and will connect to the trade socket from Binance and print out any messages it receives. The first argument of `trade_ws` determines which pair/market data stream we are interested in, here 'BTCUSDT' for Bitcoin-Tether trading pair.


Running the WebSocket Connection


Finally, Python 3.5+ allows you to use `asyncio` module to run asynchronous programs:


```python


loop = asyncio.get_event_loop() # Get an event loop


try:


loop.run_until_complete(listen_forever()) # Run until complete


finally:


loop.close() # Close the loop to free up resources


```


This code will run `listen_forever()` until it completes or raises an exception, at which point we close the event loop as there's no need for it anymore.


Conclusion


In conclusion, using Binance WebSocket API with Python is a powerful tool that can be used to receive live market data in real-time. This example shows you how easy it is to set up and start streaming data from this service. It’s just the beginning though, as there are many more features available through the Binance API which could be utilized for different purposes like automated trading strategies or even creating a charting platform that updates in real time. The possibilities are endless with the right knowledge and creativity.

Recommended articles