Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Update: Here's the code that finally worked.

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()
like image 699
Emily Avatar asked Nov 17 '15 21:11

Emily


People also ask

How does Python connect to WebSockets?

WebSocket Client with PythonCreate a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.

What is WebSocket API in Python?

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio, Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.


Video Answer


3 Answers

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)
like image 151
gre_gor Avatar answered Oct 11 '22 02:10

gre_gor


I think you are mixing here 2 different python packages. One is the websockets package which is the line you eventually commented out (#ws.connect("wss://api2.bitfinex.com:3000/ws")), and the other one is the actual package you are using which is websocket-client

like image 27
carkod Avatar answered Oct 11 '22 02:10

carkod


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})
like image 2
Alkindus Avatar answered Oct 11 '22 02:10

Alkindus