Skip to main content
 首页 » 编程设计

python之Websocket 到 Python 中的可用数据之从 GDAX websocket feed 获取价格

2025年01月19日43开发

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

感谢您的帮助。

请您参考如下方法:

当您想要实时更新时,不鼓励拉取。在这种情况下,建议使用 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)