Ethereum and WebSockets: Building Real-Time Streams with Asyncio
= Connecting to Binance Websockets
——————————–
To connect to Binance websockets, we will use the requests
library with a WebSocket client. We will also use asyncio to handle 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
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=params) as response:
data = await response.json()
returned 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 (responses)
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 provided API key. We then use asyncio.gather
to execute 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, allowing us to handle multiple connections simultaneously.
Sample Output
—————-
The result 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 multiple API keys at the same time, we can use a single asynchronous event loop and subscribe to multiple WebSocket events using the async with
operator.
import asyncio
async def main():
api_keys = ["API_KEY_1", "API_KEY_2"]
Subscribe to market data eventsasync with aiohttp.ClientSession() as session:
async for response in session.get(" response:
if "ok" in response.json():
data = await response.json()
for api_key, event in zip(api_keys, ['market', 'order', 'trading']):
Process market dataprint(f"Market data: {event}")
Process orders and trading eventsif event['type'] == 'new_order':
print("New order received")
Run the main functionasyncio.run(main())
In this example, we We subscribe to multiple WebSocket events using a “for” loop. We process each event individually, printing messages to the console.