UNPKG

1.78 kBJavaScriptView Raw
1var BitcoinCharts = require('bitcoincharts');
2var util = require('../util.js');
3var moment = require('moment');
4var _ = require('underscore');
5var log = require('../log.js');
6
7var Watcher = function(config) {
8 if(_.isObject(config))
9 this.symbol = config.market + config.currency;
10
11 this.name = 'bitcoincharts';
12
13 _.bindAll(this);
14
15 this.bitcoinCharts = new BitcoinCharts();
16}
17
18Watcher.prototype.getTrades = function(since, callback, descending) {
19 var params = { symbol: this.symbol };
20 if(since)
21 // we don't want to hammer bitcoincharts,
22 // this will fetch trades between start and now
23 params.start = since.format('X');
24
25 var args = _.toArray(arguments);
26 this.bitcoinCharts.trades(params, _.bind(function(err, data) {
27 if(err)
28 return this.retry(this.getTrades, args);
29
30 if(!data || !data.length)
31 return this.retry(this.getTrades, args);
32
33 // normalize the data
34 var trades = [];
35 _.each(data, function(array) {
36 trades.push({
37 date: array[0],
38 price: array[1],
39 amount: array[2]
40 });
41 });
42
43 if(descending)
44 callback(trades);
45 else
46 callback(trades.reverse());
47 }, this));
48}
49
50// if the exchange errors we try the same call again after
51// waiting 10 seconds
52Watcher.prototype.retry = function(method, args) {
53 var wait = +moment.duration(10, 'seconds');
54 log.debug(this.name, 'returned an error, retrying..');
55
56 var self = this;
57
58 // make sure the callback (and any other fn)
59 // is bound to Trader
60 _.each(args, function(arg, i) {
61 if(_.isFunction(arg))
62 args[i] = _.bind(arg, self);
63 });
64
65 // run the failed method again with the same
66 // arguments after wait
67 setTimeout(
68 function() { method.apply(self, args) },
69 wait
70 );
71}
72
73module.exports = Watcher;
\No newline at end of file