如何连接到poloniex.com的WebSocket API使用Python库 [英] How to connect to poloniex.com websocket api using a python library

查看:2503
本文介绍了如何连接到poloniex.com的WebSocket API使用Python库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图连接到WSS://api.poloniex.com和订阅股票。我找不到任何蟒工作的例子。我曾尝试使用高速公路/双绞线和WebSocket的客户端0.32.0。

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.

这样做的目的是为了获得实时股票数据并将其存储在MySQL数据库。

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

到目前为止,我曾尝试使用库文档中提供的例子。他们对本地主机或测试服务器的工作,但如果我改变WSS://api.poloniex.com我收到了一堆错误

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.

这是我尝试使用WebSocket的客户端0.32.0:

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

展示了如何连接和使用任何Python库将大大AP preciated订阅到WebSocket的推送API一个完整而简单的例子。

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.

推荐答案

你正在尝试完成可以通过使用 WAMP <完成/ A>,具体使用高速公路库的WAMP模块(您已经尝试使用)。

What you are trying to accomplish can be done by using WAMP, specifically by using the WAMP modules of the autobahn library (that you are already trying to use).

跟随他们的文档后,我设法建立使用高速公路和ASYNCIO一个简单的例子。下面的例子订阅了股票饲料和打印接收到的值:

After following their docs, I managed to set-up a simple example using autobahn and asyncio. The following example subscribes to the 'ticker' feed and prints the received values:

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine


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

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

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


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


if __name__ == "__main__":
    main()

您可以找到有关WAMP编程高速公路在这里更多的细节: http://autobahn.ws/蟒蛇/ WAMP / programming.html

You can find more details about WAMP programming with autobahn here: http://autobahn.ws/python/wamp/programming.html

这篇关于如何连接到poloniex.com的WebSocket API使用Python库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