SHARE
TWEET

btt_stock_tracker_node.js

a guest Mar 26th, 2020 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  *  This script uses a stock market API
  3.  *  to display real-time stock market info
  4.  *  on the Touch Bar using BetterTouchTool.
  5.  *
  6.  *  Note:
  7.  *      Axios must be installed wherever
  8.  *      this JavaScript file is located.
  9.  *      (i.e. `npm install axios`)
  10.  */
  11.  
  12. // Import axios (handles API requests)
  13. const axios = require('axios');
  14.  
  15. // Configuration
  16. const params = {
  17.     symbol: 'AAPL',      // Select the stock you want to track
  18.     token: ''           // Get an API token from https://finnhub.io/register
  19. };
  20.  
  21. // Form a request URL with search params
  22. const APIEndpoint = new URL('https://finnhub.io/api/v1/quote');
  23. for (const key in params)
  24.     APIEndpoint.searchParams.append(key, params[key]);
  25. const requestURL = APIEndpoint.href;
  26.  
  27. // Axios: execute GET request
  28. axios.get(requestURL).then(result => {
  29.     const data = result.data;
  30.  
  31.     // Extract properties from API request result (Object)
  32.     let current = data.c,       // current price
  33.         high = data.h,          // high
  34.         low = data.l,           // low
  35.         open = data.o,          // open
  36.         prevClose = data.pc,    // previous close
  37.         time = data.t;          // timestamp
  38.  
  39.     // Calculate new values
  40.     let todayPercentChange = current - open / open * 100;
  41.  
  42.     // Format values for ouput (use 2 decimal places)
  43.     const decimalPlaces = 2;
  44.     current = parseFloat(current).toFixed(decimalPlaces);
  45.     todayPercentChange = parseFloat(todayPercentChange).toFixed(decimalPlaces);
  46.  
  47.     // Insert conditoinal symbols for clarity
  48.     let positiveSymbol = '';
  49.     if (todayPercentChange > 0) positiveSymbol = '+';
  50.  
  51.     // Display formatted stock info on touch bar
  52.     const returnToBTT = `${params.symbol}: $${current} (${positiveSymbol}${todayPercentChange}\%)`;
  53.     console.log(returnToBTT);   // AAPL: $273.60 (+173.60%)
  54. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top