Skip to content

Instantly share code, notes, and snippets.

@jcoryalvernaz
Created December 16, 2018 17:52
Show Gist options
  • Save jcoryalvernaz/433cf4d732856712649efd1b09d73758 to your computer and use it in GitHub Desktop.
Save jcoryalvernaz/433cf4d732856712649efd1b09d73758 to your computer and use it in GitHub Desktop.
const API_KEY = [Enter API Key Here];
const searchStockAPI = 'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=';
const matchStockAPI = 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=';
$(document).ready(function() {
//Configure typeahead reference https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#options
$('#stockSymbol').typeahead({
highlight: true,
minLength: 1
},
{
display: (suggestion) => {
return suggestion.symbol},
limit: 10,
source: matchStock,
templates: {
suggestion: Handlebars.compile(
'<div>{{symbol}}, {{name}}</div>'
),
notFound: Handlebars.compile(
'No Stock Found for {{query}}'
),
pending: Handlebars.compile(
'Loading Results for {{query}}...'
),
footer: 'Please Choose a Stock ⬆'
}
});
//Give search box focus on page load
$('#stockSymbol').focus();
});
function searchStock() {
let table = document.querySelector('#output');
let message = document.querySelector('#message');
//Clear out table and message
table.innerHTML = '';
message.innerHTML = '';
message.className = '';
let symbol = document.querySelector('#stockSymbol').value;
//Search stock from Alpha Vantage Quote Endpoint
$.getJSON(`${searchStockAPI}${symbol}&apikey=${API_KEY}`, (data) => {
let items = [];
//Handle API frequency error
if (!data["Global Quote"]) {
message.className = 'alert alert-danger';
message.innerHTML = `${data.Note}`;
}
else {
//Table header
items.push(`<thead class="thead-dark"><th style="text-align:center" colspan="2">Stock Information for ${symbol.toUpperCase()}</th></thead>`);
//Table Rows
$.each(data["Global Quote"], ( key, val ) => {
items.push(`<tr><td>${key.substring(4)}</td><td>${val}</td></tr>`);
});
//Append to table
table.innerHTML = items.join('');
}
});
}
function matchStock(query, syncResults, asyncResults) {
//Match stock from Alpha Vantage Search Endpoint
$.getJSON(`${matchStockAPI}${query}&apikey=${API_KEY}`, (data) => {
let matches = [];
//Handle API frequency error
if(!data["bestMatches"]) {
message.className = 'alert alert-danger';
message.innerHTML = `${data.Note}`;
}
else {
//Create JSON objects for each stock with properties of symbol and name
$.each(data["bestMatches"], (key, val) => {
matches.push({symbol: val["1. symbol"], name: val["2. name"]});
});
asyncResults(matches);
}
});
};
//Search stock when user presses enter
$(document).keypress((event) => {
let keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13') {
searchStock.call();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment