· 6 years ago · Mar 27, 2020, 12:30 AM
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)
13const axios = require('axios');
14
15// Configuration
16const 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
22const APIEndpoint = new URL('https://finnhub.io/api/v1/quote');
23for (const key in params)
24 APIEndpoint.searchParams.append(key, params[key]);
25const requestURL = APIEndpoint.href;
26
27// Axios: execute GET request
28axios.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});