Here is a step -by -step guide to help you manage multiple WebSocket links to get Binance’s three pairs of cryptocurrency prices:
Prerequisites
- You have an account at Binance API and you 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 using
PIP Install Websocket.
Code
Here is an example code that demonstrates how to connect with three different Binance WebSocket streams for Bitcoin prices (BTC), Ethereum (ETH) and LITECOIN (LTC):
Python
Import Websocket
Import time
Replace with your API credentials
api_id = «your_api_id»
api_secret = «your_api_secret»
Replace with the URLs of the stream
Stream_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
)
Initialization of WebSocket Links
ws_btc = websocket.create_connection (Stream_urls [0])
ws_eth = websocket.create_connection (Stream_urls [1])
Ws_LTC = WebSocket.create_connection (Stream_urls [2])
#The feature to update price flows
Def Update_Price_stream (Symbol, WebSocket):
While true:
try:
Get the current Order Book for the Character
Answer = Websocket.Recv ()
DATA = JSON.LADS (Answer)
Price = Float (data [«price»])
Print (F «{Symbol}: {Price: .2F}»)
With the exception of Websocket.Websketexception AS E:
Print (F «Error: {e}»)
Start the price flow updates
ws_btc.update_price_stream («BTCUSDT»)
ws_eth.update_price_stream («ethusdt»)
Ws_LTC.Update_price_stream («Ltccusd»)
Works indefinitely until you stop
While true:
Time.Sleep (60)
`
Explanation
This code is associated with three Binance WebSocket Flows for Bitcoin (BTC), Ethereum (ETH) and Litecoin (LTC) prices. It defines the Update_Price_stream
feature that extracts the current price from each stream every minute. The feature uses the WebSocket.Recv ()
to obtain messages from the WebSocket link, which contains the current JSON order order book.
The main part of the code creates three connections on Websocket using the ws_create_connection ()
method and starts the price update cycle by calling outder_price_stream
for each stream.
Note : Be sure to replace your_api_id
and your_api_secret` with your actual Binance API credentials. In addition, keep in mind that this is a simple example and you may want to add further processing and registration of errors, depending on your particular case of use.
I hope this helps! Tell me if you have any questions or need additional help.