Sunday, 17 February 2019

How to send a message to Server with Websocket

I'm trying to send messages to a Server to get answers.

I've tried to use official websocket APIs from the site but I don't understand them or can't make them work as I wish, so I'm trying to build it.

import asyncio
import websockets

 async def test():

     async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:

        await websocket.send("ping")
  #OR   await websocket.send({"op": "subscribe", "args": [<SubscriptionTopic>]})

        response = await websocket.recv()
        print(response)

 asyncio.get_event_loop().run_until_complete(test())

I recieve that I'm connected but I don't recieve "pong" as an answer to "ping", nor "Good you are subscribed to this Topic" as I recieve when trying the commands on a echo website.

#!/usr/bin/env python3

import asyncio
import websockets
import json

var = []

async def test():
async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
    response = await websocket.recv()
    print(response)


    await websocket.send(json.dumps({"op": "subscribe", "args": "trade:TRXH19"}))
    response = await websocket.recv()

    resp = await websocket.recv()
    print(json.loads(resp))

    sum=0

    while True:

        resp = await websocket.recv()
        jj = json.loads(resp)["data"][0]
        var.append(jj)
        size = jj["size"]
        side = jj["side"]
        coin = jj["symbol"]
        if side=="Buy":
            sum+=size
        else:
            sum-=size
        print(coin)
        print(size)
        print(side)
        print("Totale = ", sum )

while True:
    asyncio.get_event_loop().run_until_complete(test())
    print(var)
    print("Ciclo Finito!!!!")



from How to send a message to Server with Websocket

No comments:

Post a Comment