Profit & Loss Calculator for Bitcoin

Profit & Loss Calculator for Bitcoin

Cryptocurrencies are all the people talk about these days and fascinate about what if they had bought when they first came to know about the term "Bitcoin". If someone was not under the rock in the last 5 years then should have heard about this magic internet money that keeps going up. Bitcoin Fomo

Well, I'm not here to tell you to buy the magic internet money. I'm here to show you how much would have been your profit or loss today if you had bought bitcoin in the past.

While I was doing a practice project for an assignment I had to make a Profit or Loss calculator where the user will enter a stock price, how many stocks he bought and what's the current price for that stock. with that given data I had to calculate his profit or loss. There were some bonus points for fetching the price from some API on some given date instead of taking manual input from the user. So I decided why not make the same app for our beloved Magic Internet Money.

I needed an API that can give us the current price of the bitcoin and the historical price on some date. I found CoinGecko, which gives the simple API for fetching the price of any cryptocurrency on their site.

Let's start code: Typing

Basic HTML structure for taking users input:

 <main class="container">

        <h1>Bitcoin Profit & Loss Calculator</h1>

        <label for="date-of-purchase">Date of Purchase: </label>
        <input class="date-of-purchase" type="date"></input>
        <div class="price-on-date price">Buy Price: $$$</div>

        <label for="quantity">Quantity: </label>
        <input class="quantity" type="number"></input>

        <div class="current-price price">Current Price: $$$</div>

        <button class="check">Check</button>

        <div class="timeout">
            <p>processing...</p>
            <img src="./assets/processing.gif" height="50px">
        </div>

        <div class="result"></div>
    </main>

We got two API Urls from CoinGecko for our little app:

var currentPriceURL = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd";
var historicalPriceURL = "https://api.coingecko.com/api/v3/coins/bitcoin/history?date={dd-mm-yyyy}";

Now let's fetch the prices from API:

// async fucntion for fetching the prices from API 
    var boughtAt = 0;
    var currentPrice = 0;

    await fetch(currentPriceURL)
    .then(response => response.json())
    .then(data => currentPrice = data["bitcoin"]["usd"]);

    await fetch(historicalPriceURL + purchaseDate.value.split("-").reverse().join("-"))
    .then(response => response.json())
    .then(data => boughtAt = Math.round(data["market_data"]["current_price"]["usd"]));

    buyPriceLabel.innerText = `Bought At: $${boughtAt}`;
    currentPriceLabel.innerText = `Current Price: $${currentPrice}`;

    calculateReturns(boughtAt, currentPrice, quantity.value);

We got two prices from the API i.e. price on the date chosen by the user and current price, Now we need to do our Calculation depending upon the Quantity user bought...

function calculateReturns(buy, current, quantity) {
    if (buy > current) {
        var loss = (buy - current) * quantity;
        var lossPercentage = Math.round((loss / buy) * 100);

        updateResult(`Oops! You're down by ${lossPercentage}% with total loss of $${loss}`,"red");
    } else{
        var profit = (current - buy) * quantity;
        var profitPercentage = Math.round((profit / buy) * 100);

        updateResult(`Kudos! You're in profit by ${profitPercentage}% with total profit of $${profit}`, "green");     
    }
}

There were many use cases that came to my mind while making this and I'll keep updating the code as I learn more and make this app more useful.

Some Todos:

  • Date Range (user should be able to choose only past dates for which API has data).
  • A Drop Down to select any cryptocurrency available on CoinGecko.
  • Support for decimal prices.

The above app is hosted at: bitcoin-returns-calculator.netlify.app The complete code for the above app can be found on Github

This was my first blog ever and I plan to publish more as I learn new things.