如何使用Python订阅Websocket API频道?

2024-05-18 12:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试订阅Bitfinex.com websocket API公共频道BTCUSD

代码如下:

from websocket import create_connection
ws = create_connection("wss://api2.bitfinex.com:3000/ws")
ws.connect("wss://api2.bitfinex.com:3000/ws")
ws.send("LTCBTC")
while True:

    result = ws.recv()
    print ("Received '%s'" % result)

ws.close()

我相信ws.send("BTCUSD")是什么订阅了公共频道?我收到一条消息,我想是在确认订阅({"event":"info","version":1},但之后我没有得到数据流。我错过了什么?

更新:这是最终成功的代码。

import json

from websocket import create_connection
ws = create_connection("wss://api2.bitfinex.com:3000/ws")
#ws.connect("wss://api2.bitfinex.com:3000/ws")
ws.send(json.dumps({
    "event": "subscribe",
    "channel": "book",
    "pair": "BTCUSD",
    "prec": "P0"
}))


while True:
    result = ws.recv()
    result = json.loads(result)
    print ("Received '%s'" % result)

ws.close()

Tags: 代码importcomsendjsonwscreateresult
1条回答
网友
1楼 · 发布于 2024-05-18 12:33:22

The documentation说所有消息都是JSON编码的。

Message encoding

Each message sent and received via the Bitfinex’s websocket channel is encoded in JSON format

您需要导入json库,以便对消息进行编码和解码。

The documentation提到三个公共频道:booktradesticker
如果要订阅频道,则需要发送订阅事件。

根据the documentation,订阅LTCBTC交易的示例:

ws.send(json.dumps({
    "event":"subscribe",
    "channel":"trades",
    "channel":"LTCBTC"
})

然后还需要解析传入的JSON编码消息。

result = ws.recv()
result = json.loads(result)

相关问题 更多 >

    热门问题