1

I'm running an asyncio loop in the code below to retrieve data using websockets. Occasionally the network connection drops or the server is unresponsive so I have introduced a timeout which is caught by an exception handler. The timeout enables me to stop the connection quickly before I get a connection error message.

However, once the network connection is re-established or the server is back online, I am not sure how to connect to the server again so I can carry on running my loop as before?

I also get the following errors ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host and websockets.exceptions.ConnectionClosedError: no close frame received or sent.

import asyncio
import websockets
import json
from concurrent.futures import TimeoutError as ConnectionTimeoutError

async def call_dapi():
    async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
        while True:
            try:
                msg = {"jsonrpc": "2.0", "method": "public/get_order_book", "id": 1, "params": {"instrument_name": "BTC-PERPETUAL"}, "depth": "5"}
                await websocket.send(json.dumps(msg))
                response = await asyncio.wait_for(websocket.recv(), timeout=2)
                response = json.loads(response)
                print(response)
                await asyncio.sleep(1)
            except ConnectionTimeoutError as e:
                print('Error connecting.')
                pass

asyncio.ensure_future(call_dapi())
asyncio.get_event_loop().run_forever()
4
  • You have to loop back around to the websockets.connect call again. You'll need a second loop. Commented May 9, 2022 at 20:38
  • @TimRoberts thank you but how do I do that exactly? Would you mind providing the code if it's not too much trouble? Commented May 9, 2022 at 21:04
  • I suppose I can, but it seems pretty obvious. Commented May 9, 2022 at 21:11
  • @TimRoberts thanks. I hadn't come across nested loops before. Thank you for pointing me in the right direction and introducing something new. Commented May 9, 2022 at 21:34

1 Answer 1

2

I haven't tried this, but this is the philosophy.

import asyncio
import websockets
import json
from concurrent.futures import TimeoutError as ConnectionTimeoutError

async def call_dapi():
    while True:
        async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
            live = True
            while live:
                try:
                    msg = {"jsonrpc": "2.0", "method": "public/get_order_book", "id": 1, "params": {"instrument_name": "BTC-PERPETUAL"}, "depth": "5"}
                    await websocket.send(json.dumps(msg))
                    response = await asyncio.wait_for(websocket.recv(), timeout=2)
                    response = json.loads(response)
                    print(response)
                    await asyncio.sleep(1)
                except ConnectionTimeoutError as e:
                    print('Error connecting.')
                    live = False

asyncio.ensure_future(call_dapi())
asyncio.get_event_loop().run_forever()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.