如果我在订阅消息中使用这些参数:
params = {
"type": "subscribe",
"channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
}
每次执行新交易时(在http://www.gdax.com上可见),我都会从网络套接字收到这种消息:
{
u'best_ask': u'3040.01',
u'best_bid': u'3040',
u'last_size': u'0.10000000',
u'price': u'3040.00000000',
u'product_id': u'BTC-EUR',
u'sequence': 2520531767,
u'side': u'sell',
u'time': u'2017-09-16T16:16:30.089000Z',
u'trade_id': 4138962,
u'type': u'ticker'
}
就在这条特定消息之后,我在https://api.gdax.com/products/BTC-EUR/ticker上进行了访问,我得到了这个:
{
"trade_id": 4138962,
"price": "3040.00000000",
"size": "0.10000000",
"bid": "3040",
"ask": "3040.01",
"volume": "4121.15959844",
"time": "2017-09-16T16:16:30.089000Z"
}
与获取请求相比,来自 Web 套接字的当前数据相同。
请在下面找到使用此代码实现 Web 套接字的完整测试脚本。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test for websockets."""
from websocket import WebSocketApp
from json import dumps, loads
from pprint import pprint
URL = "wss://ws-feed.gdax.com"
def on_message(_, message):
"""Callback executed when a message comes.
Positional argument:
message -- The message itself (string)
"""
pprint(loads(message))
print
def on_open(socket):
"""Callback executed at socket opening.
Keyword argument:
socket -- The websocket itself
"""
params = {
"type": "subscribe",
"channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
}
socket.send(dumps(params))
def main():
"""Main function."""
ws = WebSocketApp(URL, on_open=on_open, on_message=on_message)
ws.run_forever()
if __name__ == '__main__':
main()