Python - Poloniex Push API



我正在尝试通过推送API从Poloniex获取Python 2.7.13中的实时数据。 我阅读了许多帖子(包括如何使用python库连接到 poloniex.com websocket api(,并得出了以下代码:

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. 如果有人能引导我完成订阅和获取股票代码数据的过程,我将不胜感激,我将从第 0 步开始用 python 详细说明:我在 Windows 上的 Spyder 上运行该程序。我应该以某种方式激活横杆吗?

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

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

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

最终最适合我的代码实际上来自您在上面链接到的帖子,但我在其他地方发现了一些关于货币对 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,这是未记录的,在这里提到的另一个堆栈溢出问题中也没有答案。

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

将返回您想要的数据,但您必须将其置于循环中才能不断更新信息。收到数据后不确定您的需求,所以我将把其余的留给您。

希望这有帮助!

在其他帖子的帮助下,我制作了以下代码,以使用 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:xyDesktopzfolder_name'
df.to_csv(os.path.join(path,r'%s.csv' % pairs[i]))
i += 1

最新更新