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

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

问题描述

我正在尝试连接到 wss://api.poloniex.com 并订阅股票代码.我在 python 中找不到任何工作示例.我曾尝试使用高速公路/扭曲和 websocket-client 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-client 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 库连接和订阅 websocket push 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,特别是通过使用高速公路库的 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 设置了一个简单的示例.以下示例订阅ticker"提要并打印接收到的值:

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/python/wamp/programming.html

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

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

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