<- Blog Home

How to get email alerts when (Nasdaq, NSE, BSE) stock prices go down specified price

What We want to achieve

  • Specify the threshhold prices of stocks from NYSQ, NASDAQ, BSE, NSE
  • When the stock price dips below specified prices, we should get an email

Technical Aspect

We will need below things to achieve our objective.

  • Script that will fetch prices of desired stocks.
  • Script that will email the details of stocks that are trading below desired levels.
  • Scheduler that will run this job every day.

Implementation

This can be achieved in various tech stack but I will be using

  • Sending emails - https://app.sendgrid.com/guide/integrate
  • NodeJS (Scripting)
  • NextJS(Server) - If you do not have a server, you can use cloud functions like edge functions, lambda functions, azure functions etc.
  • Vercel platform
  • Scheduling job - https://console.upstash.com/qstash

Sending emails

For sending emails, we will be using market leader twilio's sendgrid service.

To use this service, just sign up and then get the API key for your project by going to https://app.sendgrid.com/guide/integrate. The wizard will create the sample code for selected tech stack like nodejs, python, Java etc.

Scheduling Job

You can use service like https://console.upstash.com/qstash to schedule tasks. Just signup and go to this url and create a new scheduled job to fetch the API endpoint that we will be creating in next section. I want to get alert at 3:30 PM Indian time +5:30UTC (10 AM UTC time) and second alert at 4pm NY time -5:00UTC (9:00 PM UTC time) so that I will get an email as soon as Indian and US market closes.

NextJS Server

I am assuming that you have already nextJS server up and running on platform like vercel. All you need to do is create an api endpoint that will fetch prices of stocks and then send email.

So just create an API endpoint (e.g. https://www.softpost.org/api/stocks) and add below code in it. Notice that we are using packages like @sendgrid/mail, axios, cheerio. Also note that we have specified 2 stocks Dixon.NS and AAPL and threshold prices.

import type { NextApiRequest, NextApiResponse } from "next";
const sgMail = require("@sendgrid/mail");
const axios = require("axios");
const cheerio = require("cheerio");

const symbols = ["DIXON.NS", "AAPL"];
const threshhold = [2700, 152];

let stockPrices = [];
let stockPrice: any = 0;

async function getPrices() {
  stockPrices = [];
  stockPrice = 0;

  let i = 0;
  for (const symbol of symbols) {
    let response = await axios.get(`https://finance.yahoo.com/quote/${symbol}`);

    const html = await response.data;
    const $ = await cheerio.load(html);
    stockPrice = $("#quote-header-info fin-streamer").attr("value");
    console.log("Stock price:", parseFloat(stockPrice));
    if (parseFloat(stockPrice) < threshhold[i])
      stockPrices.push(symbol + " - " + stockPrice);
    console.log(`${symbol}: ${stockPrice}`);
    i++;
  }
  console.log("exiting ");
}

async function sendMail() {
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);
  const msg = {
    to: "[email protected]", // Change to your recipient
    from: "[email protected]", // Change to your verified sender
    subject: "Stock alerts",
    html: `<strong> ${JSON.stringify(stockPrices)}  </strong>`,
  };
  await sgMail.send(msg);
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await getPrices();
  if (stockPrices.length > 0) {
    await sendMail();
  }
  console.log(stockPrice);
  res.status(200).json({ name: "" + stockPrices });
}

Testing above code

Now to test above code, you will need to visit https://www.softpost.org/api/stocks

If everything is fine, you will get an email if at least one of the stock is trading below desired levels.

To run the endpoint automatically, you can use https://console.upstash.com/qstash as explanied above.

If running from vercel, do not forget to add production environment variable for send grid api key - SENDGRID_API_KEY.

Web development and Automation testing

solutions delivered!!