forked from askmike/gekko
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.js
84 lines (75 loc) · 2.12 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var moment = require('moment');
var _ = require('lodash');
var _config = false;
// helper functions
var util = {
getConfig: function() {
if(_config)
return _config;
var path = require('path');
var configFile = path.resolve(util.getArgument('config') || 'config.js');
_config = require(configFile);
return _config;
},
// overwrite the whole config
setConfig: function(config) {
_config = config;
},
setConfigProperty: function(parent, key, value) {
if(parent)
_config[parent][key] = value;
else
_config[key] = value;
},
getArgument: function(argument) {
var ret;
_.each(process.argv, function(arg) {
var pos = arg.indexOf(argument + '=');
if(pos !== -1) {
ret = arg.substr(argument.length + 1);
}
});
return ret;
},
minToMs: function(min) {
return min * 60 * 1000;
},
toMicro: function(moment) {
return moment.format('X') * 1000 * 1000;
},
intervalsAgo: function(amount) {
return moment().subtract('minutes', config.EMA.interval * amount);
},
average: function(list) {
var total = _.reduce(list, function(m, n) { return m + n }, 0);
return total / list.length;
},
// calculate the average trade price out of a sample of trades.
// The sample consists of all trades that happened after the treshold.
calculatePriceSince: function(treshold, trades) {
var sample = [];
_.every(trades, function(trade) {
if(moment.unix(trade.date) < treshold)
return false;
var price = parseFloat(trade.price);
sample.push(price);
return true;
});
return util.average(sample);
},
// calculate the average trade price out of a sample of trades.
// The sample consists of all trades that happened before the treshold.
calculatePriceTill: function(treshold, trades) {
var sample = [];
_.every(trades, function(trade) {
if(moment.unix(trade.date) > treshold)
return false;
var price = parseFloat(trade.price);
sample.push(price);
return true;
});
return util.average(sample);
}
}
var config = util.getConfig();
module.exports = util;