2

我正在尝试获取要使用的最后价格数据,这很容易使用 /ticker 端点上的轮询,即

rawticker = requests.get('https://api.gdax.com/products/BTC-EUR/ticker')
json_data = json.loads(rawticker.text)
price = json_data['price']

但 GDAX API 不鼓励轮询。我如何使用 websocket 获得相同的信息。我怎样才能让下面的代码只运行一次,然后提取价格信息。

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()

谢谢你的帮助。

4

1 回答 1

1

当您想要实时更新时,不鼓励拉取。在这种情况下,建议使用 Web Sockets。但是,在您的情况下,运行一次代码并退出,使用拉取端点就可以了。

无论如何要回答你的问题。on_message的第一个参数是WebSocketApp你可以在收到第一条消息后简单地添加这一行来关闭它。

def on_message(ws, message):
    """Callback executed when a message comes.
    Positional argument:
    message -- The message itself (string)
    """
    pprint(loads(message))
    ws.close()

小费

Requests 库已内置.json(),您可以在.get()返回时直接使用

import requests
rawticker = requests.get('https://api.gdax.com/products/BTC-EUR/ticker').json()
price = rawticker['price']
print(price)
于 2018-01-27T20:52:50.183 回答