pythonpython-3.xwebsocket

How To Subscribe To Websocket API Channel Using Python?


I'm trying to subscribe to the Bitfinex.com websocket API public channel BTCUSD.

Here's the code:

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

I believe ws.send("BTCUSD") is what subscribes to the public channel? I get a message back I think is confirming the subscription ({"event":"info","version":1}, but I don't get the stream of data afterward. What am I missing?


Solution

  • The documentation says all the messages are JSON encoded.

    Message encoding

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

    You need to import json library, to encode and decode your messages.

    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.

    Example of subscribing to the LTCBTC trades, according to the documentation:

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

    Then you also need to parse the incoming JSON encoded messages.

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