How to create a stock Price API

• Updated March 14, 2022

In this article, I’ll cover from beginning to end how to create a stock Price API that tracks the lowest dropped share in the Market. For instance, we’re keeping a track record of the Indian Stock market.

The API can be modified according to your will and you can also sell with slight modifications once you understand the logic behind this. Other developers will be able to use the API and implement it in their front-end applications.

How to create a stock Price API

Our API is returning a JavaCcript Object which contains the share name, current price, 52week Lowest price, 52week High, and percentage dropped in market hours.

Demo

stock api demo

Scraping

To gather information on the Indian stock market, I’ve used the web scraping technique which collects live data from several websites. Groww has been one of the simplest platforms to check the lowest stock so I choose it to implement the Web Scraping process.

Clearing all the doubts about Web scraping, It’s a process where your code will automatically open a headless browser and visit your opted link interact as you program it to, then close the browser. The complete process takes place in the background within a flash so it can be implemented in backend programming.

Puppeteer‘ is one of the awesome web scraping Libraries I’ve used in my project to scrape the target page and gather data on the loser Stock.

CronJob

cronjob function in api

While gathering data there might be fluctuations in the Stock Market, to handle continuous change CronJob is added. Basically, CronJob helps to rerun our scarping functions from time to time.

Code

const puppeteer = require('puppeteer');
const express = require('express');
const cron = require('node-cron');


const app = express()

app.use(express.json());


cron.schedule('* * * * *', async () => {
    console.log('cron working')
    await scrapeChannel('https://groww.in/markets/top-losers?index=GIDXNIFTY100')
});


var stockApi

async function scrapeChannel(url) { // init function with to be scraped url argument

    const browser = await puppeteer.launch();      // launch puppeteer
    const page = await browser.newPage();       // generate a headless browser
    await page.goto(url);      // open argument passed url



    const [el] = await page.$x('/html/body/div/div/div[2]/div[2]/div/div/div[1]/div/div/table/tbody/tr[1]/td[1]/a');        // select specific element on the url fetched page with 'xpath' & assign it to el
    const text = await el.getProperty('textContent');       // choose type of data needed
    const name = await text.jsonValue();    // extract the data type

    const [el2] = await page.$x('/html/body/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div/table/tbody/tr[1]/td[3]/text()');
    const priceSrc = await el2.getProperty('textContent');
    const priceVal = await priceSrc.jsonValue();

    const [el3] = await page.$x('/html/body/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div/table/tbody/tr[1]/td[5]');
    const highSrc = await el3.getProperty('textContent');
    const highVal = await highSrc.jsonValue();

    const [el4] = await page.$x('/html/body/div/div/div[2]/div[2]/div/div/div[1]/div/div/table/tbody/tr[1]/td[4]');
    const lowSrc = await el4.getProperty('textContent');
    const lowVal = await lowSrc.jsonValue();

    const [el5] = await page.$x('/html/body/div/div/div[2]/div[2]/div/div/div[1]/div/div/table/tbody/tr[1]/td[3]/div');
    const downBy = await el5.getProperty('textContent');
    const downVal = await downBy.jsonValue();


    
    stockApi = {
        stocksName : name,
        currentPrice: priceVal,
        lowPrice: lowVal,
        highPrice : highVal,
        downBy : downVal
    }
    console.log(stockApi)
    browser.close();    // close the temporary headless browser    
}

scrapeChannel('https://groww.in/markets/top-losers?index=GIDXNIFTY100')

app.get('/', (req, res)=>{
        res.send(stockApi)
})


const port = process.env.PORT || 3000

app.listen(port, () => {
    console.log(`server started at port ${port}`)
})

Related: Create own Encryption Algorithm in JavaScript

Wrapping up

After the process, the program returns a JSON file as an API, which later can be used by FrontEnd developers in their applications.

loser stock api demo

This article elaborates on How to create a stock Price API with NodeJS and puppeteer. Major processes used in the code have been elaborated. Still, if you’re facing any issue regarding the program, raise an issue on GitHub or comment below & I’ll try to reach you as soon as possible.

Sharing Is Caring:

An aspiring BTech Electronics and Communication student, obsessed with Coding, Gadgets, and Blogging.

Leave a Comment