简体   繁体   English

通过异步websocket客户端保持与websocket服务器的连接

[英]Keep connection with websocket server via async websocket client

I want to connect WS API of Bitmex exchange(testnet.bitmex.com) and continuously fetch data. 我想连接Bitmex交换的WS API(testnet.bitmex.com)并不断获取数据。 I am using following code, it connects sucsessfully, but dont keep the connection, closing after recieving subscription data: 我使用以下代码,它连接成功,但不保持连接,收到订阅数据后关闭:

import time
import json
import hmac
import hashlib
secret ='7sol85dTkfWprpa03TbRFfgbnQDxpwiYP5PLspgYx_nNDSrn'
key='YPR0oojxqAR-2dp1J76BgNhT'
websocket_url = 'wss://testnet.bitmex.com/realtime?'


async def main():
        expires = str(int(round(time.time())) + 5)
        path = 'GET/realtime' + expires
        signature =  hmac.new(secret.encode(),path.encode(),hashlib.sha256).hexdigest()
        async with websockets.connect(websocket_url + 'api-expires=' + expires + '&api-signature=' + signature + '&api-key=' + key) as ws:
           request = {"op": "subscribe", "args": ['trade:XBTUSD', 'instrument:XBTUSD', 'quote:XBTUSD', 'position:XBTUSD']}
           await ws.send(json.dumps(request))

        while True:
            result = await ws.recv()
            print(result)


asyncio.run(main())

Here is result, you can see responses from API, but it closes after getting of subscription list. 结果如下,您可以看到API的响应,但在获取订阅列表后会关闭。 In synchronous execution all goes fine 在同步执行中一切顺利

{"info":"Welcome to the BitMEX Realtime API.","version":"2019-07-18T21:20:16.000Z","timestamp":"2019-07-20T22:19:51.071Z","docs":"https://testnet.bitmex.com/app/wsAPI","limit":{"remaining":39}}
{"table":"trade","action":"partial","keys":[],"types":{"timestamp":"timestamp","symbol":"symbol","side":"symbol","size":"long","price":"float","tickDirection":"symbol","trdMatchID":"guid","grossValue":"long","homeNotional":"float","foreignNotional":"float"},"foreignKeys":{"symbol":"instrument","side":"side"},"attributes":{"timestamp":"sorted","symbol":"grouped"},"filter":{"symbol":"XBTUSD"},"data":[{"timestamp":"2019-07-20T22:19:43.770Z","symbol":"XBTUSD","side":"Buy","size":3,"price":10954,"tickDirection":"PlusTick","trdMatchID":"bff64535-4c5d-2a0a-8533-47e93091daa3","grossValue":27387,"homeNotional":0.00027387,"foreignNotional":3}]}
{"table":"quote","action":"partial","keys":[],"types":{"timestamp":"timestamp","symbol":"symbol","bidSize":"long","bidPrice":"float","askPrice":"float","askSize":"long"},"foreignKeys":{"symbol":"instrument"},"attributes":{"timestamp":"sorted","symbol":"grouped"},"filter":{"symbol":"XBTUSD"},"data":[{"timestamp":"2019-07-20T22:19:43.770Z","symbol":"XBTUSD","bidSize":1863,"bidPrice":10951,"askPrice":10954,"askSize":1403}]}
{"success":true,"subscribe":"trade:XBTUSD","request":{"op":"subscribe","args":["trade:XBTUSD","instrument:XBTUSD","quote:XBTUSD","position:XBTUSD"]}}
{"success":true,"subscribe":"instrument:XBTUSD","request":{"op":"subscribe","args":["trade:XBTUSD","instrument:XBTUSD","quote:XBTUSD","position:XBTUSD"]}}
{"success":true,"subscribe":"quote:XBTUSD","request":{"op":"subscribe","args":["trade:XBTUSD","instrument:XBTUSD","quote:XBTUSD","position:XBTUSD"]}}
{"success":true,"subscribe":"position:XBTUSD","request":{"op":"subscribe","args":["trade:XBTUSD","instrument:XBTUSD","quote:XBTUSD","position:XBTUSD"]}}
{"table":"position","action":"partial","keys":["account","symbol","currency"],"types":{"account":"long","symbol":"symbol","currency":"symbol","underlying":"symbol","quoteCurrency":"symbol","commission":"float","initMarginReq":"float","maintMarginReq":"float","riskLimit":"long","leverage":"float","crossMargin":"boolean","deleveragePercentile":"float","rebalancedPnl":"long","prevRealisedPnl":"long","prevUnrealisedPnl":"long","prevClosePrice":"float","openingTimestamp":"timestamp","openingQty":"long","openingCost":"long","openingComm":"long","openOrderBuyQty":"long","openOrderBuyCost":"long","openOrderBuyPremium":"long","openOrderSellQty":"long","openOrderSellCost":"long","openOrderSellPremium":"long","execBuyQty":"long","execBuyCost":"long","execSellQty":"long","execSellCost":"long","execQty":"long","execCost":"long","execComm":"long","currentTimestamp":"timestamp","currentQty":"long","currentCost":"long","currentComm":"long","realisedCost":"long","unrealisedCost":"long","grossOpenCost":"long","grossOpenPremium":"long","grossExecCost":"long","isOpen":"boolean","markPrice":"float","markValue":"long","riskValue":"long","homeNotional":"float","foreignNotional":"float","posState":"symbol","posCost":"long","posCost2":"long","posCross":"long","posInit":"long","posComm":"long","posLoss":"long","posMargin":"long","posMaint":"long","posAllowance":"long","taxableMargin":"long","initMargin":"long","maintMargin":"long","sessionMargin":"long","targetExcessMargin":"long","varMargin":"long","realisedGrossPnl":"long","realisedTax":"long","realisedPnl":"long","unrealisedGrossPnl":"long","longBankrupt":"long","shortBankrupt":"long","taxBase":"long","indicativeTaxRate":"float","indicativeTax":"long","unrealisedTax":"long","unrealisedPnl":"long","unrealisedPnlPcnt":"float","unrealisedRoePcnt":"float","simpleQty":"float","simpleCost":"float","simpleValue":"float","simplePnl":"float","simplePnlPcnt":"float","avgCostPrice":"float","avgEntryPrice":"float","breakEvenPrice":"float","marginCallPrice":"float","liquidationPrice":"float","bankruptPrice":"float","timestamp":"timestamp","lastPrice":"float","lastValue":"long"},"foreignKeys":{"symbol":"instrument"},"attributes":{"account":"sorted","symbol":"grouped","currency":"grouped","underlying":"grouped","quoteCurrency":"grouped"},"filter":{"account":92043,"symbol":"XBTUSD"},"data":[{"account":92043,"symbol":"XBTUSD","currency":"XBt","underlying":"XBT","quoteCurrency":"USD","commission":0.00075,"initMarginReq":0.25,"maintMarginReq":0.005,"riskLimit":20000000000,"leverage":4,"crossMargin":false,"deleveragePercentile":1,"rebalancedPnl":38942,"prevRealisedPnl":255686,"prevUnrealisedPnl":0,"prevClosePrice":10978.78,"openingTimestamp":"2019-07-20T22:00:00.000Z","openingQty":-100,"openingCost":991600,"openingComm":-4854,"openOrderBuyQty":0,"openOrderBuyCost":0,"openOrderBuyPremium":0,"openOrderSellQty":0,"openOrderSellCost":0,"openOrderSellPremium":0,"execBuyQty":0,"execBuyCost":0,"execSellQty":0,"execSellCost":0,"execQty":0,"execCost":0,"execComm":0,"currentTimestamp":"2019-07-20T22:19:50.061Z","currentQty":-100,"currentCost":991600,"currentComm":-4854,"realisedCost":0,"unrealisedCost":991600,"grossOpenCost":0,"grossOpenPremium":0,"grossExecCost":0,"isOpen":true,"markPrice":10966.17,"markValue":911900,"riskValue":911900,"homeNotional":-0.009119,"foreignNotional":100,"posState":"","posCost":991600,"posCost2":991600,"posCross":44500,"posInit":247900,"posComm":963,"posLoss":0,"posMargin":293363,"posMaint":5921,"posAllowance":0,"taxableMargin":0,"initMargin":0,"maintMargin":213663,"sessionMargin":0,"targetExcessMargin":0,"varMargin":0,"realisedGrossPnl":0,"realisedTax":0,"realisedPnl":4854,"unrealisedGrossPnl":-79700,"longBankrupt":0,"shortBankrupt":0,"taxBase":0,"indicativeTaxRate":0,"indicativeTax":0,"unrealisedTax":0,"unrealisedPnl":-79700,"unrealisedPnlPcnt":-0.0804,"unrealisedRoePcnt":-0.3215,"simpleQty":null,"simpleCost":null,"simpleValue":null,"simplePnl":null,"simplePnlPcnt":null,"avgCostPrice":10084.5,"avgEntryPrice":10084.5,"breakEvenPrice":10549.5,"marginCallPrice":14200.5,"liquidationPrice":14200.5,"bankruptPrice":14302,"timestamp":"2019-07-20T22:19:50.061Z","lastPrice":10966.17,"lastValue":911900}]}
Traceback (most recent call last):
  File "E:/python/TRADE2/venv/2.py", line 37, in <module>
    asyncio.run(main())
  File "C:\Users\Padalecki\AppData\Local\Programs\Python\Python37-32\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Padalecki\AppData\Local\Programs\Python\Python37-32\lib\asyncio\base_events.py", line 584, in run_until_complete
    return future.result()
  File "E:/python/TRADE2/venv/2.py", line 27, in main
    result = await ws.recv()
  File "E:\python\TRADE2\venv\lib\site-packages\websockets\protocol.py", line 485, in recv
    await self.ensure_open()
  File "E:\python\TRADE2\venv\lib\site-packages\websockets\protocol.py", line 772, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason

I tried to use run_forever(): 我尝试使用run_forever():

loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()

Same result it did not helped 同样的结果它没有帮助

Your while loop is outside of the connect() context manager block, after the block is exited the connection is closed. 您的while循环位于connect()上下文管理器块之外,在退出块后,连接将关闭。 You just need to indent some of your code 你只需缩进一些代码即可

    async with websockets.connect(websocket_url + 'api-expires=' + expires + '&api-signature=' + signature + '&api-key=' + key) as ws:
        request = {"op": "subscribe", "args": ['trade:XBTUSD', 'instrument:XBTUSD', 'quote:XBTUSD', 'position:XBTUSD']}
        await ws.send(json.dumps(request))

    >>>>while True:
    >>>>    result = await ws.recv()
    >>>>    print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM