Crypto Market News

Blockchain & Cryptocurrency News

Binance websocket example python

Release time:2026-04-15 03:16:32

Recommend exchange platforms

Binance WebSocket Example in Python


In recent times, cryptocurrency trading platforms have gained a lot of traction, and one such platform is Binance. It's an exchange that allows users to trade various cryptocurrencies directly with each other without having to convert them into fiat currency first. One aspect that sets Binance apart from its competitors is the variety of tools it offers for developers. Among these tools are WebSockets, which allow real-time updates on trades and order book data. In this article, we will explore how to use Python to interact with a Binance WebSocket API and fetch trade data in real-time.


Introduction to Binance WebSockets


Binance WebSockets is an API that allows users to subscribe to different events happening on the exchange in real-time. You can connect your application to these WebSockets to get up-to-date information about trades and order book data. This data is useful for developers who want their applications to be highly responsive and provide accurate market updates.


Setting Up Your Environment


To interact with Binance WebSockets, you will need a few things: Python installed on your computer, along with the `websocket` module (which can easily be installed using pip), and an account on Binance to fetch the API keys. Once these prerequisites are met, we can proceed with setting up our environment.


1. Install the required modules by running this command in your terminal: ```pip install websocket-client```


2. Log into your Binance account and navigate to https://www.binance.com/en/fapi/v1/webSocket. Here, you can generate API keys for public data access, which will be used when connecting to the WebSockets.


3. Save these keys (your `api_key` and your `api_secret`) in a secure location because they provide access to real-time order book and trade information.


4. Create a new Python script with a ```.py``` extension. This is where we will write the code for our WebSocket connection.


Writing the Code


Now that we have set up our environment, let's write some code. The following example demonstrates how to connect to Binance's WebSockets API and fetch trade data in real-time. We will focus on fetching trades data from Bitcoin (BTC) to Tether (USDT) pair (`btcusdt`).


```python


Import required modules


import asyncio


import websockets


from binance.client import Client


async def trade_listener(websocket, path):


""" This function is the listener for the WebSocket connection and will receive


real-time trades data from Binance's API. """


while True:


The message variable contains raw JSON string that needs to be parsed


message = await websocket.recv()


data = json.loads(message)


print('received message:', data['event'])


async def run():


uri = "wss://fstream-fapi.binance.com/stream?"


Initialize your client with your API key and secret


client = Client(api_key='YOUR_API_KEY', api_secret='YOUR_API_SECRET')


async with websockets.connect(uri) as websocket:


await websocket.send(json.dumps({ 'event': 'addChannel', 'channel': 'trade',


'symbol': 'btcusdt'}))


Start the trade listener


await trade_listener(websocket, path=uri)


if __name__ == "__main__":


loop = asyncio.get_event_loop()


try:


loop.run_until_complete(run())


except KeyboardInterrupt as e:


print('\nCaught interrupt, exiting gracefully')


exit(0)


```


In this code snippet, we first import the necessary modules and define our `trade_listener` function, which will be called whenever a new trade event is received. Inside this function, we parse the incoming message (which is in JSON format), extract relevant data, and print it out to the console.


The `run` method sets up our WebSocket connection using Binance's API key and secret. We initialize our client with these keys, connect to the WebSockets URI (`wss://fstream-fapi.binance.com/stream?`), and send a JSON string containing the event name ('addChannel'), channel ('trade'), and symbol ('btcusdt') that we want to subscribe to.


Finally, when the script is executed as a standalone Python file (`python filename.py`), it will connect to Binance WebSockets and print out real-time trade data for the BTC/USDT pair until it's manually stopped with `Ctrl+C` or an equivalent method on your operating system.


Conclusion


In this article, we have explored how to use Python to interact with a Binance WebSocket API and fetch trade data in real-time. The example provided demonstrates the basics of setting up and using a WebSocket connection with Python's asyncio library and the `websockets` module. By understanding and implementing this code, you can gain valuable insights into cryptocurrency markets by accessing live order book and trade information from Binance.

Recommended articles