CoinGecko API: Getting Crypto Values

A use case for the CoinGecko API
This section describes a use case for the CoinGecko API.
This use case has been developed by me in Python and the full code is on my GitHub.

Prerequisites

To use the CoinGecko API you first need to create an account on their website.
Then, you need to create an API token. The free plan currently allows you to make 10k API calls per month.

Requirements

The program uses the match statement that, at the time of writing this documentation (November 2023) requires Python 3.10 (or newer versions).
As the program calls an API, you also need the requests library. You can install it via: $ pip install requests

Getting started

When you use this software you need to launch the initial.py file via $ python3 initial.py. This will create a file, called settings.py, which stores your email and your API token: this way, every time you use this software, you won't need to insert them
After that, you can launch the main file via $ python3 main.py.
Here's how the initial.py file works (code reference here):
  • The user inserts the email and the API KEY via CLI.
  • The program checks if the settings.py file exists in the settings folder., then
    • If exists, it warns the user that the file already exists.
    • If it doesn't exist, it creates it and stores the email and the API KEI inserted by the user.

Structure of the main file

After the first usage, always invoke the main file via $ python3 main.py.
Here's what it does:
  1. 1.
    It imports the email and the API token from the settings.py file.
  2. 2.
    It prints a welcome message reporting the version of the software.
  3. 3.
    It tries to authenticate the user.
  4. 4.
    With a while loop, it has a menù that gives the user to choose between three options:
    1. 1.
      Option 1: the user can visualize the price of one crypto in a currency of their choice. Also, the user can choose to store the value of the crypto in a CVS file with the current date.
    2. 2.
      Option 2: the user can visualize the difference between today's and yesterday's price of a crypto.
    3. 3.
      Option 0: it closes the program by breaking the loop.
Here we document all the functions used:

The authentication function

The authentication function authenticates the user by verifying their email che API token.
This is a use case of the GET/ping method shown in the documentation.
This method has no parameters and returns 200 if the authentication is successful.
In Python, we can test it as follows:
# Try access by pinging the dedicated URL
try:
ping_url = "https://api.coingecko.com/api/v3/ping"
response = requests.get(url=ping_url, auth=auth)
if response.status_code == 200:
print(f"\nAccess succesfully granted to the API!")
else:
print(f"\nAn error occurred while autenticating. Please: try again!")
except Exception as e:
print(f"\nAn exception occurred:", e)
Were the authentication is performed from the email and the API token imported from the settings.py file like so (complete code reference here):
# Import settings from the settings file
email = settings.EMAIL
token = settings.API_TOKEN
auth = (email + "/token", token) # Create authenticator

The price module

This module has two functions that retrieve the price of a currency using the API and make some calculations.
The function visualize_price() calls the API using the GET/simple/price method (for more details on this method, refer to the API documentation).
Here's how this method can be used to show the current price of one crypto with respect to a currency:
def visualize_price(auth:str)->None:
"""Shows the current price of a crypto with respect to a currency.
The auth variable is created in the main.py file.
"""
# User inserts crypto and currency
crypto = input(f"\nChoose your crypto (for example, write 'bitcoin'):\n")
currency = input(f"Choose the currency (for example, write 'usd'):\n")
# API call
url_price = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies={currency}"
response = requests.get(url=url_price, auth=auth)
# Print current price of a crypto in the selected currency
try:
if response.status_code == 200:
data = response.json()
print(f"\nThe current price for {crypto} is: {data[crypto][currency]: .1f} {currency}")
else:
print(f"An error occurred while getting the price: please, try again!")
except Exception as e:
print(f"An exception occurred while trying to get the currency value", e)
For example, suppose we want to know the current price of bitcoin in USD. Here's what you'll see:
The current price of bitcoin in USD.
The function price_change() calls the API using the GET/coins/{id}/market_chart method (for more details on this method, refer to the API documentation).
Here's how this method can be used to calculate the current price of a crypt with respect to a currency and its yesterday's price. We can also calculate the change in price during the day and print it:
def price_change(auth:str)->None:
'''Shows the difference of the price of a crypto in a currency with respect to the value it had yesterday.
The auth variable is created in the main.py file.
'''
# User inserts crypto and currency
crypto = input(f"\nChoose your crypto (for example, write 'bitcoin'):\n")
currency = input(f"Choose the currency (for example, write 'usd'):\n")
# API call
url_increment = f"https://api.coingecko.com/api/v3/coins/{crypto}/market_chart?vs_currency={currency}&days=1&interval=daily"
response = requests.get(url=url_increment, auth=auth)
try:
if response.status_code == 200:
data = response.json()
current_value = data["prices"][1][1]
yesterday_value = data["prices"][0][1]
change_price = current_value - yesterday_value
print(f"\nThe current value of {crypto} is {current_value: .1f} {currency} while yesterday's value was {yesterday_value: .1f} {currency}.\nSo, the price has changed by {change_price: .1f} {currency} from yesterday")
else:
print(f"An error occurred while getting the price: please, try again!")
except Exception as e:
print(f"An exception occurred while trying to get the currency value", e)
For example, suppose we want to know the price of Ethereum in EUR. We'd get the following:
The price of Ethereum in EUR:
Note that the response to the GET call is the following:
The GET response.
This is why the slicing used is:
  • current_value = data["prices"][1][1]
  • yesterday_value = data["prices"][0][1]

The cvs_creation module

This module has two functions:
  • The function new_csv() creates a CSV writing the header, if it doesn't exist.
  • The function write_data() writes the current value of a crypto in a currency on the current date.

Using the main file

The main file is built as a menu with two options:
  • Option 1 writes the current value of a crypto and stores its value in the CVS, if the user wants-
  • Option 2 prints the difference in the value of a crypto between today and yesterday.
Let's show how the software is expected to work:
Expected result.