Skip to content

Instantly share code, notes, and snippets.

@howie50417
Created December 26, 2017 16:49
Show Gist options
  • Save howie50417/cae0cf3fe92f2e4b47a4212dd4ec40e3 to your computer and use it in GitHub Desktop.
Save howie50417/cae0cf3fe92f2e4b47a4212dd4ec40e3 to your computer and use it in GitHub Desktop.
ATR.js
var Heap = require("collections/heap");
var Indicator = function(windowLength, len_out=20) {
this.input = 'candle';
this.len_in = windowLength;
this.candle_list = [];
this.result = 0;
this.heap_count = 0;
this.price_heap = new Heap([]);
this.len_out = len_out;
}
function get_real_price(candle_now, candle_last){
return (candle_last.close>candle_now.high ? candle_last.close : candle_now.high) -
(candle_last.close<candle_now.low ? candle_last.close : candle_now.low);
}
Indicator.prototype.update = function(candle) {
this.candle_list.unshift(candle);
if(this.candle_list.length == 1){
return candle.high - candle.low;
}
this.price_heap.push(this.candle_list[0].high);
this.price_heap.push(this.candle_list[0].low);
this.price_heap.push(this.candle_list[1].close);
this.heap_count += 1;
if(this.heap_count > this.len_in){
this.price_heap.delete(this.candle_list[this.heap_count-1].high);
this.price_heap.delete(this.candle_list[this.heap_count-1].low);
this.price_heap.delete(this.candle_list[this.heap_count].close);
this.heap_count -= 1;
}
this.candle_list[0].real_price = this.price_heap.max() - this.price_heap.min();
this.max = this.price_heap.max();
this.min = this.price_heap.min();
var sum = 0;
var c = 0;
for(var i=0;i<this.len_out;i++){
if(this.len_in*i >= this.candle_list.length){
break;
}
sum += this.candle_list[this.len_in*i].real_price;
c += 1;
}
this.result = sum / c;
}
module.exports = Indicator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment