How to easily get Bitcoin price quotes in Python

Overview – Bitcoin price quotes in Python

Bitcoin is back in the spotlight. Meanwhile as I am writing this the price is over $18K USD. What better time to write a tutorial on getting Bitcoin price quotes in Python. We can do it using the Python requests library and the Coindesk API. Coindesk has a Bitcoin Price Index called the BPI. It calculates an average price from exchanges Coindesk tracks. As a result you get a better idea of the price across all Bitcoin exchanges vs one exchange. The API is free and does not require authentication.

Getting Bitcoin (BTC) price data from Coindesk

Step 1 – Look at the Bitcoin price data

Before we jump into Python, lets look at the data. To do this open the URL in your browser or an command line client such as curl.

curl https://api.coindesk.com/v1/bpi/currentprice.json

As you can see from the URL we will be getting JSON data. Here it is structured in an easy to read format.

{
   "time":{
      "updated":"Nov 18, 2020 05:31:00 UTC",
      "updatedISO":"2020-11-18T05:31:00+00:00",
      "updateduk":"Nov 18, 2020 at 05:31 GMT"
   },
   "disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
   "chartName":"Bitcoin",
   "bpi":{
      "USD":{
         "code":"USD",
         "symbol":"$",
         "rate":"18,248.4250",
         "description":"United States Dollar",
         "rate_float":18248.425
      },
      "GBP":{
         "code":"GBP",
         "symbol":"£",
         "rate":"13,760.7906",
         "description":"British Pound Sterling",
         "rate_float":13760.7906
      },
      "EUR":{
         "code":"EUR",
         "symbol":"€",
         "rate":"15,375.6119",
         "description":"Euro",
         "rate_float":15375.6119
      }
   }
}

I want to get the price in USD out of this JSON data structure and display it. To do this I will go to my Linux command prompt and run a few commands and a write a quick script.

Step 2 – Install the Python requests library

Requests is a python client library for HTTP. It makes accessing web sites and HTTP APIs easy. The simplest way to install requests is using PIP. PIP is the Package Installer for Python. Most operating systems with Python will have PIP installed. If for some reason you don’t, check out get-pip.py. It is a script you can use to bootstrap PIP. To install requests run this command:

pip3 install requests

Step 3 – Use requests to access the API

Now we will write a some code to access the API using requests. Put the following code in a file with a .py extension. I called mine btc.py and it looks like this:

#!/usr/bin/env python
# This is my btc.py script.
import requests
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(data)

Lets walk through this line by line:

  • 1 indicates which interpreter to use for this script. It’s a Python script so we want to use Python.
  • 2 is comment I put in.
  • 3 imports the requests library we installed earlier. As a result I can now access in this script as requests.
  • 4 calls the get function on the requests library and passes in a URL as a parameter. It assigns what is returned to a variable called response.
  • 5 calls the json() method on the response object we just created. This method returns the JSON we received in the API call as a python dictionary. It assigns the results to a variable called data.
  • Finally 6 prints the JSON data.

Run the script using your Python interpreter. Remember I named mine btc.py.

python3 btc.py

The script out should look like this.

{'time': {'updated': 'Nov 18, 2020 06:49:00 UTC', 'updatedISO': '2020-11-18T06:49:00+00:00', 'updateduk': 'Nov 18, 2020 at 06:49 GMT'}, 'disclaimer': 'This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org', 'chartName': 'Bitcoin', 'bpi': {'USD': {'code': 'USD', 'symbol': '$', 'rate': '17,798.2033', 'description': 'United States Dollar', 'rate_float': 17798.2033}, 'GBP': {'code': 'GBP', 'symbol': '£', 'rate': '13,415.5381', 'description': 'British Pound Sterling', 'rate_float': 13415.5381}, 'EUR': {'code': 'EUR', 'symbol': '€', 'rate': '14,989.8782', 'description': 'Euro', 'rate_float': 14989.8782}}}

But let’s format it make it more readable:

{
   "time":{
      "updated":"Nov 18, 2020 06:40:00 UTC",
      "updatedISO":"2020-11-18T06:40:00+00:00",
      "updateduk":"Nov 18, 2020 at 06:40 GMT"
   },
   "disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
   "chartName":"Bitcoin",
   "bpi":{
      "USD":{
         "code":"USD",
         "symbol":"$",
         "rate":"17,817.2600",
         "description":"United States Dollar",
         "rate_float":17817.26
      },
      "GBP":{
         "code":"GBP",
         "symbol":"£",
         "rate":"13,429.9023",
         "description":"British Pound Sterling",
         "rate_float":13429.9023
      },
      "EUR":{
         "code":"EUR",
         "symbol":"€",
         "rate":"15,005.9280",
         "description":"Euro",
         "rate_float":15005.928
      }
   }
}

Step 4 – Select and print the USD Bitcoin price

Now we will update the script to select just the data we want. Looking at the formatted data we see we need to dig into the "bpi" object. To get the object lets change the last line of our script:

#!/usr/bin/env python
# This is my btc.py script.
import requests
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(data["bpi"])

We have changed line 6 to print the value stored in the "bpi" key of the Python dictionary.

Finally let’s take it one step further and get the price data.

#!/usr/bin/env python
# This is my btc.py script.
import requests
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(data["bpi"]["USD"]["rate"])

Now when I run the script I get the latest price data:

python3 btc.py
17,809.7333

Conclusion

In conclusion, you are now able to query the Coinbase API for BTC price data. Hence you can use this script as a foundation for integrating Bitcoin prices into other projects. For example a slack bot that message your the price or a cron job that alerts you when the price has moved. As a next step I suggest trying to extract more data out the JSON object returned by the Coindesk API. Additionally you can check out more coding related posts on Linuxhit.com.

References

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.