Building a Stock Tracker in Electron: A Beginner’s Guide

laurentiu.raducu

Building a Stock Tracker in Electron: A Beginner’s Guide

Are you interested in tracking stocks but find it tedious to constantly refresh the page on your browser? Do you want a more efficient way to stay up-to-date with the latest stock prices? Look no further than building your own stock tracker using Electron! In this beginner’s guide, we’ll walk you through the process of building a stock tracker in Electron step-by-step.

What is Electron?

Before we dive into building a stock tracker, let’s first talk about what Electron is. Electron is an open-source framework developed by GitHub that allows developers to build cross-platform desktop applications using web technologies such as HTML, CSS, and JavaScript. With Electron, you can build desktop applications for Windows, macOS, and Linux using the same codebase.

Prerequisites

Before we get started, you’ll need to have the following installed on your computer:

Setting up the Project

Let’s start by creating a new directory for our project and initializing a new Node.js project using the following commands:

mkdir stock-tracker
cd stock-tracker
npm init -y

Next, let’s install Electron as a dev dependency using the following command:

npm install electron --save-dev

Now, let’s create a new file in the root directory of our project called main.js. This file will serve as the main process for our Electron application. In this file, we’ll first require the Electron module and create a new Electron app instance using the following code:

const { app, BrowserWindow } = require('electron')

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

This code creates a new browser window with a width of 800 and a height of 600 pixels and loads an index.html file. We’ll create this file in the next section.

Creating the User Interface

Now that we have our main process set up, let’s create the user interface for our stock tracker. We’ll do this by creating a new file in the root directory of our project called index.html. In this file, we’ll create a simple user interface using HTML and CSS. Here’s an example of what our index.html file might look like:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Stock Tracker</title>
    <style>
      body {
        background-color: #f1f1f1;
        font-family: Arial, sans-serif;
      }

      h1 {
        text-align: center;
        margin-top: 50px;
      }

      input[type="text"] {
        padding: 10px;
        font-size: 16px;
        border: none;
        border-radius: 5px;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
        width: 300px;
        margin-top: 30px;
      }

      button {
        background-color: #4CAF50;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        margin-left: 10px;
        font-size: 16px;
      }

      .stock-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 50px;
      }

      .stock-row {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        width: 600px;
        margin-bottom: 20px;
        padding: 10px;
        background-color: white;
        border-radius: 5px;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
      }

      .stock-symbol {
        font-size: 24px;
        font-weight: bold;
      }

      .stock-price {
        font-size: 24px;
      }

      .stock-change {
        font-size: 18px;
      }

    </style>
  </head>
  <body>
    <h1>Stock Tracker</h1>
    <div class="input-container">
      <input type="text" id="symbolInput" placeholder="Enter stock symbol...">
      <button id="getStockDataButton">Get Stock Data</button>
    </div>
    <div class="stock-container" id="stockContainer"></div>
    <script src="./js/main.js"></script>
  </body>
</html>

This code defines the user interface for our stock tracker using HTML and CSS. The input-container div contains a text input field for the user to enter a stock symbol and a button to retrieve stock data. The stock-container div will contain our stock data, which we’ll add dynamically using JavaScript. Finally, the script tag at the bottom of the file links to our main.js file, which will handle retrieving and displaying the stock data.

Getting Stock Data

Now that we have our user interface set up, let’s move on to getting stock data. We’ll be using the Alpha Vantage API to retrieve stock data. Alpha Vantage provides free APIs for retrieving historical and real-time data for stocks, forex, and cryptocurrencies.

First, let’s install the request package using the following command:

npm install request --save

Next, let’s create a new file in the root directory of our project called stocks.js. In this file, we’ll define a function that retrieves stock data from the Alpha Vantage API and displays it on our user interface. Here’s an example of what our stocks.js file might look like:

const request = require('request')

