Build a Cryptocurrency Profit Calculator App

Web Development

In this JavaScript Project we will create Cryptocurrency Web Application that can calculator the PROFIT / LOSS using HTML CSS and JavaScript. By using your declared sell price or market price the application will also calculate the : – PROFIT / LOSS – Initial investment – Buy Fee – Investment after fees – Cryptocurrency units – Sell Fee – Total Fees – Total Exit Amount The Cryptocurrency application lets you choose between 5 Cryptocurrency (BTC, ETH, LTC, XRP, UNI).

Introduction

In this JavaScript project you will create a web application that will calculate the profit or loss from selling and buying a cryptocurrency using HTML CSS and JavaScript.

The profit or loss of de sell will depending on the specified price or the market price and the buying and selling fees that are applied.

Table of content

  • Get all HTML input tag element from the DOM / page
  • Change background color of the form depending on the cryptocurrency type
    • Get CSS Variables from css and use them in javascript
    • Get the current market price depending on the selected cryptocurrency using async await API
  • Add event listener of click to the calculate button
    • Prevent the default behavior of the form
    • Create a function to get the values from the inputs using JavaScript
    • Toggle the cryptocurrency market price or sell price value
    • Check which price is selected and calculate the profit (Actual sell price or Marketprice).
    • Calculate the profit of a cryptocurrency
      • investment with entry fee
      • units of currency
      • the amount of sold currency
      • exit value with exit fee
      • exit value with all fees
      • the profit
        • Profit in fiat currency
        • Profit in percentage
    • Display the profit
      • Check if all field are filled
      • Check if the profit is positive or negative
      • make first letter of a string uppercase
      • Create function to clear the inputs fields of the form after the calculation
      • Create a transition effect and remove it after delay using JavaScript

Starter code

Below you can find the code for the index.html file and the style.css file. Create a project folder and in the folder create the index.htmlfile and the style.css file. Then copy the code in each file accordingly.

Bought the html and the css are from the new Course Advanced HTML CSS & SASS – Build and Deploy Modern Websites, where we ware soli focusing on the design but not the functionality of the project.

HTML code

The html code consist mainly of a container witch contains a form that will fold all of the inputs for the cryptocurrency type, transaction, and submit request via a button.
It als contain a .result class where the final results will be displayed.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Crypto Profit Calculator</title>
  </head>
  <body>
    <h1>Crypto Profit Calculator</h1>
    <div class="container">
      <form id="from-currency">
        <div class="form-group">
          <label for="crypto-select">Select a crypto currency</label>
          <select name="crypto-select" id="crypto-select">
            <option value="">--Select a crypto currency--</option>
            <option value="BTC">BTC</option>
            <option value="ETH">ETH</option>
            <option value="LTC">LTC</option>
            <option value="XRP">XRP</option>
            <option value="UNI">UNI</option>
          </select>
        </div>

        <div class="form-group">
          <label for="amount">Invested Amount $</label>
          <input
            type="number"
            name="amount"
            id="amount"
            placeholder="Enter amount"
          />
        </div>
        <div class="form-group">
          <label for="price">Buy price $</label>
          <input
            type="number"
            name="price"
            id="price"
            placeholder="Enter price"
          />
        </div>
        <div class="form-group">
          <label for="fee">Investment Fee %</label>
          <input
            type="number"
            name="fee"
            id="entry-fee"
            placeholder="Enter fee"
          />
        </div>
        <div class="exit-price">
          <div class="form-group">
            <label for="sell-price">Sell price $</label>
            <input
              type="number"
              name="sell-price"
              id="sell-price"
              placeholder="Enter sell price"
            />
          </div>
          <div class="form-group">
            <span class="SelectMarket-price">
              <input type="checkbox" id="SelectMarket-price" />
              <label for="SelectMarket-price">Market price $</label>
            </span>

            <input
              type="number"
              name="Market-price"
              id="Market-price"
              placeholder="Enter Market price"
              value="000000"
              disabled
            />
          </div>
        </div>

        <div class="form-group">
          <label for="fee">Exit Fee %</label>
          <input
            type="number"
            name="fee"
            id="exit-fee"
            placeholder="Enter fee"
          />
        </div>

        <button class="btn btn-primary" type="submit" id="calculate">
          Calculate
        </button>
      </form>

      <div class="result">
        <span id="profit"></span>
      </div>
    </div>

    <script src="index.js"></script>
  </body>
