Issue
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()
Solution
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()
Answered By - Tim Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.