Ethereum: Multiple websocket streams with asyncio in Python


Ethereum: Multiple websocket streams with asyncio in Python

Ethereum and WebSockets: Creating Real-Time Streams with Asyncio

= Connecting to Binance Websockets

——————————–

To connect to Binance websockets, we will use the requests library with the WebSocket client. We will also use asyncio to manage multiple connections simultaneously.

import asyncio

import aiohttp

async def get_websocket_data(api_key):

url = f" subscribe"

parameters = {

"key": api_key,

"symbol": "BTCUSDT",

"event_type": "new_order",

"limit": 1

}

asynchronous with aiohttp.ClientSession() as session:

asynchronous with session.post(url, json=params) as response:

data = await response.json()

return data

async def main():

api_keys = ["API_KEY_1", "API_KEY_2", "API_KEY_3"]

tasks = [get_websocket_data(api_key) for api_key in api_keys]

responses = await asyncio.gather(*tasks)

print (answers)

if __name__ == "__main__":

asyncio.run(main())

In this example, we define a get_websocket_data function that sends a subscription request to Binance with the specified API key. We then use asyncio.gather to run multiple tasks simultaneously.

We create a list of API keys and pass it to the get_websocket_data function using an async for loop. Each task is executed independently, which allows us to handle multiple connections simultaneously.

Example output

—————-

The output will be a JSON object containing the latest market data from Binance’s WebSocket API.

[

{'symbol': 'BTCUSDT', 'last_price': 0.0001},

{'symbol': 'BTCUSDT', 'bid': 0.001, 'ask': 0.002},

...

]

Real-time data streams

———————

To receive messages for several API keys simultaneously, we can use a single asyncio event loop and subscribe to multiple WebSocket events using the async with command.

import asyncio

async def main():

api_keys = ["API_KEY_1", "API_KEY_2"]








Ethereum: Multiple websocket streams with asyncio in Python

Subscribe to market data events

asynchronously with aiohttp.ClientSession() as session:

async for response in session.get(" response:

if the answer is 'ok'.json():

data = await response.json()

for api_key, event in zip(api_keys, ['market', 'order', 'trading']):


Handling of market data

print(f"Market data: {event}")


Handling orders and trade events

if event['type'] == 'new_order':

print("New order received")


Run the main function

asyncio.run(main())

In this example we subscribe to multiple WebSocket events using a `for’ loop. We handle each event individually, printing messages to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *