How to connect to poloniex.com websocket api using a python library

前端 未结 4 2127
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 17:16

I am trying to connect to wss://api.poloniex.com and subscribe to ticker. I can\'t find any working example in python. I have tried to use autobahn/twisted and websocket-cli

4条回答
  •  失恋的感觉
    2020-12-07 17:29

    This uses the undocumented websocket endpoint because Poloniex has pulled support for the original WAMP socket endpoint.

    import websocket
    import thread
    import time
    import json
    
    def on_message(ws, message):
        print(message)
    
    def on_error(ws, error):
        print(error)
    
    def on_close(ws):
        print("### closed ###")
    
    def on_open(ws):
        print("ONOPEN")
        def run(*args):
            ws.send(json.dumps({'command':'subscribe','channel':1001}))
            ws.send(json.dumps({'command':'subscribe','channel':1002}))
            ws.send(json.dumps({'command':'subscribe','channel':1003}))
            ws.send(json.dumps({'command':'subscribe','channel':'BTC_XMR'}))
            while True:
                time.sleep(1)
            ws.close()
            print("thread terminating...")
        thread.start_new_thread(run, ())
    
    
    if __name__ == "__main__":
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
                                  on_message = on_message,
                                  on_error = on_error,
                                  on_close = on_close)
        ws.on_open = on_open
        ws.run_forever()
    

    The channels are:

    1001 = trollbox (you will get nothing but a heartbeat)
    1002 = ticker
    1003 = base coin 24h volume stats
    1010 = heartbeat
    'MARKET_PAIR' = market order books
    

提交回复
热议问题