function getStockData(symbol) {
  const apiKey = 'your-api-key-here'
  const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${apiKey}`

  request(url, { json: true }, (err, res, body) => {
    if (err) { return console.log(err) }

    const stockData = {
      symbol: body['Global Quote']['01. symbol'],
      open: body['Global Quote']['02. open'],
      high: body['Global Quote']['03. high'],
      low: body['Global Quote']['04. low'],
      price: body['Global Quote']['05. price'],
      volume: body['Global Quote']['06. volume'],
      latestTradingDay: body['Global Quote']['07. latest trading day'],
      previousClose: body['Global Quote']['08. previous close'],
      change: body['Global Quote']['09. change'],
      changePercent: body['Global Quote']['10. change percent']
    }

    document.getElementById('symbol').innerHTML = stockData.symbol
    document.getElementById('open').innerHTML = stockData.open
    document.getElementById('high').innerHTML = stockData.high
    document.getElementById('low').innerHTML = stockData.low
    document.getElementById('price').innerHTML = stockData.price
    document.getElementById('volume').innerHTML = stockData.volume
    document.getElementById('latestTradingDay').innerHTML = stockData.latestTradingDay
    document.getElementById('previousClose').innerHTML = stockData.previousClose
    document.getElementById('change').innerHTML = stockData.change
    document.getElementById('changePercent').innerHTML = stockData.changePercent
  })
}

This code defines a function called getStockData that takes a stock symbol as an argument and retrieves stock data from the Alpha Vantage API. It then updates the corresponding elements on our user interface with the retrieved data.

Adding Functionality

Now that we have our main.js, index.html, and stocks.js files set up, let’s add functionality to our stock tracker. We’ll do this by updating our index.html file and adding a new script tag that references our stocks.js file. Here’s an example of what our updated index.html file might look like:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Stock Tracker</title>
    <style>
      body {
        background-color: #f1f1f1;
        font-family: Arial, sans-serif;
      }

      h1 {
        text-align: center;
        margin-top: 50px;
      }

      input[type="text"] {
        padding: 10px;
        font-size: 16px;
        border: none;
        border-radius: 5px;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
        width: 300px;
        margin-top: 30px;
      }

      button {
        padding: 10px 20px;
        font-size: 16px;
        border: none;
        border-radius: 5px;
        background-color: #4CAF50;
        color: #ffffff;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        margin-left: 10px;
      }

      button:hover {
        background-color: #3e8e41;
      }

      #stockData {
        margin-top: 30px;
      }

      #symbol {
        font-size: 24px;
      }

      #stockData p {
        margin-top: 10px;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <h1>Stock Tracker</h1>
    <input type="text" id="symbolInput" placeholder="Enter stock symbol...">
    <button id="getStockDataButton">Get Stock Data</button>
    <div id="stockData">
      <h2 id="symbol"></h2>
      <p>Open: <span id="open"></span></p>
      <p>High: <span id="high"></span></p>
      <p>Low: <span id="low"></span></p>
      <p>Close: <span id="close"></span></p>
      <p>Volume: <span id="volume"></span></p>
    </div>

    <script>
      const { ipcRenderer } = require('electron');

      const symbolInput = document.getElementById('symbolInput');
      const getStockDataButton = document.getElementById('getStockDataButton');
      const symbol = document.getElementById('symbol');
      const open = document.getElementById('open');
      const high = document.getElementById('high');
      const low = document.getElementById('low');
      const close = document.getElementById('close');
      const volume = document.getElementById('volume');

      getStockDataButton.addEventListener('click', () => {
        const symbolValue = symbolInput.value;
        ipcRenderer.send('get-stock-data', symbolValue);
      });

      ipcRenderer.on('stock-data', (event, stockData) => {
        symbol.textContent = stockData.symbol;
        open.textContent = stockData.open;
        high.textContent = stockData.high;
        low.textContent = stockData.low;
        close.textContent = stockData.close;
        volume.textContent = stockData.volume;
      });
    </script>
  </body>
</html>

This index.html file includes the necessary HTML, CSS, and JavaScript code for building a stock tracker in Electron. The HTML code includes an h1 tag for the page title, an input field for entering the stock symbol, a button for triggering the data fetch, and a div for displaying the stock data.

Adding Event Listeners

Next, we’ll add event listeners to our user interface elements to trigger the getStockData function when the user clicks the “Get Stock Data” button or presses the “Enter” key in the text input field. Here’s what our updated main.js file might look like:

const { ipcRenderer } = require('electron')
const { getStockData } = require('./stocks')

const symbolInput = document.getElementById('symbolInput')
const getStockDataButton = document.getElementById('getStockDataButton')

getStockDataButton.addEventListener('click', () => {
  const symbol = symbolInput.value
  getStockData(symbol)
})

symbolInput.addEventListener('keyup', (event) => {
  if (event.key === 'Enter') {
    const symbol = symbolInput.value
    getStockData(symbol)
  }
})

ipcRenderer.on('menu-open-file', () => {
  console.log('Opening file...')
})

This code defines event listeners for the “Get Stock Data” button and the text input field. When the user clicks the button or presses the “Enter” key, the corresponding event listener retrieves the stock symbol from the text input field and passes it to the getStockData function to retrieve and display the stock data.


In this article, we’ve covered the basics of building a stock tracker in Electron. We started by setting up our user interface using HTML, CSS, and JavaScript. We then retrieved stock data using the Alpha Vantage API and displayed it on our user interface. Finally, we added event listeners to our user interface elements to trigger the getStockData function and retrieve stock data when the user clicks the “Get Stock Data” button or presses the “Enter” key.

Building a stock tracker in Electron is a fun and rewarding project that can teach you a lot about web development and desktop applications. With the skills you’ve learned in this article, you can take your stock tracker to the next level by adding additional features like data visualization, real-time updates, and user authentication. Happy coding!

FAQs

  1. Can I use a different API than Alpha Vantage to retrieve stock data?
  • Yes, there are many other APIs available for retrieving stock data. However, Alpha Vantage provides free APIs with no rate limits, making it a popular choice for hobbyist projects.
  1. How can I add data visualization to my stock tracker?
  • You can use a JavaScript charting library like Chart.js or D3.js to create interactive charts and graphs of your stock data.
  1. Is Electron only for building desktop applications?
  • Yes, Electron is a framework specifically designed for building desktop applications using web technologies like HTML, CSS, and JavaScript.
  1. Can I use Electron with other programming languages besides JavaScript?
  • No, Electron is designed to work exclusively with JavaScript and web technologies.
  1. How can I package my Electron application for distribution?
  • You can use a tool like Electron Forge or Electron Builder to package your application as a standalone executable file for Windows, macOS, and Linux.