Skip to content

Instantly share code, notes, and snippets.

@martinvol
Created January 11, 2017 22:56
Show Gist options
  • Save martinvol/6a63fb6a4bb7bc6d0c95c8085d36d820 to your computer and use it in GitHub Desktop.
Save martinvol/6a63fb6a4bb7bc6d0c95c8085d36d820 to your computer and use it in GitHub Desktop.
Bitcoin index price API with up/down arrow
var request = require('request@2.27.0');
function get_rate(json_body){
// parse the response to get current price.
return json_body.bpi.USD.rate;
}
module.exports = function (ctx, done) {
var date = new Date();
var current_hour = date.getHours();
var url = "http://api.coindesk.com/v1/bpi/currentprice.json"
// get current price
request({
url: url,
json: true }, function (error, response, body) {
if (error || !response.statusCode === 200) return done(error);
var current_rate = get_rate(body);
// retrieve last values
ctx.storage.get(function get_history (error, data) {
if (error) return done(error);
// create the document if it doesn't exist
data = data || {};
// update last hour price
data[date.getHours().toString()] = current_rate;
ctx.storage.set(data, function (error) {
// generate response
if (error) return done(error);
var past_hour = (date.getHours()-1).toString();
var last_hour_close = data[past_hour];
done(null, {current_rate: current_rate, last_hour_close: last_hour_close,
up: current_rate > last_hour_close});
});
});
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment