Stocks: Profit or loss indicator
Tags: javascript, webdev
Published: 2021-08-13 23:00:08

[Cover photo](https://unsplash.com/photos/DfjJMVhwH_8
) by @austindistel show some :heart: to [creator](https://unsplash.com/@austindistel)



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.

{% youtube tPAA7rJI5PI %}


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 SuryanshChopra/Profit-or-loss-Indicator no-readme %}

##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``

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

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

```javascript
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));
    }
}

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

<img width="100%" style="width:100%" src="https://media.giphy.com/media/9QpWnH4AWv6xKvSX7T/giphy.gif">

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](https://api.tiingo.com/). It's like 5 minute job then navigate to [api.tiingo.com/account/api/token](https://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>
```

Click on send button. You'll get a nice JSON type file looking like this
```json
[
    {
        "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
    }
]
```

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 

```javascript
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));
```
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
```javascript
fetch("https://cors-anywhere.herokuapp.com/https://api.tiingo.com/tiingo/daily/AAPL/prices", requestOptions)
``` 


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
```javascript
  .then(json => {
        
        var translatedText = json[0].adjClose;
        SP = translatedText;
        
        output0.innerHTML="Current price for this stock is: ${SP}"
```
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` 

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

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

var SP = 0;
```
and instead of using `fetch("https://cors-anywhere.herokuapp.com/https://api.tiingo.com/tiingo/daily/AAPL/prices", requestOptions)`
 
do this
```javascript
fetch(getTranslationURL(inputText), requestOptions)
```


Congratulations!! you are done with the application

<img width="100%" style="width:100%" src="https://media.giphy.com/media/g9582DNuQppxC/giphy.gif">

## 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 
>  <center>- Suryansh Chopra (2021)</center>


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

Back to the problem, create a `config.js` file,
```javascript
var config = {
    TOKEN: 'your token' //your token must be inside ''.
  }
```
and add these lines inside `app.js` file
```javascript
var token = config.TOKEN;

//rest code

myHeaders.append("Authorization", "Token " + token);
```

Now create a `.gitignore` file and add
```
config.js
```
inside it.

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

<img width="100%" style="width:100%" src="https://media.giphy.com/media/zDpYQooxkwXkAWMxRK/giphy.gif">