> For the complete documentation index, see [llms.txt](https://federico-trotta.gitbook.io/federico-trottas-portfolio/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://federico-trotta.gitbook.io/federico-trottas-portfolio/my-portfolio/api-documentation/coingecko-api-getting-crypto-values.md).

# CoinGecko API: Getting Crypto Values

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](https://github.com/federico-trotta/crypto_prices_API).

***

## Prerequisites

To use the CoinGecko API you first need to create an account on [their website](https://www.coingecko.com/).

Then, you need to create an [API token](https://apiguide.coingecko.com/getting-started/getting-started). The [free plan](https://www.coingecko.com/en/api/pricing) 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](https://github.com/federico-trotta/crypto_prices_API/blob/main/initial.py)):

* 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
  * &#x20;If exists, it warns the user that the file already exists.&#x20;
  * 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](#getting-started), always invoke the main file via `$ python3 main.py`.

Here's what it does:

1. It imports the email and the API token from the `settings.py` file.
2. It prints a welcome message reporting the version of the software.
3. It tries to authenticate the user.
4. With a `while` loop, it has a menù that gives the user to choose between three options:
   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. Option 2: the user can visualize the difference between today's and yesterday's price of a crypto.
   3. Option 0: it closes the program by breaking the loop.

Here we document all the functions used:

* [The authentication function](#the-authentication-function)
* [The `price` module](#the-price-module)
* [The `csv_creation` module](#the-cvs_creation-module)

### 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](https://www.coingecko.com/api/documentation).

This method has no parameters and returns 200 if the authentication is successful.

In Python, we can test it as follows:

```python
# 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](https://github.com/federico-trotta/crypto_prices_API/blob/main/main.py)):

```python
# Import settings from the settings file
email = settings.EMAIL
token = settings.API_TOKEN
auth = (email + "/token", token) # Create authenticator
```

### The `price` module

[This module](https://github.com/federico-trotta/crypto_prices_API/blob/main/functions/price.py) 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](https://www.coingecko.com/api/documentation)).&#x20;

Here's how this method can be used to show the current price of one crypto with respect to a currency:

<pre class="language-python"><code class="lang-python">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}&#x26;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}")
<strong>        else:
</strong><strong>            print(f"An error occurred while getting the price: please, try again!")
</strong>     except Exception as e:
        print(f"An exception occurred while trying to get the currency value", e)
</code></pre>

For example, suppose we want to know the current price of bitcoin in USD. Here's what you'll see:

<figure><img src="/files/MxzUoa9eCCMZu4Q07P9A" alt=""><figcaption><p>The current price of bitcoin in USD.</p></figcaption></figure>

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](https://www.coingecko.com/api/documentation)).&#x20;

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:

```python
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:

<figure><img src="/files/D4VycUhbJ51a1YYWMuyW" alt=""><figcaption><p>The price of Ethereum in EUR:</p></figcaption></figure>

Note that the response to the `GET` call is the following:

<figure><img src="/files/rqETkTUcjhkq5dI2VsuH" alt=""><figcaption><p>The GET response.</p></figcaption></figure>

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](https://github.com/federico-trotta/crypto_prices_API/blob/main/functions/csv_creation.py) 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:

<figure><img src="/files/sHu8SOi9Qx1CStlBS7Aj" alt=""><figcaption><p>Expected result.</p></figcaption></figure>
