我正在try 连接到wss://api.poloniex.com并订阅ticker.我在python中找不到任何有效的示例.我try 过使用autobahn/twisted和websocket客户端0.32.0.

其目的是获取实时股票行情数据,并将其存储在mysql数据库中.

到目前为止,我已经try 使用图书馆文档中提供的示例.它们适用于本地主机或测试服务器,但如果我改为wss://api.poloniex.com我犯了很多错误.

下面是我使用websocket客户端0.32.0的try :

from websocket import create_connection
ws = create_connection("wss://api.poloniex.com")
ws.send("ticker")
result = ws.recv()
print "Received '%s'" % result
ws.close()

这是使用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推送api,将不胜感激.

推荐答案

通过使用WAMP,尤其是使用autobahn library(您已经在try 使用)的WAMP模块,可以完成您想要完成的任务.

在遵循他们的文档之后,我用autobahn和asyncio创建了一个简单的示例.以下示例订阅"ticker"提要并打印收到的值:

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

Python-3.x相关问答推荐

正则表达式匹配并提取括号前的单词

字符串块数组:如何根据一个数组中的元素对另一个数组中的元素进行分组

如何验证具有内部json字符串的json字符串?

没有这样的命令';角色';-可靠分子

为什么我无法在django中按月筛选事件?

Python:如何在Pandas 的 .agg 函数中使用 value_counts()?

当我判断另一个 checkButton 时,如何判断两个 python tkinter checkButtons?

为什么 Multiprocessing 的 Lock 不会阻止其他进程使用对象?

列表中的重复数字与列表理解

聚合(aggregate)为最多包含两个元素的列表

在python中循环处理时并行写入文件

从 yahoo Finance python 一次下载多只股票

RGB 图像中最主要的 colored颜色 - OpenCV / NumPy / Python

python3源的类图查看器应用程序

python3:字节与字节数组,并转换为字符串和从字符串转换

两个Pandas数据框中的共同列列表

python 3的蓝牙库

如何使用请求发送带有标头的 PATCH 请求

Django Rest 框架 ListField 和 DictField

有效地判断一个元素是否在列表中至少出现 n 次