Stocks: Profit or loss indicator (2024)

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.

Stocks: Profit or loss indicator (1) 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>

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

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

Stocks: Profit or loss indicator (2)

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/jsonAuthorization: Token <your token>

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 }]

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 youmyHeaders.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

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

 .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

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

fetch(getTranslationURL(inputText), requestOptions)

Congratulations!! you are done with the application

Stocks: Profit or loss indicator (3)

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 ''. }

and add these lines inside app.js file

var token = config.TOKEN;//rest codemyHeaders.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.

Stocks: Profit or loss indicator (4)

Stocks: Profit or loss indicator (2024)

FAQs

Which is the most successful stock indicator? ›

The best technical indicators for day trading are the RSI, Williams Percent Range, and MACD. These measurements show overbought and oversold levels on a chart and can help predict where a price is likely to go next, based on past performance.

What is the most accurate indicator of what a stock is actually worth? ›

The price to earnings (P/E) ratio is possibly the most scrutinized of all the ratios. If sudden increases in a stock's price are the sizzle, then the P/E ratio is the steak. A stock can go up in value without significant earnings increases, but the P/E ratio is what decides if it can stay up.

How do you know if a stock has earned profit or loss? ›

To calculate your gain or loss, subtract the original purchase price from the sale price and divide the difference by the purchase price of the stock. Multiply that figure by 100 to get the percentage change.

Is it better to sell stocks in loss or profit? ›

An investor may also continue to hold if the stock pays a healthy dividend. Generally, though, if the stock breaks a technical marker or the company is not performing well, it is better to sell at a small loss than to let the position tie up your money and potentially fall even further.

What is the single best trading indicator? ›

1. Moving Average. Also known as the simple moving average (SMA), moving averages are a popular indicator that calculates the average price over a specific time period. It helps traders identify trends and potential support and resistance levels.

What are the best stock indicators for beginners? ›

Popular technical indicators include simple moving averages (SMAs), exponential moving averages (EMAs), bollinger bands, stochastics, and on-balance volume (OBV). Technical indicators provide insight into support and resistance levels which may be key in devising a low risk-reward ratio strategy.

What indicators does Warren Buffett use? ›

What's happening: Widely known as the “Buffett Indicator,” it measures the size of the US stock market against the size of the economy by taking the total value of all publicly traded companies (measured using the Wilshire 5000 index) and dividing that by the last quarterly estimate for gross domestic product.

What is the Buffett Indicator of the stock market? ›

The so-called Buffett indicator compares the total market capitalization (share prices times outstanding shares) of all U.S. stocks with the quarterly output of the U.S. economy.

Is the Buffett Indicator accurate? ›

The Buffett Indicator forecasted an average of 83% of returns across all nations and periods, though the predictive value ranged from a low of 42% to as high as 93% depending on the specific nation.

How much money do I need to invest to make $1000 a month? ›

A stock portfolio focused on dividends can generate $1,000 per month or more in perpetual passive income, Mircea Iosif wrote on Medium. “For example, at a 4% dividend yield, you would need a portfolio worth $300,000.

How much money do I need to invest to make $3,000 a month? ›

Imagine you wish to amass $3000 monthly from your investments, amounting to $36,000 annually. If you park your funds in a savings account offering a 2% annual interest rate, you'd need to inject roughly $1.8 million into the account.

What is a fair percentage for an investor? ›

Searching for the magic number

A lot of advisors would argue that for those starting out, the general guiding principle is that you should think about giving away somewhere between 10-20% of equity.

What is the 3-5-7 rule in trading? ›

A risk management principle known as the “3-5-7” rule in trading advises diversifying one's financial holdings to reduce risk. The 3% rule states that you should never risk more than 3% of your whole trading capital on a single deal.

What is the 3 day rule in stocks? ›

The 3-Day Rule in stock trading refers to the settlement rule that requires the finalization of a transaction within three business days after the trade date. This rule impacts how payments and orders are processed, requiring traders to have funds or credit in their accounts to cover purchases by the settlement date.

What is the 10 am rule in stock trading? ›

Some traders follow something called the "10 a.m. rule." The stock market opens for trading at 9:30 a.m., and the time between 9:30 a.m. and 10 a.m. often has significant trading volume. Traders that follow the 10 a.m. rule think a stock's price trajectory is relatively set for the day by the end of that half-hour.

What is the most used indicator? ›

A guide to the 10 most popular trading indicators
  • Moving Average Convergence Divergence (MACD) ...
  • Fibonacci retracements. ...
  • Stochastic oscillator. ...
  • Bollinger bands. ...
  • Relative Strength Index (RSI) Indicator. ...
  • Average Directional Index (ADX) Indicator. ...
  • Standard deviation indicator. ...
  • Ichimoku cloud indicator.

Which indicator is best for take profit? ›

The take-profit level can be calculated by measuring the height of the consolidation pattern and projecting it from the breakout point. Alternatively, traders can use Fibonacci extensions, which are indicators that show possible price levels based on the Fibonacci sequence, to set take-profit levels.

Which indicator gives a buy-sell signal? ›

Stochastics are a favored technical indicator because they are easy to understand and have a relatively high degree of accuracy. It falls into the class of technical indicators known as oscillators. The indicator provides buy and sell signals for traders to enter or exit positions based on momentum.

Which trading strategy has the highest success rate? ›

Indicator-Based Directional Trading

This strategy uses an indicator to determine the direction of the trade. The indicator provides a clear signal when it's time to enter or exit a trade, making it easy to work with. Traders who use this strategy can expect to see consistent results and high success rates.

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6256

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.