4

我正在尝试使用 Coinbase Exchange API 构建订单簿快照,特别是使用 Websocket 提要。

https://docs.exchange.coinbase.com/?python#websocket-feed

我相信我成功地建立了连接并发送了初始订阅消息。在初始订阅消息之后,我期待 onMessage 事件。但似乎没有这样的消息到达。最终连接超时并关闭。

编码:

from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
import json

class ClientProtocol(WebSocketClientProtocol):
    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))
    def initMessage(self):
        message_data = [{"type": "subscribe", "product_id": "BTC-USD"}]
        message_json = json.dumps(message_data)
        print "sendMessage: " + message_json
        self.sendMessage(message_json)
    def onOpen(self):
        print "onOpen calls initMessage()"
        self.initMessage()
    def onMessage(self, msg, binary):
        print "Got echo: " + msg
    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketClientFactory("wss://ws-feed.exchange.coinbase.com")
    factory.protocol = ClientProtocol
    connectWS(factory)
    reactor.run()

输出:

python order_twisted.py
服务器连接:tcp4:190.93.242.231:443
onOpen 调用 initMessage()
sendMessage: [{"type": "subscribe", "product_id": "BTC-USD"}]
WebSocket 连接关闭:连接被不干净地关闭(对等方在没有先前 WebSocket 关闭握手的情况下丢弃了 TCP 连接)
4

1 回答 1

2

您将订阅请求作为字典的 JSON 数组发送,而应该只是字典。将代码更改为:

def initMessage(self):
    message_data = [{"type": "subscribe", "product_id": "BTC-USD"}]
    message_json = json.dumps(message_data)
    ...

至:

def initMessage(self):
    message_data = {"type": "subscribe", "product_id": "BTC-USD"}
    message_json = json.dumps(message_data)
    ...

通过此更改,您的代码成功订阅...

于 2015-02-08T17:40:35.577 回答