我正在尝试使用Coinbase Exchange API构建订单快照,特别是使用Websocket Feed。
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 orders_twisted.py Server connected: tcp4:190.93.242.231:443 onOpen calls initMessage() sendMessage: [{"type": "subscribe", "product_id": "BTC-USD"}] WebSocket connection closed: connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
答案 0 :(得分:1)
您将订阅请求作为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)
...
通过此更改,您的代码已成功订阅...