1 year ago

#384799

test-img

Alex B

Why do some websockets require a second `await` to get a successful response?

I'm using a very simple python websocket api call below:

import asyncio
import websockets
import json

msg = {"jsonrpc": "2.0", "method": "public/get_index_price", "id": 42, "params": {"index_name": "btc_usd"}}

async def call_api(msg):
    async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
        await websocket.send(msg)
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))

which returns the following successful response:

{"jsonrpc":"2.0","id":42,"result":{"index_price":43497.69,"estimated_delivery_price":43497.69},"usIn":1649286272811228,"usOut":1649286272811333,"usDiff":105,"testnet":true}

However, when I use the code for a different api below:

import asyncio
import websockets
import json

msg = {"op": "subscribe", "args": [{"channel": "instruments", "instType": "FUTURES"}]}

async def call_api(msg):
    async with websockets.connect('wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999') as websocket:
        await websocket.send(msg)
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))

The response is the same json message that I have sent and I cannot understand why:

{"event":"subscribe","arg":{"channel":"instruments","instType":"FUTURES"}}

Looking at other code for the api I have managed to find that if I add a second response = await websocket.recv() I do manage to get the desired response as you can see in the code below:

import asyncio
import websockets
import json

msg = {"op": "subscribe", "args": [{"channel": "instruments", "instType": "FUTURES"}]}

async def call_api(msg):
    async with websockets.connect('wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999') as websocket:
        await websocket.send(msg)
        response = await websocket.recv()
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))

The successful response which I have shortened:

{'arg': {'channel': 'instruments', 'instType': 'FUTURES'}, 'data': [{'alias': 'this_week', 'baseCcy': '', 'category': '2', 'ctMult': '1', 'ctType': 'inverse', 'ctVal': '10', 'ctValCcy': 'USD', 'expTime': '1649404800000', 'instId':

My question is why do I need a addtional response = await websocket.recv() ? Why isn't a single await sufficient as it is in the first api example given at the beginning?

python

json

websocket

python-asyncio

0 Answers

Your Answer

Accepted video resources