DEV Community

Cover image for Create A Simple Crypto Currency Tracker With NodeJS
Ethan
Ethan

Posted on • Originally published at ethan-dev.com

Create A Simple Crypto Currency Tracker With NodeJS

Introduction

Hello! ๐Ÿ˜Ž
In this tutorial I will show you how to create a simple crypto currency tracker using NodeJS.

In the dynamic world of cryptocurrency, keeping a close eye on fluctuating prices is crucial. For developers and crypto enthusiasts alike, building a real-time cryptocurrency tracker can be both a valuable tool and an excellent learning experience. ๐Ÿ˜Š


Requirements


Creating The Project

First we need to create a directory to house our project, this can be done via the following:

mkdir tracker && cd tracker
npm init -y
Enter fullscreen mode Exit fullscreen mode

In this tutorial we will be using two modules, one is dotenv to load the .env file and the other is axios to make the API requests. These can be installed via the following command:

npm i dotenv axios
Enter fullscreen mode Exit fullscreen mode

Next create an ".env" file with the following contents:

BTC_ALERT={number}
ETH_ALERT={number}
API_KEY={string}
Enter fullscreen mode Exit fullscreen mode

Note, you do not need "BTC_ALERT" and "ETH_ALERT" if you don't plan on using them. Replace the API_KEY with the key you created via CryptoCompare site.

Next create a file called "index.js", first we will include the required modules:

require('dotenv').config();
Enter fullscreen mode Exit fullscreen mode

The dotenv package loads environment variables from a .env file into process.env. This is where we will store sensitive information like our API key.

const axios = require('axios');
Enter fullscreen mode Exit fullscreen mode

We will be using axios, a promise-based HTTP client, to make requests to the CryptoCompare API.

Next we will set up a couple of constants for the API query:

const API_ENDPOINT = 'https://min-api.cryptocompare.com';
const API_PATH = '/data/pricemulti';

const COINS = 'BTC,ETH';
const CURRENCY = 'JPY,USD';

const API_URL = `${API_ENDPOINT}${API_PATH}?fsyms=${COINS}&tsyms=${CURRENCY}`;
Enter fullscreen mode Exit fullscreen mode

The above sets up the base url, along with the api path. We also set which crypto coins to include in the response as well as the USD and JPY value of the coins.

Next we will set the constants for the alert values:

const BTC_ALERT = process.env.BTC_ALERT ? Number(process.env.BTC_ALERT) : undefined;
const ETH_ALERT = process.env.ETH_ALERT ? Number(process.env.ETH_ALERT) : undefined;
Enter fullscreen mode Exit fullscreen mode

The above lines will fetch the alert thresholds from the .env file and convert them into numbers. If defined we will use there to trigger alerts when prices exceed these values.

Now that we have the constants defined we can now create the http client that will be used to make requests to the API.

const apiClient = axios.create({
    headers: {
        'Authorization': `Apikey ${process.env.API_KEY}`
    }
});
Enter fullscreen mode Exit fullscreen mode

We create an Axios instance with a custom header for API authentication.

After that we need to write the functions to handle both BTC and ETH comparison:

const compareBTC = (BTC) => {
    if (BTC_ALERT) {
        if (BTC.JPY >= BTC_ALERT) {
            console.log('[ALERT] BTC has exceeded BTC alert');
        }
    }

    console.log(`BTC is worth $${BTC.USD} and ${BTC.JPY} yen`);
};

const compareETH = (ETH) => {
    if (ETH_ALERT) {
        if (ETH.JPY >= ETH_ALERT) {
            console.log('[ALERT] ETH has exceeded ETH alert');
        }
    }

    console.log(`ETH is worth $${ETH.USD} and ${ETH.JPY} yen`);
};
Enter fullscreen mode Exit fullscreen mode

The above functions checks to see if the current price exceeds the alert price and if so prints out an alert to the console. (here I compare with JPY but feel free to replace it with USD).

They also print out the current price of each coin out to the console.

Next we will write the main function of this application which is called "sendRequest":

const sendRequest = async () => {
    try {
        const response = await apiClient.get(API_URL);

        compareBTC(response.data.BTC);
        compareETH(response.data.ETH);
    } catch (error) {
        console.error('error fetching data', error);
    } finally {
        setTimeout(sendRequest, 5000);
    }
};
Enter fullscreen mode Exit fullscreen mode

This is the main funtion of the application. sendRequest is an asynchronous function that makes a GET request to the API URL. If successful, it calls both of the previous defined compare functions with the fetched data.

The finally block ensures that the request is sent again after 5 seconds has passed.

Finally the last line of code initializes the sendRequest loop:

sendRequest();
Enter fullscreen mode Exit fullscreen mode

And thats it! ๐Ÿ˜€
A very simple application that tracks the prices of cryptocurrency.


Improvements

The app is very simple so of course it has room for improvements. I would personally like to add the following:

  • Support more cryptocurrencies
  • When the alert is triggered instead of printing to the console, I'd like to implement an email alert.
  • Implement a UI and use NodeJS for the backend
  • Take into consideration rate limits as I am using a free account.

If you have anymore improvements etc. Please let me know in the comments. ๐Ÿ‘€


Conclusion

In this post, we've walked through creating a simple yet effective real-time cryptocurrency tracker using NodeJS. This application gives a foundation to build upon, feel free to add any improvements to it.

As always you can find the sample code used for this tutorial on my Github:
https://github.com/ethand91/crypto-tracker

Happy Coding! ๐Ÿ˜Ž


Like my work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.

โ€œBuy Me A Coffeeโ€

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course

Top comments (0)