Created
February 9, 2024 19:37
-
-
Save etnichols/1db76397cf16435705c7394bdcf3b2dd to your computer and use it in GitHub Desktop.
Google Apps Script - Coinbase Public API data fetching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get the coinbase price. | |
* | |
* @param {string} currency_pair The currency pair (BTC-EUR, ETH-EUR or LTC-EUR) | |
* @param {string} price_type The price type (buy, sell or spot | |
* @return The current price on coinbase | |
* @customfunction | |
*/ | |
function getPrice(currency_pair = 'BTC-USD', price_type = 'sell') { | |
const valid_price_types = [ "buy", "sell", "spot" ] | |
if (valid_price_types.indexOf(price_type) == -1) { | |
throw new Error('Invalid price_type: ' + price_type + " Valid types are: " + valid_price_types.join(",")) | |
} | |
var url = "https://api.coinbase.com/v2/prices/" + currency_pair + "/" + price_type | |
var response = UrlFetchApp.fetch(url) | |
var data = JSON.parse(response) | |
var price = data.data.amount | |
return price | |
} | |
const ASSETS = ['BTC', 'ETH', 'SOL', 'AVAX', 'LINK', 'ADA', 'ALGO', 'DOGE', 'SHIB']; | |
function updateSheet(){ | |
const sellValues = ASSETS.map((asset) => { | |
const price = getPrice(asset + '-USD'); | |
return [asset, price]; | |
}); | |
const ss = SpreadsheetApp.getActiveSpreadsheet(); | |
const sheet = ss.getSheetByName('PRICES'); | |
const range = sheet.getRange('A2:B10'); | |
range.setValues(sellValues); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment