Here is a step-by-step guide that allows you to manage multiple websocket connections to get a three pair of encryptions Binance:
Prerequisites
and
Secret_id.
Library on the Python project. If not, you can install it using the
Pip Install WebSocket -Clientapplication.
Code
Here is an example code that shows how to connect to three different websocket streams Binance Bitcoin (BTC), Ethereum (ETH) and Litecoin (LTC):
Python
Bring websocket
import -time
Replace your application subscription access information
Api_id = “Your_api_id”
Api_secret = “Your_api_secret”
Replace Stream -Url addresses
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 = Etusdt & Type = Order_Book & Stream = Order_Book & Limit = 10”,
Ethereum
“Wss: //binance.com/ws? Symbol = Ltccusdt & Type = Limit & Stream = Order_Book & Limit = 20”
Litecoin
–
Start websocket connections
Ws_btc = websocket.create_connection (stream_urls [0])
ws_eth = websocket.create_connection (stream_urls [1])
WS_LTC = websocket.create_connection (stream_urls [2])
Function updates price currents
Def Upday_Price_stream (Symbol, WebSocket):
Although true:
try:
Get a symbol of your current order book
Response = websocket.recv ()
Data = JSON.LOADS (Answer)
Price = floating (data [“price”])
Print (f “{symbol}: {price: .2f}”)
Except websocket.websocketexception like e:
Print (f “error: {e}”)
Start the price flow updates
ws_btc.update_price_stream (“BTCUSDT”)
ws_eth.update_price_stream (“etosdt”)
ws_ltc.update_price_stream (“ltccusdt”)
Run indefinitely until you stop
Although true:
TIME.SLEEP (60)
`
Explanation
This code connects to three WebSocket streams on Binance website Bitcoin (BTC), Ethereum (ETH) and Litecoin (LTC). It defines the action Update_Price_stream
, which seeks the current price for each stream every minute. The function uses the websocket.recv ()
method to receive messages from a websocket connection, which contains current order book information in JSON format.
The main part of the code creates three websocket connections using the ws_create_connection () method and start the price update by calling the
update_price_streamfor each stream.
Note : Remember to replace theyour_api_idand _iapi_secret
with real Binance API access rights. Also note that this is a simplified example, and you may want to increase additional error processing and login depending on your special use case.
I hope this will help! Tell me if you have any questions or you need additional help.