Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This script uses a stock market API
- * to display real-time stock market info
- * on the Touch Bar using BetterTouchTool.
- *
- * Note:
- * Axios must be installed wherever
- * this JavaScript file is located.
- * (i.e. `npm install axios`)
- */
- // Import axios (handles API requests)
- const axios = require('axios');
- // Configuration
- const params = {
- symbol: 'AAPL', // Select the stock you want to track
- token: '' // Get an API token from https://finnhub.io/register
- };
- // Form a request URL with search params
- const APIEndpoint = new URL('https://finnhub.io/api/v1/quote');
- for (const key in params)
- APIEndpoint.searchParams.append(key, params[key]);
- const requestURL = APIEndpoint.href;
- // Axios: execute GET request
- axios.get(requestURL).then(result => {
- const data = result.data;
- // Extract properties from API request result (Object)
- let current = data.c, // current price
- high = data.h, // high
- low = data.l, // low
- open = data.o, // open
- prevClose = data.pc, // previous close
- time = data.t; // timestamp
- // Calculate new values
- let todayPercentChange = current - open / open * 100;
- // Format values for ouput (use 2 decimal places)
- const decimalPlaces = 2;
- current = parseFloat(current).toFixed(decimalPlaces);
- todayPercentChange = parseFloat(todayPercentChange).toFixed(decimalPlaces);
- // Insert conditoinal symbols for clarity
- let positiveSymbol = '';
- if (todayPercentChange > 0) positiveSymbol = '+';
- // Display formatted stock info on touch bar
- const returnToBTT = `${params.symbol}: $${current} (${positiveSymbol}${todayPercentChange}\%)`;
- console.log(returnToBTT); // AAPL: $273.60 (+173.60%)
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement