Here is a step-by-step guide to help you manage multiple WebSocket connections to get prices of three crypto pairs on Binance:
Prerequisites
- You have a Binance API account and can create an application with
app_id
andsecret_id
.
- You have installed the
websocket-client
library in your Python project. Alternatively, you can install it usingpip install websocket-client
.
Code
Here is a code example that shows how to connect to three different WebSocket streams on Binance for Bitcoin (BTC), Ethereum (ETH), and Litecoin (LTC) prices:
import websocket
import time
Replace with your API credentialsapi_id = "your_api_id"
api_secret = "your_api_secret"
Replace with the stream URLsstream_urls = [
"wss://binance.com/ws?symbol=BTCUSDT&type=limit&stream=order_book&limit=100",
Bitcoin"wss://binance.us/api/v3 WebSocket API ( websocket+limit+24h) ? symbol=ETHUSDT & type=order_book & stream=order_book & limit=10",
Ethereum"wss://binance.com/ws?symbol=LTCCUSDT&type=limit&stream=order_book&limit=20"
Litecoin]
Initialize websocket connectionsws_btc = websocket.create_connection(stream_urls[0])
ws_eth = websocket.create_connection(stream_urls[1])
ws_ltc = websocket.create_connection(stream_urls[2])
Function to update price feedsdef update_price_stream(symbol, websocket):
while True:
try:
Get the current order book for the symbolresponse = websocket.recv()
data = json.loads(response)
price = float(data["price"])
print(f"{symbol}: {price:.2f}")
except websocket.WebSocketException as e:
print(f"Error: {e}")
Start price stream updatesws_btc.update_price_stream("BTCUSDT")
ws_eth.update_price_stream("ETHUSDT")
ws_ltc.update_price_stream("LTCCUSDT")
Run forever until stoppedwhile True:
time.sleep(60)
Explanation
This code connects to three WebSocket streams on Binance for the prices of Bitcoin (BTC), Ethereum (ETH), and Litecoin (LTC). It defines a function update_price_stream
that retrieves the current price of each stream every minute. The function uses the websocket.recv()
method to receive messages from the WebSocket connection, which contains the current order book data in JSON format.
The main part of the code creates three WebSocket connections using the ws_create_connection()
method and starts the price update loop by calling update_price_stream
for each stream.
Note: Make sure to replace your_api_id
and your_api_secret
with your actual Binance API credentials. Also, be aware that this is a simplified example and you may want to add additional error handling and logging depending on your specific use case.
Hope this helps! Feel free to contact me if you have any questions or need further assistance.