Hi !
I am working on python library
for voptions
, but I don’t understand how websockets work.
Do you have someone who can explain voptions
websockets to me, please …
Code:
async def initConnection(listenKey):
uri = "wss://testnetws.binanceops.com/ws/" + listenKey
print("wss://testnetws.binanceops.com/ws/{myListenKey}")
async with websockets.connect(uri) as websocket:
await websocket.send({
'method': "BINARY",
'params': ["false"],
'id': 1,
})
await websocket.send({
"method": "SUBSCRIBE",
"params": ["BTC-210326-24000-C@ticker"],
"id": 1
})
await websocket.send({})
print(f"< {await websocket.recv()}")
print(f"< {await websocket.recv()}")
print(f"< {await websocket.recv()}")
if __name__ == '__main__':
api_key = os.getenv("API_KEY")
api_secret = os.getenv("API_SECRET")
binance_ops = OptionClient(api_key=api_key, api_secret=api_secret)
test = binance_ops.get_listen_key()
asyncio.get_event_loop().run_until_complete(initConnection(test['data']['listenKey']))
Output:
wss://testnetws.binanceops.com/ws/{myListenKey}
< {"code":"10001","desc":"JSON格式错误"}
< {"code":"10001","desc":"JSON格式错误"}
MJW
February 8, 2021, 10:31am
2
“id”:1, - remove the comma and try again
await websocket.send({
‘method’: “BINARY”,
‘params’: [“false”],
‘id’: 1,
})
MJW
February 8, 2021, 11:50pm
4
What did you send exactly this time? And which message triggered below error message?
{“code”:“10001”,“desc”:“JSON格式错误”}
It works for me pretty well if I use https://blacksabbather.github.io/ws/wstool.htm to test. You can do the same thing:
Set URL as “wss://testnetws.binanceops.com/ws/” and click ‘Link’
Send {‘method’: “BINARY”,‘params’: [“false”], ‘id’: 1} # No comma
Nice, it was the dict.
Now with json.dumps()
it’s working, thanks you!
async def convert_to_text(websocket):
msg = json.dumps({
"method": "BINARY",
"params": ["false"],
"id": 1
})
await websocket.send(msg)
async def subscribe_to(websocket, stream):
msg = json.dumps({
"method": "SUBSCRIBE",
"params": [stream],
"id": 1
})
await websocket.send(msg)
async def initConnection():
uri = "wss://testnetws.binanceops.com/ws/"
async with websockets.connect(uri) as websocket:
await convert_to_text(websocket)
await subscribe_to(websocket, "BTC-210326-24000-C@ticker")
while True:
try:
message = await websocket.recv()
print(message)
except websockets.exceptions.ConnectionClosed:
print('ConnectionClosed')
break
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(initConnection())
Or like that:
async def convert_to_text(websocket):
msg = '{ "method": "BINARY", "params": ["false"], "id": 1 }'
await websocket.send(msg)
async def subscribe_to(websocket, stream):
msg = f'{{ "method": "SUBSCRIBE", "params": ["{stream}"], "id": 1 }}'
await websocket.send(msg)