如何从 GDAX websocket feed 获取实时出价/要价/价格

How to get real time bid / ask / price from GDAX websocket feed

API 文档不鼓励在 /ticker 端点上进行轮询,并建议使用 websocket 流来侦听匹配消息

但是匹配响应只提供一个price和一个side(卖/买)

如何从 websocket 提要中重新创建代码数据(价格、要价和出价)?

{
  “price”: “333.99”,
  “size”: “0.193”,
  “bid”: “333.98”,
  “ask”: “333.99”,
  “volume”: “5957.11914015”,
  “time”: “2015-11-14T20:46:03.511254Z”
}

ticker 端点和 websocket 都提供 return 和 'price',但我想这不一样​​。来自 ticker 端点的 price 是一段时间内的某种平均值吗?

如何计算 Bid 值、Ask 值?

如果我在 subscribe 消息中使用这些参数:

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 上执行了 get,我得到了这个:

{
  "trade_id": 4138962,
  "price": "3040.00000000",
  "size": "0.10000000",
  "bid": "3040",
  "ask": "3040.01",
  "volume": "4121.15959844",
  "time": "2017-09-16T16:16:30.089000Z"
}

get 请求相比,来自网络套接字的当前数据相同。

请在下面找到一个完整的测试脚本,该脚本实现了带有此代码的网络套接字。

#!/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()