Connecting Python to the GDAX Websocket Feed
Reading the GDAX Feed using Python
GDAX provides a public websocket service which allows anyone to read real-time GDAX data. This is a great service when you consider that it is free to anyone that has the skills to utilize it. This feed could be used for automated trading purposes or for performing real-time calculations that are not included in the GDAX web UI.
In this case, there is not an official GDAX Python module. There are some notable modules on GitHub which you could utilize. We will put together some code using the well established websocket module.
A WORD OF CAUTION: Coinbase handles financial assets. Always use the sandbox when testing code and ideas. Use appropriate security measures when using API credentials.
Goals
- Create a subscription request in JSON format
- Send the subscription request to wss://ws-feed.gdax.com
- Display the results
- Display the execution duration in seconds each time
Prep
- Install the python websocket and json modules
- Choose the GDAX Channels to join
Python Code
I will be subscribing to the Litecoin ticker using the code below. Feel free to use the currency of your choice.
from websocket import create_connection import json, time # Tracking execution time start = time.time() # Create connection ws = create_connection("wss://ws-feed.gdax.com") # Create subscription message message = { "type": "subscribe", "channels": [{"name": "ticker", "product_ids": ["LTC-USD"]}] } # Send subscribe Message ws.send(json.dumps(message)) result = ws.recv() print result ws.close() # execution time print "\nExecution Time: " + str(time.time() - start)
Notes
- The subscribe message needs to be sent once
- Omit the ws.close() statement to keep the websocket connection open
- Run the ws.recv() command to read the feed
- The subscribe message needs to be sent once
- Omit the ws.close() statement to keep the websocket connection open
- Run the ws.recv() command to read the feed
Result
{"type":"ticker","sequence":585932452,"product_id":"LTC-USD","price":"58.72000000","open_24h":"57.90000000","volume_24h":"920408.37260391","low_24h":"55.25000000","high_24h":"60.96000000","volume_30d":"17232432.91842303","best_bid":"58.71","best_ask":"58.72"} Execution Time: 0.608999967575
And Then?
In a future post, we will look at how to store this feed data, perform useful calculations, and then visualize the data.
You might be interested in Lomond: https://www.willmcgugan.com/blog/tech/post/stream-btc-prices-over-websockets-with-python-and-lomond/
ReplyDelete