Python Forum
How to print results of asyncio websockets at the same time?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print results of asyncio websockets at the same time?
#1
Question

- How can I merge the results of two or three asynchronous websocket results, defined with the library asyncio?
- I am downloading order book data (how many people want to buy or sell something at which price) of cryptocurrencies using websockets asynchronously, but having hard time showing the results of several coins.
- The desired output example is as follows, being printed at the same time :

XRP-BTC : The most favorable ask price is 0.00023
ETH-BTC : The most favorable ask price is 0.04
LTC-BTC : The most favorable ask price is 0.001
- Each line is a result of each websocket, so what I want to do is to merge the results of several webscokets

Code Example

import asyncio
import websockets
import ast
import time
import json

# websocket address for the cryptocurrency exchange OKEx
url = "wss://ws.okex.com:8443/ws/v5/public"

# function to download orderbook data, using websocket asynchronously
async def ws_orderbook5(crypto_pair):
    while True:
            try:
                async with websockets.connect(url) as ws:
                    channels = [{'channel': 'books5', 'instId': f'{crypto_pair}'}]
                    sub_param = {"op": "subscribe", "args": channels}
                    sub_str = json.dumps(sub_param)
                    await ws.send(sub_str)
                    print(f"send: {sub_str}")
                    res = await asyncio.wait_for(ws.recv(), timeout=25)

                    while True:
                        try:
                            res = await asyncio.wait_for(ws.recv(), timeout=25)
                            res = ast.literal_eval(res) 
                            print(f"{crypto-pair} : Most favorable ask price is {res['data'][0]['asks'][0][0]}")
                            
                            time.sleep(1)

                        except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e:
                            try:
                                await ws.send('ping')
                                print("")
                                print("ping")
                                res = await ws.recv()
                                continue
                            except Exception as e:
                                print("Failure due to an unknown error. Stopped working")
                                break
            except Exception as e:
                print("Failure due to an unknown error. Try working again")
                continue
- The variable res, which is the data downloaded from OKEx websocket looks like the following dictionary, when the argument crypto_pair = 'XRP-BTC' .

{'arg': {'channel': 'books5', 'instId': 'XRP-BTC'}, 
 'data': [{'asks': [['0.00002585', '4514.84', '0', '2'], 
                    ['0.00002586', '5845.946', '0', '5'],
                    ['0.00002587', '30306.155', '0', '5'], 
                    ['0.00002588', '9974.105', '0', '7'], 
                    ['0.00002589', '3104.84', '0', '5']], 
           'bids': [['0.00002582', '3988', '0', '2'], 
                    ['0.00002581', '23349.817', '0', '4'], 
                    ['0.0000258', '18735.565', '0', '8'], 
                    ['0.00002579', '6429.196', '0', '6'], 
                    ['0.00002578', '3492.795', '0', '5']], 
 'instId': 'XRP-BTC', 
 'ts': '1622805157064'}]}
- As such what is printed on console is as follows. The argument here, for example, is "XRP-BTC" again.

XRP-BTC : The most favorable ask price is 0.00023
- Can anyone tell me how I can merge the result of websockets so that they can be printed at the same time?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Print names in x-axis of a time-series values hobbyist 4 1,236 Apr-22-2023, 09:29 PM
Last Post: deanhystad
  websockets and pymongo exception sankar2000 0 1,011 Oct-07-2022, 09:52 PM
Last Post: sankar2000
  websockets server loop? korenron 1 1,863 Dec-23-2020, 03:59 PM
Last Post: korenron
  Print characters in a single line rather than one at a time hhydration 1 2,040 Oct-10-2020, 10:00 PM
Last Post: bowlofred
  How to print n days back date at give time Mekala 1 1,994 Oct-10-2020, 03:35 AM
Last Post: bowlofred
  Having a hard time conceptualizing how to print something MysticLord 6 3,127 Sep-19-2020, 10:43 PM
Last Post: MysticLord
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,243 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  Print a certain string only the first time it appears in a test file buttercup 5 2,793 Jul-23-2020, 01:30 PM
Last Post: palladium
  How to print the current time in color julio2000 3 2,757 Apr-16-2020, 10:21 AM
Last Post: julio2000
  Print date, Time and output to file tpolim008 3 2,352 Mar-26-2020, 06:49 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020