forked from DeviaVir/zenbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsi.js
42 lines (40 loc) · 1.44 KB
/
rsi.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
var precisionRound = function(number, precision) {
var factor = Math.pow(10, precision)
return Math.round(number * factor) / factor
}
module.exports = function rsi (s, key, length) {
if (s.lookback.length >= length) {
var avg_gain = s.lookback[0][key + '_avg_gain']
var avg_loss = s.lookback[0][key + '_avg_loss']
if (typeof avg_gain === 'undefined') {
var gain_sum = 0
var loss_sum = 0
var last_close
s.lookback.slice(0, length).forEach(function (period) {
if (last_close) {
if (period.close > last_close) {
gain_sum += period.close - last_close
}
else {
loss_sum += last_close - period.close
}
}
last_close = period.close
})
s.period[key + '_avg_gain'] = gain_sum / length
s.period[key + '_avg_loss'] = loss_sum / length
}
else {
var current_gain = s.period.close - s.lookback[0].close
s.period[key + '_avg_gain'] = ((avg_gain * (length - 1)) + (current_gain > 0 ? current_gain : 0)) / length
var current_loss = s.lookback[0].close - s.period.close
s.period[key + '_avg_loss'] = ((avg_loss * (length - 1)) + (current_loss > 0 ? current_loss : 0)) / length
}
if(s.period[key + '_avg_loss'] == 0) {
s.period[key] = 100
} else {
var rs = s.period[key + '_avg_gain'] / s.period[key + '_avg_loss']
s.period[key] = precisionRound(100 - (100 / (1 + rs)), 2)
}
}
}