Websocket to useable data in Python - get price from GDAX websocket feed

2.1k Views Asked by At

I am trying to get the last price data to use which is easy enough using polling on /ticker endpoint i.e.

rawticker = requests.get('https://api.gdax.com/products/BTC-EUR/ticker')
json_data = json.loads(rawticker.text)
price = json_data['price']

but the GDAX API discourages polling. How could I get the same information using websocket. How could I get the following code to run just once and then extract the price information.

from websocket import WebSocketApp
from json import dumps, loads
from pprint import pprint

URL = "wss://ws-feed.gdax.com"

def on_message(_, message):
    """Callback executed when a message comes.
    Positional argument:
    message -- The message itself (string)
    """
    pprint(loads(message))
    print

def on_open(socket):
    """Callback executed at socket opening.
    Keyword argument:
    socket -- The websocket itself
    """
    params = {
        "type": "subscribe",
        "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}]
    }
    socket.send(dumps(params))

def main():
    """Main function."""
    ws = WebSocketApp(URL, on_open=on_open, on_message=on_message)
    ws.run_forever()

if __name__ == '__main__':
    main()

Thanks for any help.

1

There are 1 best solutions below

0
On

Pulling is discouraged when you want to have real-time updates. In that case, it is recommended to use Web Sockets. In your case, however, running the code once and exiting, it is fine to use the pull endpoint.

To answer your question anyway. on_message's first argument is the WebSocketApp you can simply add this line to close it after receiving the first message.

def on_message(ws, message):
    """Callback executed when a message comes.
    Positional argument:
    message -- The message itself (string)
    """
    pprint(loads(message))
    ws.close()

Tip

Requests library has built-in .json() that you can use directly on the .get() return

import requests
rawticker = requests.get('https://api.gdax.com/products/BTC-EUR/ticker').json()
price = rawticker['price']
print(price)