DEV Community

Cover image for Stocks: Profit or loss indicator
Suryansh Chopra
Suryansh Chopra

Posted on

Stocks: Profit or loss indicator

Cover photo by @austindistel show some ❤️ to creator

It's been a while since I uploaded a blog. The project I did recently was to make a Profit or loss indicator for Stocks.

This is a project I created by using Vanilla JS, It inputs 3 parameters

  1. Stock symbol
  2. Initial investing amount
  3. Stock quantity

Based on these 3 parameters, it will give output of the current price and and shows profit and loss according to it.

GitHub logo SuryanshChopra / Profit-or-loss-Indicator

Stocks: profit or loss indicator

Now I wanna show you how you can build this awesome website.

Nothing to be feared, I got you

Remember what you need in the project, 3 input parameters

  1. A stock symbol
  2. A initial investing amount
  3. A stock quantity

Start by including these 3 things in your index.html

<form>
<label><input id="input1" placeholder="Enter the stock symbol" type="text" required> Enter the stock symbol</label>                       
<label><input id="input2" placeholder="Enter Cost price of Stock" type="text" required> Purchase Price</label>       
<label><input id="input3" placeholder="Enter stock Quantity" type="text" required> Stock Quantity </label>                       
<button type="submit">Check</button>
</form>
<div class="output0"></div>
<div class="output"></div>
Enter fullscreen mode Exit fullscreen mode

Done with these, now move to JavaScript section, In app.js return the form elements and add a event listener on "submit" button

form = document.forms[0];
input1 = document.querySelector("#input1");
input2 = document.querySelector("#input2");
input3 = document.querySelector("#input3");

output = document.querySelector(".output");
output0 = document.querySelector(".output0");

form.addEventListener("submit", checkHandler);

function checkHandler(e){
    e.preventDefault();

    let CP = input2.value;
    let Qty = input3.value;

    if( !isNaN(CP) && !isNaN(Qty) && !isNaN(SP)) {
        CP = Number(CP);
        Qty = Number(Qty);
        SP = Number(SP);

        if(CP>0 && Qty>0 && SP>0){

            if (CP>SP){
                const loss = ((CP-SP)*Qty).toFixed(2);
                const lossPer = (((CP-SP)*100)/CP).toFixed(2);
                output.innerHTML=  "You lost ${lossPer}%. Your total loss is $${loss}";

            }

            else{
                const profit = ((SP-CP)*Qty).toFixed(2)
                const profitPer=(((SP-CP)*100)/CP).toFixed(2) ;
                output.innerHTML=  "You gained ${profitPer}%. Your total profit is $${profit}";
            }
        }
        else {
            output.innerHTML="Please enter values greater than 0 (only numbers are allowed in above fields"
        }
    }
    else{
        output.innerHTML="Please enter values greater than 0 (only numbers are allowed in above fields"
    }

        })


    .catch(error => console.log('error', error));
    }
}

Enter fullscreen mode Exit fullscreen mode

You must be like "WOAH dude where the hell is this SP coming from"

Relax man we gonna get this value from the API, That's right the Stock symbol user has entered, its closing price will become our SP. It is included here just to let you know our logic is correct.

So Now the problem arises where do I get this API that's gonna get my closing price. Chill man

So, we are gonna use Tiingo API, or use any of your favourite API, some use AlphaVantage, I never used it , so I cannot tell the difference.

Anyways, make a account on api.tiingo.com. It's like 5 minute job then navigate to api.tiingo.com/account/api/token. Here is your API key, Don't give it to anyone, keep it safe.

Now usually how Tiingo api works is by calling the stock symbol of a particular stock. For example:
https://api.tiingo.com/tiingo/daily/AAPL/prices - Here I have use Apple Stock symbol AAPL(this is gonna become our input1). It won't work right now because it is not associated with your token.

Input this link in on Postman app. if you don't have it, install it. Add 2 headers

Content-type: application/json
Authorization: Token <your token>
Enter fullscreen mode Exit fullscreen mode

Click on send button. You'll get a nice JSON type file looking like this

[
    {
        "adjClose": 148.89,
        "adjHigh": 149.05,
        "adjLow": 145.84,
        "adjOpen": 146.19,
        "adjVolume": 73779113,
        "close": 148.89,
        "date": "2021-08-12T00:00:00+00:00",
        "divCash": 0.0,
        "high": 149.05,
        "low": 145.84,
        "open": 146.19,
        "splitFactor": 1.0,
        "volume": 73779113
    }
]
Enter fullscreen mode Exit fullscreen mode

Click on the code snippet </> icon and get the link in JavaScript-Fetch. Copy the entire code and paste it in app.js inside the CheckHandler function

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Token <your token>"); // your token doesn't go in <>. It is a way to explain you
myHeaders.append("Cookie", "sessionid=<your session id>");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://api.tiingo.com/tiingo/daily/AAPL/prices", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
Enter fullscreen mode Exit fullscreen mode

On running you must be getting a CORS error, it is normal nothing to be panick about. It is use to restrict HTTP and HTTPS requests made from scripts to resources in a different origin for security reasons, mainly to protect the user's data and prevent attacks that would compromise the app.

There are many ways to resolve this error, we are gonna do this by using a simple way. You can use any method you want. just go to https://cors-anywhere.herokuapp.com/ and "request temporary access" Also add a single line https://cors-anywhere.herokuapp.com/ before your api link like this

fetch("https://cors-anywhere.herokuapp.com/https://api.tiingo.com/tiingo/daily/AAPL/prices", requestOptions)
Enter fullscreen mode Exit fullscreen mode

Now, let's fix this snippet first we don't need entire JSON file which is showing in our console right now. We are only interested in close price of the stock. Instead of .then(result => console.log(result)) do this

  .then(json => {

        var translatedText = json[0].adjClose;
        SP = translatedText;

        output0.innerHTML="Current price for this stock is: ${SP}"
Enter fullscreen mode Exit fullscreen mode

Onto our second problem, the current snippet will always give value for the AAPL prices. To change this add in the initial lines of app.js

var serverURL = "https://cors-anywhere.herokuapp.com/https://api.tiingo.com/tiingo/daily/"

function getTranslationURL(text){
    return serverURL + text +"/prices"

}

var SP = 0;
Enter fullscreen mode Exit fullscreen mode

and instead of using fetch("https://cors-anywhere.herokuapp.com/https://api.tiingo.com/tiingo/daily/AAPL/prices", requestOptions)

do this

fetch(getTranslationURL(inputText), requestOptions)
Enter fullscreen mode Exit fullscreen mode

Congratulations!! you are done with the application

Do this part only if you want to upload your project on to github

Now, that we've made our application there is one problem still remaining. Our code is sitting right there with our API key in it. We certainly can't push this onto github. so, we are gonna do what any man should do in this situation

We should not push our code onto github

- Suryansh Chopra (2021)

That's a joke That's a joke...

Back to the problem, create a config.js file,

var config = {
    TOKEN: 'your token' //your token must be inside ''.
  }
Enter fullscreen mode Exit fullscreen mode

and add these lines inside app.js file

var token = config.TOKEN;

//rest code

myHeaders.append("Authorization", "Token " + token);
Enter fullscreen mode Exit fullscreen mode

Now create a .gitignore file and add

config.js
Enter fullscreen mode Exit fullscreen mode

inside it.

Push the code and you have successfully uploaded the code and kept your API key safe.

Discussion (1)

Collapse
vikalp2502 profile image
Vikalp Kaushik

Amazing and nice explanation 👌