Skip to content

Instantly share code, notes, and snippets.

@abrkn abrkn/derp.gs
Last active Apr 18, 2018

Embed
What would you like to do?
var ISO_DATE_SUFFIX = 'T00:00:00';
var SLEEP_BEFORE_FETCH = 2000;
var cache = CacheService.getDocumentCache();
function fetchWithCache(url) {
var raw = cache.get(url);
if (raw) {
return raw;
}
Utilities.sleep(SLEEP_BEFORE_FETCH);
var res = UrlFetchApp.fetch(url);
raw = res.getContentText();
cache.put(url, raw);
return raw;
}
function fetchCryptowatchRateFor(venue, symbol, date, which) {
var index = ['open', 'high', 'low', 'close'].indexOf(which || "close");
if (index === -1) throw ("which shoul be open, high, low, or close");
var date = new Date(date + 'T00:00:00.000Z');
var ts = Math.floor((date.getTime() / 1000)).toString();
var url = Utilities.formatString(
'https://api.cryptowat.ch/markets/%s/%s/ohlc?before=%s&after=%s&periods=86400',
venue,
symbol,
ts,
ts
);
var raw = fetchWithCache(url);
var points = JSON.parse(raw).result['86400'];
var point = points[0];
// 0=date, 1=open, 2=high, 3=low, 4=close, 5=volume
return point[index + 1];
}
function testFetchCryptowatchRateFor() {
Logger.log(fetchCryptowatchRateFor('bitfinex', 'BCHUSD', '2018-03-14'));
}
// date is ISO
function fetchOerRateFor(currency, date) {
var cacheKey = new Date(date).toISOString().substr(0, 13) + ISO_DATE_SUFFIX;
Logger.log('cacheKey');
Logger.log(cacheKey);
var url = Utilities.formatString(
'https://openexchangerates.org/api/historical/%s.json?app_id=%s&symbols=%s',
date,
'yolo',
currency
);
var raw = fetchWithCache(url);
var json = JSON.parse(raw);
var rate = json.rates[currency];
return rate;
}
function test() {
// fetchOerRateFor('NOK', '2017-01-01');
// testFetchCryptowatchRateFor();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.