我想订阅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()

推荐答案

The documentation表示所有消息都是JSON编码的.

Message encoding

通过Bitfinex的websocket通道发送和接收的每条消息都以JSON格式编码

你需要导入json个库,对你的信息进行编码和解码.

The documentation mentions three public channels: book, trades and ticker.
If you want to subscribe to a channel, you need to send a subscribe event.

根据the documentation,认购LTCBTC交易的示例:

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

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

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

Python-3.x相关问答推荐

文件名中的文件打开和撇号

如何使用 Selenium Python 连续单击一个按钮直到另一个元素出现?

Python根据条件从多行读取值

如何将 WebDriver 传输到导入的测试?

根据按不同列中的值分组的平均值划分 DataFrame

转换Pandas 数据框 - 添加行

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

如何在 Telethon 中向机器人发送发送表情符号

python 3.10.5 中可能存在的错误. id 函数工作不明确

matplotlib.pyplot 多边形,具有相同的纵横比和紧凑的布局

如何在 on_ready 事件中使用 change_presence? (discord.py)

机器学习实验笔记本的工作区 url

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

Seaborn 热图 colored颜色 条标签作为百分比

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

asyncio.Semaphore RuntimeError: Task got Future 附加到不同的循环

如何在 jupyter notebook 5 中逐行分析 python 3.5 代码

pdfminer python 3.5

如何创建一个永远在其上运行滚动协程的事件循环?

TypeError:无法实例化类型元组;使用 tuple() 代替