-1

I know this may be a dumb question but I am still learning web-sockets with python.

Here is the code I have for testing out the api.

import json

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


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

ws.close()

Now here is my issue. I know with the REST API you can define variable and assign a JSON request to it for example.

bitFinexTick = requests.get("https://api.bitfinex.com/v1/ticker/btcusd")
return bitFinexTick.json()['last_price']

This would return the following

{"mid":"2276.85","bid":"2274.6","ask":"2279.1","last_price":"2275.0","timestamp":"1495763263.217562408"}

and then output

"2275.0"

However, with the websocket API the response is not labled, for example below.

[5, 2306.9, 0.0989, 2307.2, 0.07409371, -176.49194056, -0.0711, 2307.2, 55446.734771, 2690, 2141.1]

The data format following bitfinex's documentation is the following.

[
   "<CHANNEL_ID>",
   "<BID>",
   "<BID_SIZE>",
   "<ASK>",
   "<ASK_SIZE>",
   "<DAILY_CHANGE>",
   "<DAILY_CHANGE_PERC>",
   "<LAST_PRICE>",
   "<VOLUME>",
   "<HIGH>",
   "<LOW>"
]

Now my question is, how do I pull specifically only the LAST_PRICE from the json array and assign it to result?

Thanks a million for the help!

xxen0nxx
  • 87
  • 1
  • 5

1 Answers1

-1

So you have what in python is a list right?

So you just do:

return bitFinexTick.json()[7]

Instead of

return bitFinexTick.json()['last_price']

This is because they aren't returning a 'dictionary' - where they are nicely naming the keys and values, just a list of values.

So you know that the value you want (last_price) is always going to be the 8th value in the list. Therefore the index of that value is 7, seeing as we start counting indexes at 0 in Python.

Callam Delaney
  • 641
  • 3
  • 15