</html>

CSS code

The style.css file contains a general reset using the * selector, some project specific css variables applied globally to the style sheet using the :root selector.

The most important part that you need to pay attention to are the utility classes at the and of the code. This are used to interchange states in the project.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
  list-style-type: none;
  font-family: "Roboto", sans-serif;
}

:root {
  --primary-color: #7633f9;
  --secondary-color: #ffc107;
  --light-color: #f5f5f5;
  --dark-color: #08023a;
  --success-color: #28a745;
  --danger-color: #dc3545;
  --btc-color: #f2a400;
  --eth-color: #626bd9;
  --ltc-color: #7d8fb3;
  --xrp-color: #0c1818;
  --uni-color: #ff007a;
}

body {
  background-color: var(--dark-color);
}
/*  Utility classes*/
.container {
  width: 600px;
  margin: auto;
  margin-top: 5vh;
  background: var(--secondary-color);
  padding: 20px;
  border-radius: 20px;
  display: flex;
  gap: 20px;
}
h1 {
  margin: 2rem;
  text-align: center;
  font-size: 5rem;
  color: var(--light-color);
}
/*Buttons*/
.btn {
  margin: 0.25rem 0.125rem;
  padding: 0.35rem 1.25rem;
  font-family: inherit;
  font-weight: 400;
  font-size: 1rem;
  line-height: 1.5;
  letter-spacing: 0.7px;
  border-radius: 0.3rem;
  color: #fff;
  background-color: black;
  border: none;
  box-shadow: 0 2px 5px rgba(51, 51, 51, 0.3);
  transition: 0.3s ease;
}
.btn:hover {
  cursor: pointer;
  box-shadow: none;
  transition: 0.3s ease;
  background: rgba(0, 0, 0, 0.75);
}

.btn-primary {
  background-color: #7633f9;
  color: black;
  width: 100%;
  margin-top: 2rem;
}

