Last active
November 29, 2022 11:37
-
-
Save foloinfo/ddbb00551137eaa675dd3dd9e239e087 to your computer and use it in GitHub Desktop.
Google spreadsheet function (app script) to fetch crypto exchange rate using coin api with cache
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
// 1. get your coin api key, free key is limited to 100 req/day | |
// 2. add AppScript on google spreadsheet | |
// 3. save & call function `exchangeRate("BTC")` to get the current exchange rate | |
// refer to the previous gist for function withou cache. | |
const cacheHours = 6 | |
const cacheMsecs = cacheHours * 60 * 60 * 1000 | |
function exchangeRate(ticker) { | |
const cache = PropertiesService.getScriptProperties() | |
const cachedData = cache.getProperties() | |
const prev = cachedData[ticker] && JSON.parse(cachedData[ticker]) || {} | |
const isValidCache = prev['at'] && parseInt(prev['at']) + cacheMsecs > Date.now() | |
if(isValidCache){ | |
return prev['rate'] | |
} | |
const endpoint = `https://rest.coinapi.io/v1/exchangerate/${ticker}/USD` | |
const options = { | |
headers: { | |
"X-CoinAPI-Key": "XXXXX" | |
} | |
} | |
const response = UrlFetchApp.fetch(endpoint, options) | |
const text = response.getContentText() | |
const json = JSON.parse(text) | |
const rate = json['rate'] | |
cache.setProperties({ | |
...cachedData, | |
[ticker]: JSON.stringify({ | |
rate: rate, | |
at: Date.now() | |
}) | |
}); | |
return json['rate'] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bonus for your shell (.zshrc / .bashrc)
usage:
$ rate BTC
I found it's pretty useful since you can also convert fiat <-> fiat like USD <-> JPY.