Skip to content

Instantly share code, notes, and snippets.

@yhauxell
Last active January 5, 2021 16:10
Show Gist options
  • Save yhauxell/f932f2c4520c99dfd450fadb54754e0f to your computer and use it in GitHub Desktop.
Save yhauxell/f932f2c4520c99dfd450fadb54754e0f to your computer and use it in GitHub Desktop.
Scrap price data from coinmarketcap into google sheet
/**
This function is intended to be used as (google app script)[https://developers.google.com/apps-script/guides/sheets/functions#using_a_custom_function] inside google sheets to load the price for a given coin name from coinmarketcap
Since google sheet makes exahustive calls to their functions this one has implemented a cache mechanism to prevent calling cooinmarketcap constantly and being banned easily
The cache last 30 minutes but can be reseted by passing true as second param to the function in your sheet cell
usage:
| A1 | A2
| bitcoin | =CRYPTOPRICE(A1)
Forced price refresh:
=CRYPTOPRICE(A2, true)
*/
function CRYPTOPRICE(input = 'bitcoin', reload = false) {
const cache = CacheService.getDocumentCache();
let price = cache.get(input);
if(!price || reload){
const response = UrlFetchApp.fetch(`https://coinmarketcap.com/currencies/${input}`).getContentText();
const parsed = new RegExp('<div class="priceValue___11gHJ">([^<]+)<\/div>').exec(response);
price = parsed[1].replace(',', '');
cache.put(input, price, 1800);//every 30 minutes expires so we refresh the price
Logger.log('##Save price to cache: ', price);
}else{
Logger.log('##Loaded cached price: ', price);
}
return price;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment