Emily
Emily

Reputation: 2331

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?

Upvotes: 25

Views: 34945

Answers (2)

Alkindus
Alkindus

Reputation: 2312

I prefer to send parameters on open and add ssl to prevent errors

import websocket
import ssl
import json

SOCKET = 'wss://api-pub.bitfinex.com/ws/2'

params = {
    "event": "subscribe",
    "channel": "book",
    "pair": "BTCUSD",
    "prec": "P0"
    }

def on_open(ws):
    print('Opened Connection')
    ws.send(json.dumps(params))

def on_close(ws):
    print('Closed Connection')

def on_message(ws, message):
    print (message)

def on_error(ws, err):
  print("Got a an error: ", err)


ws = websocket.WebSocketApp(SOCKET, on_open = on_open, on_close = on_close, on_message = on_message,on_error=on_error)
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

Upvotes: 1

gre_gor
gre_gor

Reputation: 6802

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)

Upvotes: 20

Related Questions