Here is a step-by-step guide to help you manage multiple websocket connections to get prices of three cryptocurrency pairs on Binance:
Prerequisites
- You have a Binance API account and can create an app with
app_id
andsecret_id
.
- You have installed the
websocket-client
library in your Python project. If not, you can install it usingpip install websocket-client
.
Code
Here is a sample code showing 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 stream URLsStream URL = [
"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 streamsdef update_price_stream(symbol, websocket):
while True:
Attempt:
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 indefinitely until stoppedwhile True:
time.sleep(60)
Explanation
This code connects to three websocket streams on Binance for Bitcoin (BTC), Ethereum (ETH), and Litecoin (LTC) prices. It defines a function update_price_stream
that retrieves the current price from 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. Keep in mind that this is a simplified example and you may want to add additional error handling and logging functionality depending on your specific use case.
Hope this helps! If you have any questions or need further assistance, feel free to contact me.