Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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-client 0.32.0.

The purpose of this is to get real time ticker data and store it in a mysql database.

So far I have tried to use examples provided in library documentation. They work for localhost or the test server but if I change to wss://api.poloniex.com I get a bunch of errors.

here is my attempt using websocket-client 0.32.0:

from websocket import create_connection
ws = create_connection("wss://api.poloniex.com")
ws.send("ticker")
result = ws.recv()
print "Received '%s'" % result
ws.close()

and this is using autobahn/twisted:

from autobahn.twisted.websocket import WebSocketClientProtocol
from autobahn.twisted.websocket import WebSocketClientFactory


class MyClientProtocol(WebSocketClientProtocol):

    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))

    def onOpen(self):
        print("WebSocket connection open.")

        def hello():
            self.sendMessage(u"ticker".encode('utf8'))
            self.sendMessage(b"\x00\x01\x03\x04", isBinary=True)
            self.factory.reactor.callLater(1, hello)

        # start sending messages every second ..
        hello()

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketClientFactory("wss://api.poloniex.com", debug=False)
    factory.protocol = MyClientProtocol

    reactor.connectTCP("wss://api.poloniex.com", 9000, factory)
    reactor.run()

A complete but simple example showing how to connect and subscribe to to a websocket push api using any python library would be greatly appreciated.

like image 810
Matei Razvan Avatar asked Aug 22 '15 08:08

Matei Razvan


People also ask

How do I import a WebSocket client in Python?

Open your macOS terminal. Type “ pip install websocket-client ” without quotes and hit Enter . If it doesn't work, try "pip3 install websocket-client" or “ python -m pip install websocket-client “. Wait for the installation to terminate successfully.

What is Poloniex API?

Poloniex provides both HTTP and websocket APIs for interacting with the exchange. Both allow read access to public market data and private read access to your account. Private write access to your account is available via the private HTTP API.


1 Answers

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
like image 109
Ricky Han Avatar answered Sep 19 '22 17:09

Ricky Han