Realtime current stock price API integration with JAVASCRIPT.

Realtime current stock price API integration with JAVASCRIPT.

by Financial Modeling Prep

HTML

<div class="container">
  Apple Inc.
  <div class="stock-name"></div>
  <div class="time"></div>
</div>

CSS

body {
  font-family: Helvetica Neue, Arial, sans-serif;
  font-size: 14px;
  color: #444;
}

.table {
  width: 100%;
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  font: normal 13px Arial, sans-serif;
}

.table thead th {
  background-color: #f1efb8;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  padding: 10px;
  text-align: center;
  text-shadow: 1px 1px 1px #fff;
}

.table tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 10px;
  text-shadow: 1px 1px 1px #fff;
  min-width: 80px;
  text-align: center;
}

.stock-name {
  padding: 10px;
  padding-left: 0;
}

.container {
  height: 100px;
  padding: 20px;
  font-size: 20px;
}

JavaScript

var intervalTime = 60;

document.addEventListener('DOMContentLoaded', () => {
  // https://financialmodelingprep.com/developer/docs

  getRequest(
    'https://financialmodelingprep.com/api/v3/quote-short/AAPL?apikey=demo',
    drawOutput
  );

  setInterval(() => {
    getRequest(
      'https://financialmodelingprep.com/api/v3/quote-short/AAPL?apikey=demo',
      drawOutput
    );
  }, 1000 * intervalTime);

  function drawOutput(responseText) {

    let resp = JSON.parse(responseText);

    var elements = document.querySelectorAll('.stock-name')[0];
    
    elements.innerHTML = "$ " + resp[0].price;

    var time = document.querySelectorAll('.time')[0];
    var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
		usaTime = new Date(usaTime);
    time.innerHTML = usaTime;

  }

  function getRequest(url, success) {
    var req = false;
    try {
      req = new XMLHttpRequest();
    } catch (e) {
      try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          return false;
        }
      }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function() {};
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        if (req.status === 200) {
          success(req.responseText)
        }
      }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
  }
})