.btn-primary:hover {
  background: rgba(118, 51, 249, 0.75);
}
#crypto-select {
  width: 100%;
}
form {
  width: 50%;
}
form .btn {
  color: #eee;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.form-group input,
.form-group select {
  border: 1px solid #eeee;
  border-radius: 5px;
  padding: 0.5rem;
  width: 100%;
}

.form-group input:focus {
  outline: 1px solid #5308b6;
}
.SelectMarket-price {
  display: grid;
  grid-template-columns: 1fr 11fr;
  gap: 10px;
  margin-bottom: 0.7rem;
}
label[for="SelectMarket-price"] {
  font-size: 0.8rem;
  margin-bottom: 0;
  cursor: pointer;
}
label[for="SelectMarket-price"]:hover {
  color: #5308b6;
  text-decoration: underline;
}
#SelectMarket-price {
  outline: none;
}
.exit-price {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}
.result {
  width: 50%;
  padding: 20px;
  background-color: var(--light-color);
  color: var(--dark-color);
  border-radius: 25px;
  font-weight: 500;
}
.result div {
  margin-bottom: 1rem;
}
.profit {
  color: var(--success-color);
}
.loss {
  color: var(--danger-color);
}
.primary {
  color: var(--primary-color);
}
.fadeIn {
  animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

/* responsive  */

@media (max-width: 768px) {
  h1 {
    font-size: 3.5rem;
  }
  .container {
    width: 95%;
    margin: 2 0.5rem;
  }
  form {
    width: 40%;
  }
  .result {
    width: 60%;
  }

  .exit-price {
    grid-template-columns: 1fr;
  }
}


I also added just a little bit of responsive design at the and of the code and slit animation to the final design.

Get all HTML input tag element from the DOM / page

First create your javascript file and name it accordingly. Now you need to get all of the necessary elements from the DOM as reusable variables.

const container = document.querySelector(".container"),
  fromCurrency = document.getElementById("from-currency"),
  amount = document.getElementById("amount"),
  price = document.getElementById("price"),
  entryFee = document.getElementById("entry-fee"),
  sellPrice = document.getElementById("sell-price"),
  marketPrice = document.getElementById("Market-price"),
  selectMarketPrice = document.getElementById("SelectMarket-price"),
  exitFee = document.getElementById("exit-fee"),
  calculate = document.getElementById("calculate"),
  cryptoCurrency = document.getElementById("crypto-select"),
  profit = document.getElementById("profit");

Change background color of the form depending on the cryptocurrency type

The first interactive action the you can code is to make the background color of the app container to change color depending on the selected cryptocurrency.
For this you need to add a event listener of “change” to the cryptoCurrency selection and use a switch statement with multiple cases.

cryptoCurrency.addEventListener("change", function () {
  switch (cryptoCurrency.value) {
    case "BTC":

      break;
    case "ETH":

      break;
    case "LTC":

      break;
    case "XRP":

      break;
    case "UNI":

      break;

    default:

  }
});

Get CSS Variables from css and use them in javascript

For each case of cryptocurrency selected you will assign a according background and text color using you css variables witch you can access using the var(--var-name) selector.

cryptoCurrency.addEventListener("change", function () {
  switch (cryptoCurrency.value) {
    case "BTC":
      container.style.background = "var(--btc-color)";
      container.style.color = "var(--dark-color)";
      break;
    case "ETH":
      container.style.background = "var(--eth-color)";
      container.style.color = "var(--light-color)";
      break;
    case "LTC":
      container.style.background = "var(--ltc-color)";
      container.style.color = "var(--dark-color)";
      break;
    case "XRP":
      container.style.background = "var(--xrp-color)";
      container.style.color = "var(--light-color)";
      break;
    case "UNI":
      container.style.background = "var(--uni-color)";
      container.style.color = "var(--light-color)";
      break;

    default:
      container.style.background = "var(--secondary-color)";
      container.style.color = "var(--dark-color)";
  }
});

Get the current market price depending on the selected cryptocurrency using async await API

Use the coingecko API to get cryptocurrency market prices (not the most currant prices).

The async await function will help you call the API asyncronasly and the the current price.

async function getPrice(cryptoCurrency) {
  try {
    const res = await fetch(
      `https://api.coingecko.com/api/v3/coins/markets?vs_currency=gbp&order=market_cap_desc&per_page=250&page=1&sparkline=false`
    );
    const data = await res.json();
    const cryptoElement = data.find((ele) => ele.symbol === cryptoCurrency);
    document.querySelector("#Market-price").value = cryptoElement.current_price;
    return cryptoElement.current_price;
    // console.log(cryptoElement);
  } catch (error) {
    console.log(error);
  }
}

Add the function to the different cases in thw switch and use each currency symbol as a argument that you pass in to the getPrice() function.

...
  case "BTC":
      container.style.background = "var(--btc-color)";
      container.style.color = "var(--dark-color)";
      getPrice("btc");
      break;
    case "ETH":
      container.style.background = "var(--eth-color)";
      container.style.color = "var(--light-color)";
      getPrice("eth");
      break;
    case "LTC":
      container.style.background = "var(--ltc-color)";
      container.style.color = "var(--dark-color)";
      getPrice("ltc");

      break;
    case "XRP":
      container.style.background = "var(--xrp-color)";
      container.style.color = "var(--light-color)";
      getPrice("xrp");

      break;
    case "UNI":
      container.style.background = "var(--uni-color)";
      container.style.color = "var(--light-color)";
      getPrice("uni");

      break;

...


Add event listener of click to the calculate button

calculate.addEventListener("click", function (e) {...}

Prevent de default behavior iof the form

calculate.addEventListener("click", function (e) {
   e.preventDefault();
  ...}

Create a function to get the values from the inputs using JavaScript

You have selected all the input elements from the DOM but that is not enough, you now need there actual values.
This is easily don using a function that will return new variables that contain the values of the inputs.

function getValues() {
  return (
    (amountValue = parseFloat(amount.value)),
    (priceValue = parseFloat(price.value)),
    (entryFeeValue = parseFloat(entryFee.value)),
    (sellPriceValue = selectMarketPrice.checked
      ? marketPrice.value
      : parseFloat(sellPrice.value)),
    (exitFeeValue = parseFloat(exitFee.value)),
    (cryptoCurrencyValue = cryptoCurrency.value)
  );
}

Initiate the function in the click event.

calculate.addEventListener("click", function (e) {
   e.preventDefault();
   getValues();
  ...}

Toggle the cryptocurrency market price or sell price value

(sellPriceValue = selectMarketPrice.checked ? marketPrice.value : parseFloat(sellPrice.value)),

Check witch price is selected and calculate the profit (Actual sell price or Market price)

selectMarketPrice.addEventListener("change", function () {
  if (selectMarketPrice.checked === true) {
    sellPrice.disabled = true;
  } else {
    sellPrice.disabled = false;
  }
});

Calculate the profit of a cryptocurrency

Investment with entry fee

const investmentWithFee = (amountValue * entryFeeValue) / 100;

Units of currency

const units = (amountValue - investmentWithFee) / priceValue;

The amount of sold currency

const soldCurrency = units * sellPriceValue;

Exit value with exit fee

const feeOfTheExitValue = (soldCurrency * exitFeeValue) / 100;

Exit value with all fees

const exitValue = soldCurrency - feeOfTheExitValue - investmentWithFee;

The profit

Profit in fiat currency

const profitValue = exitValue - amountValue;

Profit in percentage

const profitPercentage = (profitValue / amountValue) * 100;

Display the profit

Check if all filed are filled

if (isNaN(profitValue, profitPercentage)) {
    profit.innerHTML = `<h2 class= "loss" > Complete all fields !</h2>`;
  } else {
    profit.innerHTML = `<h2 class=${profitLoss}> ${
      profitLoss.charAt(0).toUpperCase() + profitLoss.slice(1)
    }</h2>

    <div class=${profitLoss}>${profitValue.toFixed(
      2
    )} $ (${profitPercentage.toFixed(2)}%)</div>

    <h4>Initial investment</h4>
  <div class="primary">${amountValue.toFixed(2)} $</div>

    <h4>Buy fee</h4>
  <div class="primary">${investmentWithFee.toFixed(2)} $</div>

        <h4>Investment after fee</h4>
  <div class="primary">${amountValue - investmentWithFee.toFixed(2)} $</div>


  <h4>Crypto currency units</h4>
  <div class="primary">${units} ${cryptoCurrencyValue}</div>


  <h4>Sell Fee</h4>
  <div class="primary">${feeOfTheExitValue.toFixed(2)}</div>


 <h4>Total Fees</h4>
  <div class="primary">${(feeOfTheExitValue + investmentWithFee).toFixed(
    2
  )}</div>


  <h4>Total Exit Amount</h4>
  <div class="${profitLoss}">${exitValue.toFixed(2)}</div>


    `;
  }

Check if the profit is positive or negative

  let profitLoss;
  if (profitValue > 0) {
    profitLoss = "profit";
  } else {
    profitLoss = "loss";
  }

Make first latter of a string uppercase

Create a transition effect and remove it after delay using JavaScript

  profit.classList.add("fadeIn");

  setTimeout(function () {
    profit.classList.remove("fadeIn");
  }, 500);

Clear all input fields

function clearInputs() {
  amount.value = "";
  price.value = "";
  entryFee.value = "";
  sellPrice.value = "";
  exitFee.value = "";
}

Watch the video tutorial

Leave a Reply

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