Python Poloniex推送API

2024-04-29 01:07:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过pushapi从Poloniex获得python2.7.13中的实时数据。 我阅读了许多帖子(包括How to connect to poloniex.com websocket api using a python library),并得出以下代码:

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

现在,当我运行代码时,它看起来运行得很成功,但是我不知道我从哪里得到数据。我有两个问题:

  1. 如果有人能指导我完成订阅和获取股票数据的过程,我将在python中详细说明,从第0步开始:我在Windows上的Spyder上运行程序。我应该激活横杆吗?

  2. 我如何退出连接?我简单地用Ctrl+c终止了进程,现在当我再次尝试运行它时,我得到了一个错误:ReactorNonRestartable


Tags: to数据代码fromimportselfcomapi
2条回答

在其他帖子的帮助下,我编写了以下代码,用python3.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

我在使用Poloniex和Python2.7时遇到了很多问题,但最终找到了一个解决方案,希望能对您有所帮助。在

我发现Poloniex已经取消了对原始WAMP套接字端点的支持,所以我可能会完全偏离这个方法。也许这就是你所需要的全部答案,但如果不是的话,这里有一个获取股票信息的替代方法。在

最终对我最有用的代码实际上是从您linked到上面的文章,但是我在别处找到了一些关于货币对id的信息。在

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

我注释掉了那些你似乎不想要的数据,但是这里有一些来自上一篇文章的更多信息作为参考:

^{pr2}$

现在您应该得到一些如下所示的数据:

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

这也很烦人,因为开头的“121”是货币对id,这是没有文档记录的,在这里提到的另一个堆栈溢出问题中也没有答案。在

但是,如果您访问这个url:https://poloniex.com/public?command=returnTicker,那么id似乎显示为第一个字段,因此您可以创建自己的id->;货币对映射,或者通过您希望从中获得的id解析数据。在

或者,简单到:

import urllib
import urllib2
import json

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

将返回给您所需的数据,但您必须将其放入循环中以获取不断更新的信息。收到数据后不确定你的需求,所以我将把剩下的留给你。在

希望这有帮助!在

相关问题 更多 >