Python - Poloniex Push API

I am trying to get Live data in Python 2.7.13 from Poloniex via the push API. I read a lot of posts (including How to connect to poloniex.com websocket api using the python library ) and I came to the following code:

from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.wamp import ApplicationRunner
from twisted.internet.defer import inlineCallbacks
import six


class PoloniexComponent(ApplicationSession):
    def onConnect(self):
        self.join(self.config.realm)

    @inlineCallbacks
    def onJoin(self, details):
        def onTicker(*args):
            print("Ticker event received:", args)

        try:
            yield self.subscribe(onTicker, 'ticker')
        except Exception as e:
            print("Could not subscribe to topic:", e)


def main():
    runner = ApplicationRunner(six.u("wss://api.poloniex.com"), six.u("realm1"))
    runner.run(PoloniexComponent)


if __name__ == "__main__":
    main()

Now, when I run the code, it looks like it is working successfully, but I do not know where I get the data. I have two questions:

  • I would really appreciate if anyone could go through the process of subscribing and receiving ticker data, which I will discuss in detail in python starting from step 0: I run the program on Spyder on Windows. Should I somehow activate Crossbar?

  • ? Ctrl+c, , , : ReactorNonRestartable.

+4
2

, Poloniex Python2.7, , , , , , .

, Poloniex WAMP-, , , . , , , , .

, , , , , - .

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()

, , , , , :

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

, :

[121,"2759.99999999","2759.99999999","2758.000000‌​00","0.02184376","12‌​268375.01419869","44‌​95.18724321",0,"2767‌​.80020000","2680.100‌​00000"]]

, "121" , , , .

, URL: https://poloniex.com/public?command=returnTicker, , , id- > currency , .

, - :

import urllib
import urllib2
import json

ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=returnTicker'))
print json.loads(ret.read())

, , . , , .

, !

+3

, Python 3.x. , :

#TO SAVE THE HISTORICAL DATA (X MINUTES/HOURS) OF EVERY CRYPTOCURRENCY PAIR IN POLONIEX:

    from poloniex import Poloniex
    import pandas as pd
    from time import time
    import os

    api = Poloniex(jsonNums=float)

    #Obtains the pairs of cryptocurrencies traded in poloniex
    pairs = [pair for pair in api.returnTicker()]

    i = 0
    while i < len(pairs):
        #Available candle periods: 5min(300), 15min(900), 30min(1800), 2hr(7200), 4hr(14400), and 24hr(86400)
        raw = api.returnChartData(pairs[i], period=86400, start=time()-api.YEAR*10)
        df = pd.DataFrame(raw)

        # adjust dates format and set dates as index
        df['date'] = pd.to_datetime(df["date"], unit='s')
        df.set_index('date', inplace=True)

        # Saves the historical data of every pair in a csv file
        path=r'C:\x\y\Desktop\z\folder_name'
        df.to_csv(os.path.join(path,r'%s.csv' % pairs[i]))

        i += 1
0

Source: https://habr.com/ru/post/1682344/


All Articles