【问题标题】:Python - Poloniex Push APIPython - Poloniex 推送 API
【发布时间】:2018-01-02 07:25:06
【问题描述】:

我正在尝试通过推送 API 从 Poloniex 获取 Python 2.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 上运行程序。我应该以某种方式激活 Crossbar 吗?

  2. 如何退出连接?我只是用Ctrl+c 杀死了这个进程,现在当我尝试再次运行它时,我得到了错误:ReactorNonRestartable

【问题讨论】:

    标签: python wamp autobahn poloniex


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      我发现 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()
      

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

      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”是货币对 id,这是无证的,在此处提到的其他堆栈溢出问题中也没有答案。

      但是,如果您访问此网址: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())
      

      将返回您想要的数据,但您必须将其置于循环中以获取不断更新的信息。收到数据后不确定您的需求,因此我将剩下的交给您。

      希望这会有所帮助!

      【讨论】:

      • 您从哪里得知他们正在取消 WAMP 支持?他们的 API 文档仍然声称这是使用它的方式。
      • 感谢@scott_det 的解决方案!我和@Nate 有同样的问题,在 WAMP 上浪费了几个小时。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2018-04-17
      相关资源
      最近更新 更多