Advertisement
urosevic

Simple AlphaVantage.co jQuery API example

Aug 15th, 2018
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.48 KB | None | 0 0
  1. /**
  2.  *
  3.  * AlphaVantage.co simple jQuery API demo
  4.  * API Documentation: https://www.alphavantage.co/documentation/
  5.  *
  6.  */
  7. jQuery(document).ready(function($) {
  8.     // AlphaVantage.co API Key - get your own from https://www.alphavantage.co/support/#api-key and replace `demo` below
  9.     var apiKey = 'demo';
  10.  
  11.     // Define stock symbol
  12.     var symbol = 'BABA';
  13.  
  14.     // Build request URL
  15.     var requestUrl = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + symbol + '&apikey=' + apiKey;
  16.  
  17.     // Get JSON-formatted data from the AlphaVantage.co API (AJAX request)
  18.     $.getJSON( requestUrl, function( response ) {
  19.         if ( response.Information ) {
  20.             // Handle wrong API key response
  21.             console.log(response.Information);
  22.         } else if (response["Error Message"]) {
  23.             // Handle error responses
  24.             console.log(response["Error Message"]);
  25.         } else {
  26.             // Get last refreshed date
  27.             var lastRefreshed = response["Meta Data"]["3. Last Refreshed"];
  28.             // Get time series object
  29.             var timeSeries = response["Time Series (Daily)"];
  30.             // Get last item series
  31.             var lastData = timeSeries[Object.keys(timeSeries)[0]];
  32.             // Get stock close from object
  33.             var close = lastData["4. close"];
  34.             // Output message to console
  35.             console.log(symbol + ' ' + close + ' (Last Refreshed at ' + lastRefreshed + ')');
  36.         }
  37.     });
  38. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement