【问题标题】:Websocket to useable data in Python - get price from GDAX websocket feedWebsocket 到 Python 中的可用数据 - 从 GDAX websocket 提要获取价格
【发布时间】:2017-12-27 23:59:15
【问题描述】:

我正在尝试获取要使用的最后价格数据,这很容易使用 /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()

感谢您的帮助。

【问题讨论】:

    标签: python coinbase-api gdax-api


    【解决方案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() return 上使用它

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

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多