├── .eslint-default-config.yml ├── .eslintrc ├── README.md ├── bower.json ├── css └── styles.css ├── gulpfile.js ├── index.html ├── js ├── atr.js ├── demo.js ├── ema.js ├── indicators.js ├── rsi.js └── sma.js ├── license.txt ├── manifest.json └── package.json /.eslint-default-config.yml: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/eslint/eslint/blob/master/packages/eslint-config-eslint/default.yml 2 | # Updated 2015-04-06 3 | 4 | extends: 5 | "eslint:recommended" 6 | 7 | rules: 8 | array-callback-return: "error" 9 | indent: ["error", 4, {SwitchCase: 1}] 10 | block-spacing: "error" 11 | brace-style: ["error", "1tbs"] 12 | camelcase: ["error", { properties: "never" }] 13 | callback-return: ["error", ["cb", "callback", "next"]] 14 | comma-spacing: "error" 15 | comma-style: ["error", "last"] 16 | consistent-return: "error" 17 | curly: ["error", "all"] 18 | default-case: "error" 19 | dot-notation: ["error", { allowKeywords: true }] 20 | eol-last: "error" 21 | eqeqeq: "error" 22 | func-style: ["error", "declaration"] 23 | guard-for-in: "error" 24 | key-spacing: ["error", { beforeColon: false, afterColon: true }] 25 | keyword-spacing: "error" 26 | lines-around-comment: ["error", { 27 | beforeBlockComment: true, 28 | afterBlockComment: false, 29 | beforeLineComment: true, 30 | afterLineComment: false 31 | }] 32 | new-cap: "error" 33 | newline-after-var: "error" 34 | new-parens: "error" 35 | no-alert: "error" 36 | no-array-constructor: "error" 37 | no-caller: "error" 38 | no-console: 0 39 | no-delete-var: "error" 40 | no-eval: "error" 41 | no-extend-native: "error" 42 | no-extra-bind: "error" 43 | no-fallthrough: "error" 44 | no-floating-decimal: "error" 45 | no-implied-eval: "error" 46 | no-invalid-this: "error" 47 | no-iterator: "error" 48 | no-label-var: "error" 49 | no-labels: "error" 50 | no-lone-blocks: "error" 51 | no-loop-func: "error" 52 | no-mixed-spaces-and-tabs: ["error", false] 53 | no-multi-spaces: "error" 54 | no-multi-str: "error" 55 | no-native-reassign: "error" 56 | no-nested-ternary: "error" 57 | no-new: "error" 58 | no-new-func: "error" 59 | no-new-object: "error" 60 | no-new-wrappers: "error" 61 | no-octal: "error" 62 | no-octal-escape: "error" 63 | no-process-exit: "error" 64 | no-proto: "error" 65 | no-redeclare: "error" 66 | no-return-assign: "error" 67 | no-script-url: "error" 68 | no-self-assign: "error" 69 | no-sequences: "error" 70 | no-shadow: "error" 71 | no-shadow-restricted-names: "error" 72 | no-spaced-func: "error" 73 | no-trailing-spaces: "error" 74 | no-undef: "error" 75 | no-undef-init: "error" 76 | no-undefined: "error" 77 | no-underscore-dangle: ["error", {allowAfterThis: true}] 78 | no-unmodified-loop-condition: "error" 79 | no-unused-expressions: "error" 80 | no-unused-vars: ["error", {vars: "all", args: "after-used"}] 81 | no-use-before-define: "error" 82 | no-useless-concat: "error" 83 | no-with: "error" 84 | one-var-declaration-per-line: "error" 85 | quotes: ["error", "double"] 86 | radix: "error" 87 | require-jsdoc: "error" 88 | semi: "error" 89 | semi-spacing: ["error", {before: false, after: true}] 90 | space-before-blocks: "error" 91 | space-before-function-paren: ["error", "never"] 92 | space-in-parens: "error" 93 | space-infix-ops: "error" 94 | space-unary-ops: ["error", {words: true, nonwords: false}] 95 | spaced-comment: ["error", "always", { exceptions: ["-"]}] 96 | strict: ["error", "global"] 97 | valid-jsdoc: ["error", { prefer: { "return": "returns"}}] 98 | wrap-iife: "error" 99 | yoda: ["error", "never"] 100 | 101 | # Previously on by default in node environment 102 | no-catch-shadow: "off" 103 | no-mixed-requires: "error" 104 | no-new-require: "error" 105 | no-path-concat: "error" 106 | handle-callback-err: ["error", "err"] -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | extends: 2 | ".eslint-default-config.yml" 3 | 4 | rules: 5 | camelcase: [2, {"properties": "always"}] 6 | comma-dangle: [2, "never"] 7 | dot-location: [2, "property"] 8 | lines-around-comment: 0 9 | newline-after-var: 0 10 | no-alert: 2 11 | no-console: 2 12 | no-debugger: 2 13 | no-else-return: 2 14 | no-unmodified-loop-condition: 0 15 | object-curly-spacing: [2, "always"] 16 | operator-linebreak: [2, "after"] 17 | space-before-function-paren: [2, {"anonymous": "always", "named": "never"}] # JSLint style 18 | strict: 0 19 | quotes: [2, "single"] 20 | 21 | no-trailing-spaces: ["error", { "skipBlankLines": true }] 22 | indent: ["error", "tab", {SwitchCase: 1}] 23 | no-nested-ternary: 0 24 | no-invalid-this: 0 25 | eol-last: 0 26 | require-jsdoc: 0 27 | brace-style: [2, "1tbs", { "allowSingleLine": true }] 28 | wrap-iife: [2, "any"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ### ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) We encourage you to use Highstock 6+ as it has a vast range of technical analysis indicators build in. This plugin was build for older versions of Highstock 3 | 4 | # Indicators - Highstock module 5 | 6 | Indicators available in this plugin: **SMA, EMA, ATR, RSI**. You can use these indicators for free. 7 | 8 | We also have other indicators available: **Bollinger Bands, MACD, Momentum, CCI, Stochastic, Rate of Change (ROC), Accumulation / distribution (AD), Pivot Points, ZigZag, Weighted Moving Average (WMA), PSAR, MFI, Price Envelopes.**
9 | If you're are interested in purchasing them, developing new indicators or any other tools, please contact us at: start@blacklabel.pl 10 | 11 | You may also want to check our other demo here: http://demo.blacklabel.pl. 12 | 13 | Go to project page to see this module in action: [http://blacklabel.github.io/indicators/](http://blacklabel.github.io/indicators/) 14 | 15 | 16 | ### Requirements 17 | 18 | * Version 2.0+ requires the latest Highstock (v2.1.5+) 19 | * Version 1.1 requires Highstock v2.1.5 20 | * Version <1.1 supported since Highstock v1.3.9 to Highstock v2.1.4 21 | 22 | ### Versions 23 | 24 | * 2.x - Improved logic for calculations and performance. Values are based on initial points, not grouped. When points are grouped by `dataGrouping` then indicators values are grouped too. 25 | * 1.x - Initial version of Indicators.js. Calculations are based on grouped points (aka `dataGrouping`) 26 | 27 | ### Installation 28 | 29 | * Like any other Highcharts module (e.g. exporting), add ` 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |

Indicators - Highstock module

20 |

Indicators available in this plugin: SMA, EMA, ATR, RSI. You can use these indicators for free.

21 |

We also have other indicators available: Bollinger Bands, MACD, Momentum, CCI, Stochastic, Rate of Change (ROC), Accumulation / distribution (AD), Pivot Points, ZigZag, Weighted Moving Average (WMA), PSAR, MFI, Price Envelopes..
If you're are interested in purchasing them, developing new indicators or any other tools, please contact us at: start@blacklabel.pl 22 | You may also want to check our other demo here: http://demo.blacklabel.pl.

23 | 24 |
25 | 26 |

Requirements

27 | 28 | 33 | 34 |

Versions

35 | 36 | 40 | 41 |

Installation

42 | 43 | 57 | 58 |

Code

59 | 60 |

The latest code is available on github: (https://github.com/blacklabel/indicators/)

61 | 62 |

Usage and demos

63 |
 64 | indicators: [{
 65 |             id: 'AAPL',
 66 |             type: 'sma',
 67 |             params: {
 68 |                 period: 5,
 69 |             }
 70 |         }, {
 71 |             id: 'AAPL',
 72 |             type: 'ema',
 73 |             params: {
 74 |                 period: 5,
 75 |                 index: 0
 76 |             },
 77 |             styles: {
 78 |                 strokeWidth: 2,
 79 |                 stroke: 'green',
 80 |                 dashstyle: 'solid'
 81 |             }
 82 |         }, {
 83 |             id: 'AAPL',
 84 |             type: 'atr',
 85 |             params: {
 86 |                 period: 14,
 87 |             },
 88 |             styles: {
 89 |                 strokeWidth: 2,
 90 |                 stroke: 'orange',
 91 |                 dashstyle: 'solid'
 92 |             },
 93 |             yAxis: {
 94 |                 lineWidth:2,
 95 |                 title: {
 96 |                     text:'My ATR title'
 97 |                 }
 98 |             }   
 99 |         }, {
100 |             id: 'AAPL',
101 |             type: 'rsi',
102 |             params: {
103 |                 period: 14,
104 |                 overbought: 70,
105 |                 oversold: 30
106 |             },
107 |             styles: {
108 |                 strokeWidth: 2,
109 |                 stroke: 'black',
110 |                 dashstyle: 'solid'
111 |             },
112 |             yAxis: {
113 |                 lineWidth:2,
114 |                 title: {
115 |                     text:'My RSI title'
116 |                 }
117 |             }   
118 | }],
119 | tooltip:{
120 |     enabledIndicators: true
121 | },
122 | 
123 | 124 |

Parameters

125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 |
PropertyTypeDescription
idStringid of series
typeStringtype of indicator (one of: sma, ema, atr, rsi)
showInLegendBooleandetermines if indicator should be visible in the legend. Defaults to false.
nameStringname is used in legend and tooltip to display indicator. By default it's the same as type.
stylesObjectcolor, dashstyle, width etc. for a indicator line
yAxis (ATR/RSI)ObjectyAxis object like in Highcharts, options for additional yAxis
paramsObjectconfig options for indicator
params.approximation (SMA/EMA/ATR/RSI)String/FunctionThe same property as in dataGrouping.approximation for Highstock. Supported since version 2.0.0. Defaults to "average".
params.period (SMA/EMA/ATR/RSI)Numberbase perdiod for indicator (it's number of points to be calculated). Defaults to 14.
params.index (SMA/EMA)Numbery-value index. Useful when using candlestick/ohlc/range series to determine which value (open/high/low/close) should be used in indicator. Defaults to 0.
params.overbought (RSI)Numberoverbought value between 0-100. Defaults to 70.
params.oversold (RSI)Numberoversold value between 0-100. Defaults to 30.
params.decimals (RSI)Number Precision for the calculations. For example decimals=1 will cut off value 123.4567 to 123.4. Higher value provides more accurate values, but will cost performance. Defaults to 4.
tooltip.pointFormatString point.color and point.y return values from indicator. Disabled by default.
155 | 156 | 157 |

New options/methods in Chart:

158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 |
Method Version: Description
chart.addIndicator(options, [redraw]) v 1.0.0+ Add new indicator with given options. Optionally redraw chart.
chart.indicators.allItems v 1.0.0+ Array containing all indicators.
chart.alignAxes v 1.0.9+ true/false. When idicator requires separate yAxis (like ATR or RSI) then indicators plugin will update heights of the axes to fit plotting area. Disable it and set yAxis.top and yAxis.height when you want different heights for the y-axes. Defaults to true. Note: When disabled, top and height options need to be set for all axes for better view.
tooltip.enabledIndicators v 1.0.0+ true/false, show indicators in tooltip. Disabled by default.
Highcharts.approximations v 2.0.0+ Object containing built-in approximations (functions) in Highstock. For more details see dataGrouping.approximation
195 | 196 | 197 |

Indicator object

198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 |
Method Description
indicator.update(options) Update indicator with given options
indicator.destroy() Destroy indicator
indicator.setVisible(true|false) Hide or show indicator.
221 | 222 |

Demo

223 | 224 |

Demos are available at project's github page: (http://blacklabel.github.io/indicators/)

225 |
226 | 227 | 228 | -------------------------------------------------------------------------------- /js/atr.js: -------------------------------------------------------------------------------- 1 | /* global Highcharts module:true */ 2 | (function (factory) { 3 | if (typeof module === 'object' && module.exports) { 4 | module.exports = factory; 5 | } else { 6 | factory(Highcharts); 7 | } 8 | }(function (HC) { 9 | 'use strict'; 10 | /** 11 | 12 | Each indicator requires mothods: 13 | 14 | - getDefaultOptions() - returns object with default parameters, like period etc. 15 | - getValues(chart, series, options, points) - returns array of calculated values for indicator 16 | - getGraph(chart, series, options, values) - returns path, or columns as SVG elements to add. 17 | Doesn't add to the chart via renderer! 18 | 19 | **/ 20 | 21 | var merge = HC.merge, 22 | isArray = HC.isArray, 23 | addAxisPane = HC.Axis.prototype.addAxisPane, 24 | maxInArray = HC.Axis.prototype.maxInArray, 25 | UNDEFINED; 26 | 27 | HC.Indicator.prototype.atr = { 28 | getDefaultOptions: function () { 29 | return { 30 | period: 14, 31 | approximation: 'average' 32 | }; 33 | }, 34 | getValues: function (chart, series, options, extraPoints) { 35 | var utils = this.utils, 36 | params = options.params, 37 | period = params.period, 38 | xVal = extraPoints[0].concat(series.processedXData || []), // #22 39 | yVal = extraPoints[1].concat(series.processedYData || []), // #22 40 | yValLen = yVal ? yVal.length : 0, 41 | xValue = xVal[0], 42 | yValue = yVal[0], 43 | range = 1, 44 | prevATR = 0, 45 | TR = 0, 46 | ATR = [], 47 | xData = [], 48 | yData = [], 49 | point, i, points; 50 | 51 | points = [[xValue, yValue]]; 52 | 53 | if ((xVal.length <= period) || !isArray(yVal[0]) || yVal[0].length !== 4) { 54 | return false; 55 | } 56 | 57 | for (i = 1; i < yValLen; i++) { 58 | 59 | utils.accumulateAverage(points, xVal, yVal, i); 60 | 61 | if (period < range) { 62 | point = utils.populateAverage(points, xVal, yVal, i, period, prevATR); 63 | prevATR = point[1]; 64 | ATR.push(point); 65 | xData.push(point[0]); 66 | yData.push(point[1]); 67 | } else if (period === range) { 68 | prevATR = TR / (i - 1); 69 | ATR.push([xVal[i - 1], prevATR]); 70 | range++; 71 | } else { 72 | TR += utils.getTR(yVal[i - 1], yVal[i - 2]); 73 | range++; 74 | } 75 | } 76 | 77 | point = utils.populateAverage(points, xVal, yVal, i, period, prevATR); 78 | xData.push(point[0]); 79 | yData.push(point[1]); 80 | ATR.push(point); 81 | 82 | // register extremes for axis; 83 | options.yAxisMax = maxInArray(ATR); 84 | options.yAxisMin = 0; 85 | 86 | return { 87 | values: ATR, 88 | xData: xData, 89 | yData: yData 90 | }; 91 | }, 92 | getGraph: function (chart, series, options, values) { 93 | var path = [], 94 | attrs = {}, 95 | xAxis = series.xAxis, 96 | atrLen = values.length, 97 | max = maxInArray(values), 98 | yAxis, 99 | defaultOptions, 100 | userOptions, 101 | index, 102 | atrX, 103 | atrY, 104 | i; 105 | 106 | defaultOptions = { 107 | min: 0, 108 | max: max, 109 | // tickPixelInterval: 50, 110 | // height: 100, 111 | title: { 112 | text: 'ATR' 113 | } 114 | }; 115 | 116 | if (options.visible === false) { 117 | return false; 118 | } 119 | 120 | userOptions = merge(defaultOptions, options.yAxis); 121 | 122 | if (options.Axis === UNDEFINED) { 123 | index = addAxisPane(chart, userOptions); 124 | options.Axis = chart.yAxis[index]; 125 | options.Axis.oldMax = max; 126 | } else { 127 | // options.Axis.render(); 128 | } 129 | 130 | yAxis = options.Axis; 131 | 132 | 133 | options.styles = attrs = merge({ 134 | 'stroke-width': 2, 135 | stroke: 'red', 136 | dashstyle: 'Dash' 137 | }, options.styles); 138 | 139 | path.push('M', xAxis.toPixels(values[0][0]), yAxis.toPixels(values[0][1])); 140 | 141 | for (i = 0; i < atrLen; i++) { 142 | atrX = values[i][0]; 143 | atrY = values[i][1]; 144 | path.push('L', xAxis.toPixels(atrX), yAxis.toPixels(atrY)); 145 | } 146 | 147 | return [chart.renderer.path(path).attr(attrs)]; 148 | }, 149 | utils: { 150 | accumulateAverage: function (points, xVal, yVal, i) { 151 | var xValue = xVal[i], 152 | yValue = yVal[i]; 153 | 154 | points.push([xValue, yValue]); 155 | }, 156 | populateAverage: function (points, xVal, yVal, i, period, prevATR) { 157 | var x = xVal[i - 1], 158 | TR = this.getTR(yVal[i - 1], yVal[i - 2]), 159 | y; 160 | 161 | y = (((prevATR * (period - 1)) + TR) / period); 162 | return [x, y]; 163 | }, 164 | getTR: function (currentPoint, prevPoint) { 165 | var pointY = currentPoint, 166 | prevY = prevPoint, 167 | HL = pointY[1] - pointY[2], 168 | HCp = prevY === UNDEFINED ? 0 : Math.abs(pointY[1] - prevY[3]), 169 | LCp = prevY === UNDEFINED ? 0 : Math.abs(pointY[2] - prevY[3]), 170 | TR = Math.max(HL, HCp, LCp); 171 | 172 | return TR; 173 | } 174 | } 175 | }; 176 | })); -------------------------------------------------------------------------------- /js/demo.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | 3 | var adv_options = { 4 | title: { 5 | useHTML: true, 6 | x: -10, 7 | y: 8, 8 | text: 'SMA, EMA, ATR, RSI indicators Black Label plugin by ' 9 | }, 10 | indicators: [{ 11 | id: 'AAPL', 12 | type: 'sma', 13 | params: { 14 | period: 14 15 | } 16 | }, { 17 | id: 'AAPL', 18 | type: 'ema', 19 | params: { 20 | period: 14, 21 | index: 0 //optional parameter for ohlc / candlestick / arearange - index of value 22 | }, 23 | styles: { 24 | strokeWidth: 2, 25 | stroke: 'green', 26 | dashstyle: 'solid' 27 | } 28 | }, { 29 | id: 'AAPL', 30 | type: 'atr', 31 | params: { 32 | period: 14 33 | }, 34 | styles: { 35 | strokeWidth: 2, 36 | stroke: 'orange', 37 | dashstyle: 'solid' 38 | }, 39 | yAxis: { 40 | lineWidth: 2, 41 | title: { 42 | text: 'ATR' 43 | } 44 | } 45 | }, { 46 | id: 'AAPL', 47 | type: 'rsi', 48 | params: { 49 | period: 14, 50 | overbought: 70, 51 | oversold: 30 52 | }, 53 | styles: { 54 | strokeWidth: 2, 55 | stroke: 'black', 56 | dashstyle: 'solid' 57 | }, 58 | yAxis: { 59 | lineWidth: 2, 60 | title: { 61 | text: 'RSI' 62 | } 63 | } 64 | }], 65 | yAxis: { 66 | opposite: false, 67 | title: { 68 | text: 'DATA SMA EMA', 69 | x: -4 70 | }, 71 | lineWidth: 2, 72 | labels: { 73 | x: 22 74 | } 75 | }, 76 | rangeSelector: { 77 | selected: 0 78 | }, 79 | tooltip: { 80 | enabledIndicators: true 81 | }, 82 | series: [{ 83 | cropThreshold: 0, 84 | id: 'AAPL', 85 | name: 'AAPL', 86 | data: [], 87 | tooltip: { 88 | valueDecimals: 2 89 | } 90 | }] 91 | }; 92 | 93 | $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) { 94 | 95 | adv_options.series[0].type = 'candlestick'; 96 | adv_options.series[0].data = data; 97 | 98 | $('#chart-advanced').highcharts('StockChart', adv_options); 99 | }); 100 | 101 | }); -------------------------------------------------------------------------------- /js/ema.js: -------------------------------------------------------------------------------- 1 | /* global Highcharts module:true */ 2 | (function (factory) { 3 | if (typeof module === 'object' && module.exports) { 4 | module.exports = factory; 5 | } else { 6 | factory(Highcharts); 7 | } 8 | }(function (HC) { 9 | 'use strict'; 10 | /** 11 | 12 | Each indicator requires mothods: 13 | 14 | - getDefaultOptions() - returns object with default parameters, like period etc. 15 | - getValues(chart, series, options, points) - returns array of calculated values for indicator 16 | - getGraph(chart, series, options, values) - returns path, or columns as SVG elements to add. 17 | Doesn't add to the chart via renderer! 18 | 19 | **/ 20 | 21 | var merge = HC.merge, 22 | isArray = HC.isArray, 23 | minInArray = HC.Axis.prototype.minInArray, 24 | maxInArray = HC.Axis.prototype.maxInArray; 25 | 26 | HC.Indicator.prototype.ema = { 27 | getDefaultOptions: function () { 28 | return { 29 | period: 14, 30 | index: 0, 31 | approximation: 'average' 32 | }; 33 | }, 34 | getValues: function (chart, series, options, extraPoints) { 35 | var utils = this.utils, 36 | params = options.params, 37 | period = params.period, 38 | xVal = extraPoints[0].concat(series.processedXData || []), // #22 39 | yVal = extraPoints[1].concat(series.processedYData || []), // #22 40 | yValLen = yVal ? yVal.length : 0, 41 | EMApercent = (2 / (period + 1)), 42 | calEMA = 0, 43 | range = 1, 44 | xValue = xVal[0], 45 | yValue = yVal[0], 46 | EMA = [], 47 | xData = [], 48 | yData = [], 49 | index = -1, 50 | i, points, 51 | EMAPoint; 52 | 53 | // check period, if bigger than points length, skip 54 | if (xVal.length <= period) { 55 | return false; 56 | } 57 | 58 | // switch index for OHLC / Candlestick / Arearange 59 | if (isArray(yVal[0])) { 60 | index = params.index ? params.index : 0; 61 | yValue = yVal[0][index]; 62 | } 63 | 64 | // starting point 65 | points = [[xValue, yValue]]; 66 | 67 | // accumulate first N-points 68 | while (range !== period) { 69 | utils.accumulateAverage(points, xVal, yVal, range, index); 70 | range++; 71 | } 72 | 73 | // calculate value one-by-one for each perdio in visible data 74 | for (i = range; i < yValLen; i++) { 75 | EMAPoint = utils.populateAverage(points, xVal, yVal, i, EMApercent, calEMA, index); 76 | EMA.push(EMAPoint); 77 | xData.push(EMAPoint[0]); 78 | yData.push(EMAPoint[1]); 79 | calEMA = EMAPoint[1]; 80 | 81 | utils.accumulateAverage(points, xVal, yVal, i, index); 82 | } 83 | 84 | EMAPoint = utils.populateAverage(points, xVal, yVal, i, EMApercent, calEMA, index); 85 | EMA.push(EMAPoint); 86 | xData.push(EMAPoint[0]); 87 | yData.push(EMAPoint[1]); 88 | 89 | // registger extremes for axis; 90 | options.yAxisMax = maxInArray(EMA); 91 | options.yAxisMin = minInArray(EMA); 92 | 93 | return { 94 | values: EMA, 95 | xData: xData, 96 | yData: yData 97 | }; 98 | }, 99 | getGraph: function (chart, series, options, values) { 100 | var path = [], 101 | attrs = {}, 102 | xAxis = series.xAxis, 103 | yAxis = options.Axis = series.yAxis, 104 | ema = values, 105 | emaLen = ema.length, 106 | emaX, 107 | emaY, 108 | i; 109 | 110 | if (options.visible === false) { 111 | return false; 112 | } 113 | 114 | options.styles = attrs = merge({ 115 | 'stroke-width': 2, 116 | stroke: 'red', 117 | dashstyle: 'Dash' 118 | }, options.styles); 119 | 120 | path.push('M', xAxis.toPixels(ema[0][0]), yAxis.toPixels(ema[0][1])); 121 | 122 | for (i = 0; i < emaLen; i++) { 123 | emaX = ema[i][0]; 124 | emaY = ema[i][1]; 125 | 126 | path.push('L', xAxis.toPixels(emaX), yAxis.toPixels(emaY)); 127 | } 128 | 129 | return [chart.renderer.path(path).attr(attrs)]; 130 | }, 131 | utils: { 132 | accumulateAverage: function (points, xVal, yVal, i, index) { 133 | var xValue = xVal[i], 134 | yValue = index < 0 ? yVal[i] : yVal[i][index]; 135 | 136 | points.push([xValue, yValue]); 137 | }, 138 | populateAverage: function (points, xVal, yVal, i, EMApercent, calEMA, index) { 139 | var x = xVal[i - 1], 140 | yValuePrev = index < 0 ? yVal[i - 2] : yVal[i - 2][index], 141 | yValue = index < 0 ? yVal[i - 1] : yVal[i - 1][index], 142 | prevPoint, y; 143 | 144 | prevPoint = calEMA === 0 ? yValuePrev : calEMA; 145 | y = ((yValue * EMApercent) + (prevPoint * (1 - EMApercent))); 146 | 147 | return [x, y]; 148 | } 149 | } 150 | }; 151 | })); -------------------------------------------------------------------------------- /js/indicators.js: -------------------------------------------------------------------------------- 1 | /* global Highcharts window module:true */ 2 | (function (factory) { 3 | if (typeof module === 'object' && module.exports) { 4 | module.exports = factory; 5 | } else { 6 | factory(Highcharts); 7 | } 8 | }(function (HC) { 9 | 'use strict'; 10 | /** 11 | * Each indicator requires methods: 12 | * 13 | * - getDefaultOptions() - returns object with default parameters, like period etc. 14 | * - getValues(chart, series, options) - returns array of calculated values for indicator 15 | * - getGraph(chart, series, options) - returns path, or columns as SVG elemnts to add. Don't add to chart via renderer! 16 | * 17 | **/ 18 | 19 | /** 20 | indicators: [{ 21 | id: @string, 22 | type: @string, 23 | params: { 24 | period: @number 25 | } 26 | }] 27 | **/ 28 | 29 | var UNDEFINED, 30 | Chart = HC.Chart, 31 | Axis = HC.Axis, 32 | extend = HC.extend, 33 | each = HC.each, 34 | merge = HC.merge, 35 | wrap = HC.wrap, 36 | splat = HC.splat, 37 | isNaN = HC.isNumber, 38 | NUMBER = 'number', 39 | Indicator; 40 | 41 | if (!window) { 42 | window = HC.win; // eslint-disable-line 43 | } 44 | 45 | function error(name) { 46 | if (window.console) { 47 | console.error(name); // eslint-disable-line 48 | } 49 | } 50 | 51 | function defined(obj) { 52 | return obj !== UNDEFINED && obj !== null; 53 | } 54 | 55 | function forceRedraw(s) { 56 | if (s.indicators) { 57 | each(s.indicators, function (el) { 58 | el.isDirtyData = true; 59 | }); 60 | each(s.chart.yAxis, function (el) { 61 | el.render(); 62 | }); 63 | } 64 | } 65 | 66 | // copy od object 67 | function clone(obj) { 68 | if (obj === null || typeof obj !== 'object') { 69 | return obj; 70 | } 71 | 72 | var copy = obj.constructor(); 73 | 74 | for (var attr in obj) { 75 | if (obj.hasOwnProperty(attr)) { 76 | copy[attr] = obj[attr]; 77 | } 78 | } 79 | 80 | return copy; 81 | } 82 | 83 | HC.isArray = HC.isArray || function (obj) { 84 | return Object.prototype.toString.call(obj) === '[object Array]'; 85 | }; 86 | 87 | HC.isObject = HC.isObject || function (obj) { 88 | return typeof obj === 'object'; 89 | }; 90 | 91 | splat = function (obj) { 92 | return HC.isArray(obj) ? obj : [obj]; 93 | }; 94 | 95 | HC.setOptions({ 96 | tooltip: { 97 | followPointer: true 98 | } 99 | }); 100 | 101 | 102 | /** 103 | * 104 | * Wrappers: 105 | * 106 | **/ 107 | 108 | /* 109 | * Update height when chart's height has changed. 110 | */ 111 | wrap(HC.Chart.prototype, 'setSize', function (p, w, h, a) { 112 | p.call(this, w, h, false); 113 | if (this.alignAxes) { 114 | // #30 115 | this.updateHeightAxes(20, false, false); 116 | this.redraw(a); 117 | } 118 | }); 119 | 120 | /* 121 | * Remove corresponding indicators for series, when updating series. 122 | * Updating series means recreating the series. 123 | */ 124 | wrap(HC.Series.prototype, 'update', function (proceed, redraw, animation) { 125 | var tempIndics = [], 126 | s = this, 127 | len, el; 128 | 129 | if (s.indicators) { 130 | len = s.indicators.length; 131 | while (len--) { // #21 132 | el = s.indicators[len]; 133 | tempIndics.push(el.options); 134 | el.destroy(); 135 | } 136 | proceed.call(this, redraw, animation); 137 | s = this; // get series reference back after update 138 | len = tempIndics.length; 139 | while (len--) { // #21 140 | s.chart.addIndicator(tempIndics[len]); 141 | } 142 | } else { 143 | proceed.call(this, redraw, animation); 144 | } 145 | }); 146 | 147 | /* 148 | * Remove connected indicators altogether with a series. 149 | */ 150 | wrap(HC.Series.prototype, 'remove', function (proceed, redraw, animation) { 151 | var s = this, 152 | len; 153 | 154 | if (s.indicators) { 155 | len = s.indicators.length; 156 | while (len--) { // #21 157 | s.indicators[len].destroy(); 158 | } 159 | s.indicators = null; 160 | } 161 | 162 | proceed.call(this, redraw, animation); 163 | }); 164 | 165 | /* 166 | * Force redraw for an indicator when new data arrives. 167 | */ 168 | wrap(HC.Series.prototype, 'setData', function (proceed, redraw, animation) { 169 | forceRedraw(this); 170 | proceed.call(this, redraw, animation); 171 | }); 172 | 173 | /* 174 | * Force redraw for an indicator when new point is added. 175 | */ 176 | wrap(HC.Series.prototype, 'addPoint', function (proceed, options, redraw, shift, animation) { 177 | forceRedraw(this); 178 | proceed.call(this, options, redraw, shift, animation); 179 | }); 180 | 181 | 182 | /* 183 | * Set visibility to true, but disable tooltip when needed. Required for forced recalculation of values. 184 | */ 185 | wrap(HC.Series.prototype, 'setVisible', function (proceed, vis) { 186 | var newVis = vis === UNDEFINED ? (this.isVisible === UNDEFINED ? !this.visible : !this.isVisible) : vis, 187 | showOrHide = newVis ? 'show' : 'hide', 188 | series = this; 189 | 190 | if (series.indicators) { 191 | series.isVisible = newVis; 192 | series.hideInTooltip = !newVis; 193 | proceed.call(series, true, true); 194 | if (series.chart.legend && series.chart.legend.options.enabled) { // #20 195 | series.chart.legend.colorizeItem(this, newVis); 196 | } 197 | 198 | // Show or hide elements 199 | each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { 200 | if (series[key]) { 201 | series[key][showOrHide](); 202 | } 203 | }); 204 | series.legendVisibility = newVis; 205 | series.visible = true; 206 | } else { 207 | delete series.legendVisibility; 208 | proceed.call(series, newVis, true); 209 | } 210 | }); 211 | 212 | /* 213 | * Since Highstock 4.2.0, visibility is used by plotGroup when updating too. 214 | * Set it according to the original state, since series.visible is modified by indicator. 215 | */ 216 | wrap(HC.Series.prototype, 'plotGroup', function (proceed) { 217 | 218 | if (defined(this.legendVisibility)) { 219 | arguments[3] = this.legendVisibility ? 'inherit' : 'hidden'; 220 | } 221 | 222 | return proceed.apply(this, Array.prototype.slice.call(arguments, 1)); 223 | }); 224 | 225 | /* 226 | * Force redraw for an indicator when point is updated. 227 | */ 228 | wrap(HC.Point.prototype, 'update', function (proceed, options, redraw) { 229 | forceRedraw(this.series); 230 | proceed.call(this, options, redraw); 231 | }); 232 | 233 | /* 234 | * Force redraw for indicator when one of points is removed. 235 | */ 236 | wrap(HC.Point.prototype, 'remove', function (proceed, options, redraw, animation) { 237 | forceRedraw(this.series); 238 | proceed.call(this, options, redraw, animation); 239 | }); 240 | 241 | /* 242 | * Set flag for hasData when indicator has own axis. 243 | */ 244 | wrap(HC.Axis.prototype, 'render', function (p) { 245 | var oldHasData; 246 | 247 | function manageIndicators() { 248 | var hasData = false, 249 | indMin = Infinity, 250 | indMax = -Infinity; 251 | each(this.indicators, function (ind) { 252 | if (ind.visible) { 253 | hasData = true; 254 | indMin = Math.min(indMin, ind.options.yAxisMin); 255 | indMax = Math.max(indMax, ind.options.yAxisMax); 256 | } 257 | }); 258 | if (hasData && indMax !== Infinity && indMin !== -Infinity) { 259 | this.isDirty = true; 260 | this.isDirtyExtremes = true; 261 | this.userMax = indMax; 262 | this.userMin = indMin; 263 | } else { 264 | this.userMax = null; 265 | this.userMin = null; 266 | } 267 | return hasData; 268 | } 269 | 270 | if (this.indicators && !this.hasVisibleSeries) { 271 | // Case 1: axis doesn't have series 272 | oldHasData = manageIndicators.call(this); 273 | this.hasData = typeof this.hasData === 'function' ? function () { return oldHasData; } : oldHasData; // version 4.1.6 vs 4.1.7 274 | 275 | if ((typeof this.hasData === 'function' && this.hasData()) || (typeof this.hasData !== 'function' && this.hasData)) { // version 4.1.6 vs 4.1.7 276 | this.setScale(); 277 | this.setTickPositions(true); 278 | 279 | this.chart.getMargins(); // #38 280 | each(this.indicators, function (ind) { 281 | ind.drawGraph(); 282 | }); 283 | } 284 | } else if (this.indicators) { 285 | // Case 2: right now all series are 'visible', so we need to check param: isVisible 286 | var hasData = false; 287 | 288 | each(this.series, function (serie) { 289 | if (serie.isVisible || (serie.isVisible === UNDEFINED && serie.visible)) { 290 | hasData = true; 291 | } 292 | }); 293 | 294 | if (!hasData) { 295 | hasData = manageIndicators.call(this); 296 | } else { 297 | this.userMax = null; 298 | this.userMin = null; 299 | } 300 | if (hasData) { 301 | this.setScale(); 302 | this.setTickPositions(true); 303 | this.chart.getMargins(); 304 | } 305 | this.hasData = typeof this.hasData === 'function' ? function () { return hasData; } : hasData; // version 4.1.6 vs 4.1.7 306 | 307 | each(this.indicators, function (ind) { 308 | ind.drawGraph(); 309 | }); 310 | } 311 | p.call(this); 312 | }); 313 | 314 | 315 | /* 316 | * Tooltip formatter content. 317 | */ 318 | wrap(HC.Tooltip.prototype, 'defaultFormatter', function (proceed, tooltip) { 319 | var items = this.points || splat(this), 320 | tooltipOptions = items[0].series.chart.tooltip.options, 321 | indicatorTooltip = '', 322 | indicators, 323 | ind, 324 | s; 325 | 326 | // build the header 327 | s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; // #3397: abstraction to enable formatting of footer and header 328 | 329 | // build the values 330 | s = s.concat(tooltip.bodyFormatter(items)); 331 | 332 | // add indicator info 333 | each(items, function (item) { 334 | 335 | indicators = item.indicators; 336 | 337 | if (indicators === UNDEFINED || !tooltipOptions.enabledIndicators) { 338 | return; 339 | } 340 | 341 | for (var type in indicators) { 342 | 343 | ind = indicators[type]; 344 | 345 | if (ind.values !== UNDEFINED && ind.visible !== false && ((ind.options && ind.options.params) && ind.options.params.allowTooltip !== false)) { 346 | 347 | // multiple lines 348 | each(ind.values, function (val, k) { 349 | if (isNaN(val.y)) { // #31 350 | indicatorTooltip += '' + splat(ind.options.names || ind.name)[k] + ': ' + HC.numberFormat(val.y, 3) + '
'; 351 | } 352 | }); 353 | } 354 | } 355 | }); 356 | 357 | s.push(indicatorTooltip); 358 | 359 | // footer 360 | s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); // #3397: abstraction to enable formatting of footer and header 361 | 362 | return s.join(''); 363 | }); 364 | 365 | /** 366 | * Add legend items: 367 | **/ 368 | 369 | /* 370 | * Add indicators to legend. 371 | */ 372 | wrap(HC.Legend.prototype, 'getAllItems', function (p) { 373 | var allItems = p.call(this), 374 | indicators = this.chart.indicators; 375 | if (indicators) { 376 | each(indicators.allItems, function (e) { 377 | if (e.options.showInLegend) { 378 | allItems.push(e); 379 | } 380 | }); 381 | } 382 | return allItems; 383 | }); 384 | 385 | /* 386 | * Render indicator in legend. 387 | */ 388 | wrap(HC.Legend.prototype, 'renderItem', function (p, item) { 389 | if (item instanceof Indicator) { 390 | var series = item.series; 391 | item.series = null; 392 | item.color = item.options.styles.stroke; 393 | p.call(this, item); 394 | item.series = series; 395 | } else { 396 | p.call(this, item); 397 | } 398 | }); 399 | 400 | wrap(HC.Point.prototype, 'getLabelConfig', function () { 401 | var p = this; 402 | 403 | return { 404 | x: p.category, 405 | y: p.y, 406 | indicators: p.indicators, 407 | key: p.name || p.category, 408 | series: p.series, 409 | point: p, 410 | percentage: p.percentage, 411 | total: p.total || p.stackTotal 412 | }; 413 | }); 414 | 415 | wrap(HC.Point.prototype, 'init', function (proceed, series, options, x) { 416 | var point = this, 417 | colors; 418 | 419 | point.series = series; 420 | point.color = series.color; // #3445 421 | point.applyOptions(options, x); 422 | point.pointAttr = {}; 423 | point.indicators = {}; 424 | 425 | if (series.options.colorByPoint) { 426 | colors = series.options.colors || series.chart.options.colors; 427 | point.color = point.color || colors[series.colorCounter++]; 428 | // loop back to zero 429 | if (series.colorCounter === colors.length) { 430 | series.colorCounter = 0; 431 | } 432 | } 433 | 434 | series.chart.pointCount++; 435 | return point; 436 | }); 437 | 438 | /* 439 | * When hovering legend item, use isVisible instead of visible property 440 | */ 441 | wrap(HC.Legend.prototype, 'setItemEvents', function (p, item, legendItem, useHTML, itemStyle, itemHiddenStyle) { 442 | p.call(this, item, legendItem, useHTML, itemStyle, itemHiddenStyle); 443 | (useHTML ? legendItem : item.legendGroup).on('mouseout', function () { 444 | var style = item.isVisible === UNDEFINED ? (item.visible ? itemStyle : itemHiddenStyle) : (item.isVisible ? itemStyle : itemHiddenStyle); 445 | legendItem.css(style); 446 | item.setState(); 447 | }); 448 | }); 449 | 450 | /** 451 | * Indicator Class: 452 | **/ 453 | 454 | HC.Indicator = Indicator = function () { 455 | this.init.apply(this, arguments); 456 | }; 457 | 458 | Indicator.prototype = { 459 | /* 460 | * Initialize the indicator 461 | */ 462 | init: function (chart, options) { 463 | // set default params, when not specified in params 464 | if (!Indicator.prototype[options.type]) { 465 | error('Indicator: ' + options.type + ' not found!'); 466 | } 467 | options.params = merge({}, Indicator.prototype[options.type].getDefaultOptions(), options.params); 468 | 469 | this.chart = chart; 470 | this.options = options; 471 | this.series = chart.get(options.id); 472 | this.name = options.name === UNDEFINED ? options.type : options.name; 473 | this.visible = options.visible === UNDEFINED ? true : options.visible; 474 | this.tooltipKey = this.name + '_' + +new Date(); // #49 475 | 476 | if (!this.series.indicators) { 477 | this.series.indicators = []; 478 | } 479 | this.series.indicators.push(this); 480 | }, 481 | 482 | /* 483 | * Render the indicator 484 | */ 485 | render: function () { 486 | var indicator = this, 487 | chart = this.chart, 488 | renderer = chart.renderer, 489 | graph = this.graph, 490 | group = this.group, 491 | options = this.options, 492 | series = this.series, 493 | optionsAxis, 494 | arrayValues, 495 | len, i; 496 | 497 | if (!indicator.visible) { 498 | return; 499 | } 500 | 501 | if (!group) { 502 | indicator.group = group = renderer.g().add(chart.indicators.group); 503 | } 504 | 505 | if (!series) { 506 | error('Series not found'); 507 | return; 508 | } else if (!graph) { 509 | arrayValues = Indicator.prototype[options.type].getValues(chart, { points: [] }, options, [series.xData, series.yData]); 510 | 511 | if (!arrayValues) { // #6 - create dummy data 512 | arrayValues = { 513 | values: [[]], 514 | xData: [[]], 515 | yData: [[]] 516 | }; 517 | } 518 | this.values = this.currentPoints = arrayValues.values; 519 | this.xData = arrayValues.xData; 520 | this.yData = arrayValues.yData; 521 | this.groupPoints(series); 522 | 523 | this.graph = graph = Indicator.prototype[options.type].getGraph(chart, series, options, this.values); 524 | 525 | if (graph) { 526 | len = graph.length; 527 | for (i = 0; i < len; i++) { 528 | graph[i].add(group); 529 | } 530 | } 531 | // indicator has connection to the specific Axis, like RSI or ATR 532 | optionsAxis = indicator.options.Axis; 533 | 534 | if (optionsAxis) { 535 | optionsAxis.indicators = optionsAxis.indicators || []; 536 | optionsAxis.indicators.push(indicator); 537 | if (indicator.clipPath) { 538 | indicator.clipPath.destroy(); 539 | } 540 | indicator.clipPath = renderer.clipRect({ 541 | x: optionsAxis.left, 542 | y: optionsAxis.top, 543 | width: optionsAxis.width, 544 | height: optionsAxis.height 545 | }); 546 | group.clip(indicator.clipPath); 547 | } 548 | } 549 | if (chart.legend && chart.legend.options.enabled) { 550 | chart.legend.render(); 551 | } 552 | }, 553 | 554 | /* 555 | * Redraw the indicator 556 | */ 557 | redraw: function () { 558 | var options = this.options, 559 | chart = this.chart, 560 | series = this.series, 561 | isDirtyData = this.isDirtyData, 562 | arrayValues; 563 | 564 | if (!this.visible) { 565 | // Remove extremes 566 | options.yAxisMax = null; 567 | options.yAxisMin = null; 568 | this.values = [[]]; 569 | return; 570 | } 571 | // Only after series.setData() or series.addPoint() etc. 572 | if (isDirtyData) { 573 | arrayValues = Indicator.prototype[options.type].getValues(chart, { points: [] }, options, [series.xData, series.yData]); 574 | if (!arrayValues) { // #6 - create dummy data 575 | arrayValues = { 576 | values: [[]], 577 | xData: [[]], 578 | yData: [[]] 579 | }; 580 | } 581 | this.values = this.currentPoints = arrayValues.values; 582 | this.xData = arrayValues.xData; 583 | this.yData = arrayValues.yData; 584 | } 585 | // Always check if points should be grouped, like after setExtremes() which doesn't change data 586 | this.groupPoints(series); 587 | }, 588 | 589 | /* 590 | * Draw graph 591 | */ 592 | drawGraph: function () { 593 | var ind = this, 594 | graph = this.graph, 595 | len = graph.length, 596 | i; 597 | 598 | if (graph) { 599 | for (i = 0; i < len; i++) { 600 | graph[i].destroy(); 601 | } 602 | } 603 | ind.graph = Indicator.prototype[ind.options.type].getGraph(ind.chart, ind.series, ind.options, ind.values); 604 | 605 | if (ind.graph) { 606 | ind.clipPath.attr({ 607 | x: ind.options.Axis.left, 608 | y: ind.options.Axis.top, 609 | width: ind.options.Axis.width, 610 | height: ind.options.Axis.height 611 | }); 612 | len = ind.graph.length; 613 | for (i = 0; i < len; i++) { 614 | ind.graph[i].add(ind.group); 615 | } 616 | } 617 | }, 618 | 619 | /* 620 | * Group points to allow calculation before extremes 621 | */ 622 | groupPoints: function (series) { 623 | var start = series.cropStart, 624 | end, 625 | length = splat(this.options.params.period)[0], // #23 - don't use cropShoulded - it's broken since v1.3.6 626 | groupedPoints = [], 627 | currentData = [], 628 | xAxis = series.xAxis, 629 | ex = xAxis.getExtremes(), 630 | xMin = ex.min, 631 | xMax = ex.max, 632 | yData, groupPositions, 633 | processedXData, 634 | minLen = this.getCropStart(ex.min, this.xData); 635 | 636 | if (series.currentDataGrouping && this.options.params.allowGrouping !== false) { 637 | processedXData = series.processedXData.slice(); 638 | end = this.getCropEnd(start, xMax, this.xData); 639 | groupPositions = series.xAxis.getTimeTicks( 640 | series.currentDataGrouping, 641 | xMin, 642 | xMax, 643 | xAxis.options.startOfWeek, 644 | processedXData, 645 | series.closestPointRange 646 | ); 647 | groupedPoints = this.groupData(this.xData.slice(Math.max(0, start - length), end), this.yData.slice(Math.max(0, start - length), end), groupPositions.slice(), this.options.params.approximation); 648 | this.processedXData = groupedPoints[0]; 649 | this.processedYData = yData = groupedPoints[1]; 650 | } else { 651 | this.processedXData = this.xData.slice(minLen); // Copy default data 652 | this.processedYData = yData = this.yData.slice(minLen); 653 | } 654 | 655 | // Merge current points 656 | each(this.processedXData, function (p, i) { 657 | if (HC.isArray(yData[i])) { 658 | currentData.push([p].concat(yData[i])); 659 | } else { 660 | currentData.push([p, yData[i]]); 661 | } 662 | }); 663 | this.options.yAxisMin = Math.min.apply(null, Array.prototype.concat.apply([], this.processedYData)); // new extremes 664 | this.options.yAxisMax = Math.max.apply(null, Array.prototype.concat.apply([], this.processedYData)); // new extremes 665 | this.values = currentData; 666 | this.applyTooltipPoints(); 667 | 668 | }, 669 | /* 670 | * Mechanism for grouping points into grouped positions 671 | */ 672 | groupData: function (xData, yData, groupPositions, approximation) { 673 | 674 | var groupedXData = [], 675 | groupedYData = [], 676 | groupedY, 677 | dataLength = xData.length, 678 | pointY, 679 | pointX, 680 | values = [[], [], [], [], []], 681 | approximationFn = typeof approximation === 'function' ? approximation : HC.approximations[approximation], 682 | i; 683 | 684 | // Start with the first point within the X axis range (#2696) 685 | for (i = 0; i <= dataLength; i++) { 686 | if (xData[i] >= groupPositions[0]) { 687 | break; 688 | } 689 | } 690 | 691 | for (; i <= dataLength; i++) { 692 | // when a new group is entered, summarize and initiate the previous group 693 | while ((groupPositions[1] !== UNDEFINED && xData[i] >= groupPositions[1]) || 694 | i === dataLength) { // get the last group 695 | 696 | // get group x and y 697 | pointX = groupPositions.shift(); 698 | groupedY = approximationFn.apply(0, values); 699 | 700 | // push the grouped data 701 | if (groupedY !== UNDEFINED) { 702 | groupedXData.push(pointX); 703 | groupedYData.push(groupedY); 704 | } 705 | 706 | // reset the aggregate arrays 707 | values[0] = []; 708 | values[1] = []; 709 | values[2] = []; 710 | values[3] = []; 711 | values[4] = []; 712 | 713 | // don't loop beyond the last group 714 | if (i === dataLength) { 715 | break; 716 | } 717 | } 718 | 719 | // break out 720 | if (i === dataLength) { 721 | break; 722 | } 723 | 724 | pointY = yData[i]; 725 | 726 | if (pointY === null) { 727 | values[0].hasNulls = true; 728 | } else if (typeof pointY === NUMBER) { 729 | values[0].push(pointY); 730 | } else { 731 | each(pointY, function (e, j) { 732 | values[j].push(e); 733 | }); 734 | } 735 | } 736 | 737 | return [groupedXData, groupedYData]; 738 | }, 739 | 740 | /* 741 | * Apply indicator's value to the grouped, corresponding points 742 | */ 743 | applyTooltipPoints: function () { 744 | var indicator = this, 745 | params = indicator.options.params, 746 | allowTooltip = params && params.tooltip, 747 | series = this.series, 748 | cropStart = series.cropStart, 749 | type = this.tooltipKey, // #49 750 | values = indicator.values, 751 | points = indicator.series.points, 752 | pLen = points ? points.length : 0, 753 | index = series.processedXData.indexOf(indicator.processedXData[0]), 754 | diff = index === -1 ? (indicator.options.params && indicator.options.params.period) || 0 : index, 755 | i = cropStart === 0 ? diff : 0, 756 | currentIndex, 757 | indValues, 758 | graphLen, 759 | point, 760 | k; 761 | 762 | if (allowTooltip === false) { 763 | return false; 764 | } 765 | 766 | for (i; i < pLen; i++) { 767 | 768 | currentIndex = cropStart === 0 ? i - diff : i + (index < 0 ? 1 : 0); // #55 769 | 770 | point = points && points[i]; // #50 771 | indValues = values && values[currentIndex]; 772 | 773 | if (point && indValues) { 774 | point.indicators[type] = clone(indicator); 775 | point.indicators[type].x = indValues[0]; // x value 776 | point.indicators[type].values = []; 777 | 778 | graphLen = indValues.length - 1; 779 | 780 | for (k = 0; k < graphLen; k++) { 781 | 782 | point.indicators[type].values.push({ 783 | y: indValues[k + 1], 784 | color: indicator.graph && indicator.graph[k].stroke 785 | }); 786 | 787 | } 788 | } 789 | } 790 | return true; 791 | }, 792 | 793 | /* 794 | * Get right edge of the data actually displayed on the chart. cropStart is stored, but cropEnd we need to find 795 | */ 796 | 797 | getCropEnd: function (start, max, data) { 798 | var len = data.length, 799 | i = start; 800 | while (i < len) { 801 | if (data[i] >= max) { 802 | break; 803 | } 804 | i++; 805 | } 806 | return i + 1; 807 | }, 808 | 809 | getCropStart: function (min, data) { 810 | var len = data.length, 811 | i = 0; 812 | 813 | while (i < len) { 814 | if (data[i] >= min) { 815 | break; 816 | } 817 | i++; 818 | } 819 | return Math.max(0, i - 1); 820 | }, 821 | /* 822 | * Destroy the indicator 823 | */ 824 | destroy: function (redraw) { 825 | var indicator = this, 826 | chart = this.chart, 827 | allItems = chart.indicators.allItems, 828 | index = allItems.indexOf(indicator), 829 | axis = this.options.Axis; 830 | 831 | // remove from all indicators array 832 | if (index > -1) { 833 | allItems.splice(index, 1); 834 | } 835 | // remove from series.indicators 836 | index = indicator.series.indicators.indexOf(indicator); 837 | if (index > -1) { 838 | indicator.series.indicators.splice(index, 1); 839 | } 840 | 841 | // remove from yAxis.indicators 842 | index = axis.indicators.indexOf(indicator); 843 | if (index > -1) { 844 | axis.indicators.splice(index, 1); 845 | } 846 | 847 | if (indicator.legendGroup) { 848 | indicator.legendGroup.destroy(); 849 | if (chart.legend && chart.legend.options.enabled) { 850 | chart.legend.render(); 851 | } 852 | } 853 | 854 | // Remove axis if that was the last one indicator 855 | if (axis && axis.series.length === 0 && axis.indicators && axis.indicators.length === 0) { 856 | axis.remove(); 857 | this.options.Axis = UNDEFINED; 858 | chart.indicators.haveAxes --; // #18: decrement number of axes to be updated 859 | if (chart.alignAxes) { 860 | chart.updateHeightAxes(20, false, true); 861 | } 862 | } 863 | 864 | // Remove group with graph 865 | if (indicator.group) { 866 | indicator.group.destroy(); 867 | indicator.group = null; 868 | } 869 | 870 | // Remove points from tooltip #29 871 | each(indicator.series.points, function (p) { 872 | if (p && p.indicators && p.indicators[indicator.tooltipKey]) { 873 | delete p.indicators[indicator.tooltipKey]; 874 | } 875 | }); 876 | indicator = null; 877 | chart.redraw(redraw); 878 | }, 879 | 880 | /* 881 | * setState for indicator? 882 | */ 883 | setState: function () { 884 | return this; 885 | }, 886 | 887 | /* 888 | * Hide or show indicator 889 | */ 890 | setVisible: function (vis) { 891 | var indicator = this, 892 | oldVis = indicator.visible, 893 | legend = indicator.chart.legend, 894 | newVis, 895 | method; 896 | 897 | if (vis === UNDEFINED) { 898 | newVis = oldVis ? false : true; 899 | method = oldVis ? 'hide' : 'show'; 900 | } else { 901 | newVis = vis; 902 | method = vis ? 'show' : 'hide'; 903 | } 904 | 905 | if (legend.options.enabled && this.options.showInLegend) { 906 | legend.colorizeItem(this, newVis); 907 | } 908 | this.visible = newVis; 909 | 910 | indicator[method](); 911 | indicator.redraw(); 912 | 913 | // hide axis by resetting extremes 914 | if (this.options.Axis) { 915 | this.options.Axis.render(); 916 | } 917 | }, 918 | 919 | /* 920 | * Draw symbol in legend - should be simple line 921 | */ 922 | drawLegendSymbol: function (legend) { 923 | var options = this.options, 924 | legendOptions = legend.options, 925 | symbolWidth = legend.symbolWidth, 926 | renderer = this.chart.renderer, 927 | legendItemGroup = this.legendGroup, 928 | verticalCenter = legend.baseline - Math.round(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3), 929 | attr; 930 | 931 | // Draw the line 932 | attr = { 933 | 'stroke-width': options.lineWidth || 2 934 | }; 935 | if (options.styles && options.styles.dashstyle) { 936 | attr.dashstyle = options.styles.dashstyle; 937 | } 938 | this.legendLine = renderer.path([ 939 | 'M', 940 | 0, 941 | verticalCenter, 942 | 'L', 943 | symbolWidth, 944 | verticalCenter 945 | ]) 946 | .attr(attr) 947 | .add(legendItemGroup); 948 | }, 949 | 950 | /* 951 | * Update the indicator with a given options 952 | */ 953 | update: function (options, redraw) { 954 | merge(true, this.options, options); 955 | 956 | this.redraw(redraw); 957 | this.options.Axis.render(); 958 | }, 959 | 960 | /* 961 | * Hide the indicator 962 | */ 963 | hide: function () { 964 | this.group.hide(); 965 | this.visible = false; 966 | }, 967 | 968 | /* 969 | * Show the indicator 970 | */ 971 | show: function () { 972 | this.group.show(); 973 | this.visible = true; 974 | } 975 | }; 976 | 977 | 978 | // Add indicator methods to chart prototype 979 | extend(Chart.prototype, { 980 | /* 981 | * Adding indicator to the chart 982 | */ 983 | addIndicator: function (options, redraw) { 984 | var chart = this, 985 | indicators = chart.indicators.allItems, 986 | item; 987 | 988 | item = new Indicator(chart, options); 989 | indicators.push(item); 990 | item.render(redraw); 991 | chart.redraw(redraw); 992 | return item; 993 | }, 994 | /* 995 | * Redraw all indicators, method used in chart events 996 | */ 997 | redrawIndicators: function () { 998 | var chart = this; 999 | 1000 | each(chart.indicators.allItems, function (indicator) { 1001 | indicator.redraw(); 1002 | }); 1003 | // we need two loops - one to calculate values and register extremes 1004 | // and second to draw paths with proper extremes on yAxis 1005 | each(chart.yAxis, function (axis) { 1006 | axis.render(); 1007 | }); 1008 | }, 1009 | /* 1010 | * Updates axes and returns new and normalized height for each of them. 1011 | */ 1012 | updateHeightAxes: function (topDiff, add, afterRemove) { 1013 | var chart = this, 1014 | chYxis = chart.yAxis, 1015 | len = chYxis.length, 1016 | calcLen = len, 1017 | i = 0, 1018 | sum = chart.chartHeight - chart.plotTop - chart.marginBottom, // Workaround until chart.plotHeight will return real value 1019 | indexWithoutNav = 0, 1020 | currentIndicators, 1021 | newHeight, 1022 | top; 1023 | 1024 | // #18 - don't update axes when none of indicators have separate axis 1025 | if (afterRemove !== true && (!chart.indicators || chart.indicators.haveAxes === 0 || chart.indicators.allItems.length === 0)) { 1026 | return UNDEFINED; 1027 | } 1028 | 1029 | // When we want to remove axis, e.g. after indicator remove 1030 | // #17 - we need to consider navigator (disabled vs enabled) when calculating height in advance 1031 | if (!add && chart.options.navigator.enabled) { 1032 | calcLen--; 1033 | } else if (add && !chart.options.navigator.enabled) { 1034 | calcLen++; 1035 | } 1036 | 1037 | newHeight = (sum - (calcLen - 1) * topDiff) / calcLen; 1038 | // Update all axis 1039 | for (;i < len; i++) { 1040 | var yAxis = chYxis[i]; 1041 | 1042 | if (yAxis.options.id !== 'navigator-y-axis') { 1043 | top = chart.plotTop + indexWithoutNav * (topDiff + newHeight); 1044 | 1045 | if (yAxis.top !== top || yAxis.height !== newHeight) { 1046 | currentIndicators = chYxis[i].indicators; 1047 | chYxis[i].update({ 1048 | top: top, 1049 | height: newHeight 1050 | }, false); 1051 | chYxis[i].indicators = currentIndicators; 1052 | } 1053 | indexWithoutNav++; 1054 | } 1055 | } 1056 | return newHeight; 1057 | } 1058 | }); 1059 | 1060 | // Add yAxis as pane 1061 | extend(Axis.prototype, { 1062 | /* 1063 | * When new indicator is added, sometimes we need new pane. 1064 | * Note: It automatically scales all of other axes unless alignAxes is set to false. 1065 | */ 1066 | addAxisPane: function (chart, userOptions) { 1067 | chart.indicators.haveAxes++; // #18: increment number of axes 1068 | 1069 | var topDiff = 20, 1070 | height, 1071 | yLen = chart.options.navigator.enabled ? chart.yAxis.length - 1 : chart.yAxis.length, // #17 - don't count navigator 1072 | defaultOptions, 1073 | options; 1074 | 1075 | if (chart.alignAxes) { 1076 | height = chart.updateHeightAxes(topDiff, true); 1077 | defaultOptions = { 1078 | labels: { 1079 | align: 'left', 1080 | x: 2, 1081 | y: -2 1082 | }, 1083 | offset: chart.alignAxes ? 0 : null, 1084 | height: height, 1085 | top: chart.plotTop + yLen * (topDiff + height), 1086 | min: 0, 1087 | max: 100 1088 | }; 1089 | } else { 1090 | defaultOptions = { 1091 | min: 0, 1092 | max: 100 1093 | }; 1094 | } 1095 | 1096 | options = merge(defaultOptions, userOptions); 1097 | 1098 | // Add new axis 1099 | chart.preventIndicators = true; 1100 | chart.addAxis(options, false, true, false); 1101 | chart.preventIndicators = false; 1102 | return chart.yAxis.length - 1; 1103 | }, 1104 | minInArray: function (arr) { 1105 | return arr.reduce(function (min, res) { 1106 | return Math.min(min, res[1]); 1107 | }, Infinity); 1108 | }, 1109 | maxInArray: function (arr) { 1110 | return arr.reduce(function (max, res) { 1111 | return Math.max(max, res[1]); 1112 | }, -Infinity); 1113 | } 1114 | }); 1115 | 1116 | // Initialize on chart load 1117 | Chart.prototype.callbacks.push(function (chart) { 1118 | var options = chart.options.indicators, 1119 | optionsLen = options ? options.length : 0, 1120 | i = 0, 1121 | group, 1122 | exportingFlag = true; 1123 | 1124 | group = chart.renderer.g('indicators'); 1125 | group.attr({ 1126 | zIndex: 2 1127 | }); 1128 | group.add(); 1129 | 1130 | if (!chart.indicators) { 1131 | chart.indicators = {}; 1132 | } 1133 | 1134 | // initialize empty array for indicators 1135 | if (!chart.indicators.allItems) { 1136 | chart.indicators.allItems = []; 1137 | } 1138 | 1139 | // link chart object to indicators 1140 | chart.indicators.chart = chart; 1141 | 1142 | // link indicators group element to the chart 1143 | chart.indicators.group = group; 1144 | 1145 | // counter for axes #18 1146 | chart.indicators.haveAxes = 0; 1147 | chart.alignAxes = defined(chart.options.chart.alignAxes) ? chart.options.chart.alignAxes : true; 1148 | 1149 | for (i = 0; i < optionsLen; i++) { 1150 | chart.addIndicator(options[i], false); 1151 | if ((chart.get(options[i].id).points.length - 1) <= options[i].params.period) { // SPLAT? 1152 | exportingFlag = false; 1153 | } 1154 | } 1155 | 1156 | // update indicators after chart redraw 1157 | HC.addEvent(chart, 'redraw', function () { 1158 | if (!chart.preventIndicators) { 1159 | chart.redrawIndicators(); 1160 | } 1161 | chart.preventIndicators = false; 1162 | }); 1163 | 1164 | if (exportingFlag && optionsLen > 0 && chart.series && chart.series.length > 0) { // #16 & #27 1165 | chart.isDirtyLegend = true; 1166 | chart.series[0].isDirty = true; 1167 | chart.series[0].isDirtyData = true; 1168 | chart.redraw(false); 1169 | } 1170 | }); 1171 | 1172 | HC.approximations = { 1173 | sum: function (arr) { 1174 | var len = arr.length, 1175 | ret; 1176 | 1177 | // 1. it consists of nulls exclusively 1178 | if (!len && arr.hasNulls) { 1179 | ret = null; 1180 | // 2. it has a length and real values 1181 | } else if (len) { 1182 | ret = 0; 1183 | while (len--) { 1184 | ret += arr[len]; 1185 | } 1186 | } 1187 | // 3. it has zero length, so just return undefined 1188 | // => doNothing() 1189 | 1190 | return ret; 1191 | }, 1192 | average: function (arr) { 1193 | var len = arr.length, 1194 | ret = HC.approximations.sum(arr); 1195 | 1196 | // If we have a number, return it divided by the length. If not, return 1197 | // null or undefined based on what the sum method finds. 1198 | if (typeof ret === NUMBER && len) { 1199 | ret = ret / len; 1200 | } 1201 | 1202 | return ret; 1203 | }, 1204 | open: function (arr) { 1205 | return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED); 1206 | }, 1207 | high: function (arr) { 1208 | return arr.length ? HC.arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED); 1209 | }, 1210 | low: function (arr) { 1211 | return arr.length ? HC.arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED); 1212 | }, 1213 | close: function (arr) { 1214 | return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED); 1215 | }, 1216 | // ohlc and range are special cases where a multidimensional array is input and an array is output 1217 | ohlc: function (open, high, low, close) { 1218 | open = HC.approximations.open(open); 1219 | high = HC.approximations.high(high); 1220 | low = HC.approximations.low(low); 1221 | close = HC.approximations.close(close); 1222 | 1223 | if (typeof open === NUMBER || typeof high === NUMBER || typeof low === NUMBER || typeof close === NUMBER) { 1224 | return [open, high, low, close]; 1225 | } 1226 | return UNDEFINED; 1227 | }, 1228 | range: function (low, high) { 1229 | low = HC.approximations.low(low); 1230 | high = HC.approximations.high(high); 1231 | 1232 | if (typeof low === NUMBER || typeof high === NUMBER) { 1233 | return [low, high]; 1234 | } 1235 | return UNDEFINED; 1236 | } 1237 | }; 1238 | })); -------------------------------------------------------------------------------- /js/rsi.js: -------------------------------------------------------------------------------- 1 | /* global Highcharts module:true */ 2 | (function (factory) { 3 | if (typeof module === 'object' && module.exports) { 4 | module.exports = factory; 5 | } else { 6 | factory(Highcharts); 7 | } 8 | }(function (HC) { 9 | 'use strict'; 10 | /** 11 | 12 | Each indicator requires mothods: 13 | 14 | - getDefaultOptions() - returns object with default parameters, like period etc. 15 | - getValues(chart, series, options, points) - returns array of calculated values for indicator 16 | - getGraph(chart, series, options, values) - returns path, or columns as SVG elements to add. 17 | Doesn't add to the chart via renderer! 18 | 19 | **/ 20 | 21 | function toFixed(a, n) { 22 | return parseFloat(a.toFixed(n)); 23 | } 24 | 25 | var UNDEFINED, 26 | each = HC.each, 27 | merge = HC.merge, 28 | isArray = HC.isArray, 29 | addAxisPane = HC.Axis.prototype.addAxisPane; 30 | 31 | HC.Indicator.prototype.rsi = { 32 | getDefaultOptions: function () { 33 | return { 34 | period: 14, 35 | overbought: 70, 36 | oversold: 30, 37 | approximation: 'average', 38 | decimals: 4 39 | }; 40 | }, 41 | getValues: function (chart, series, options, points) { 42 | var utils = this.utils, 43 | params = options.params, 44 | period = params.period, 45 | xVal = points[0].concat(series.processedXData || []), // #22 46 | yVal = points[1].concat(series.processedYData || []), // #22 47 | yValLen = yVal ? yVal.length : 0, 48 | //EMA = HC.Indicator.prototype.ema, 49 | decimals = params.decimals, 50 | // EMApercent = (2 / (period + 1)), 51 | // calEMAGain = 0, 52 | // calEMALoss = 0, 53 | range = 1, 54 | RSI = [], 55 | xData = [], 56 | yData = [], 57 | index = 3, 58 | gain = [], 59 | loss = [], 60 | RSIPoint, change, RS, avgGain, avgLoss, i; 61 | 62 | // atr requires close value 63 | if ((xVal.length <= period) || !isArray(yVal[0]) || yVal[0].length !== 4 /*|| EMA === UNDEFINED*/) { 64 | return false; 65 | } 66 | 67 | // accumulate first N-points 68 | while (range < period + 1) { 69 | change = toFixed(yVal[range][index] - yVal[range - 1][index], decimals); 70 | gain.push(change > 0 ? change : 0); 71 | loss.push(change < 0 ? Math.abs(change) : 0); 72 | range++; 73 | } 74 | 75 | for (i = range - 1; i < yValLen; i++) { 76 | // gain.push(change > 0 ? change : 0); 77 | // len = loss.push(change < 0 ? Math.abs(change) : 0); // better than loss.length 78 | 79 | // EMA for loss and gains 80 | // avgGain = EMA.utils.populateAverage([], gain, [ yVal[i-1], [utils.sumArray(gain) / len] ], 2, EMApercent, calEMAGain, 0); 81 | // avgLoss = EMA.utils.populateAverage([], gain, [ yVal[i-1], [utils.sumArray(loss) / len] ], 2, EMApercent, calEMALoss, 0); 82 | if (i > range - 1) { 83 | // remove first point from array 84 | gain.shift(); 85 | loss.shift(); 86 | // calculate new change 87 | change = toFixed(yVal[i][index] - yVal[i - 1][index], decimals); 88 | // add to array 89 | gain.push(change > 0 ? change : 0); 90 | loss.push(change < 0 ? Math.abs(change) : 0); 91 | } 92 | 93 | // calculate averages, RS, RSI values: 94 | avgGain = toFixed(utils.sumArray(gain) / period, decimals); 95 | avgLoss = toFixed(utils.sumArray(loss) / period, decimals); 96 | 97 | if (avgLoss === 0) { 98 | RS = 100; 99 | } else { 100 | RS = toFixed(avgGain / avgLoss, decimals); 101 | } 102 | RSIPoint = toFixed(100 - (100 / (1 + RS)), decimals); 103 | RSI.push([xVal[i], RSIPoint]); 104 | xData.push(xVal[i]); 105 | yData.push(RSIPoint); 106 | 107 | // calEMAGain = avgGain[1]; 108 | // calEMALoss = avgLoss[1]; 109 | } 110 | 111 | options.yAxisMax = 100; 112 | options.yAxisMin = 0; 113 | 114 | return { 115 | values: RSI, 116 | xData: xData, 117 | yData: yData 118 | }; 119 | }, 120 | getGraph: function (chart, series, options, values) { 121 | var path = [], 122 | attrs = {}, 123 | xAxis = series.xAxis, 124 | atr = values, 125 | atrLen = atr.length, 126 | defaultOptions, 127 | userOptions, 128 | yAxis, 129 | index, 130 | atrX, 131 | atrY, 132 | i; 133 | 134 | defaultOptions = { 135 | min: 0, 136 | tickInterval: 25, 137 | plotLines: [{ 138 | value: options.params.overbought, 139 | color: 'orange', 140 | width: 1 141 | }, { 142 | value: options.params.oversold, 143 | color: 'orange', 144 | width: 1 145 | }], 146 | // height: 100, 147 | max: 100, 148 | title: { 149 | text: 'RSI' 150 | } 151 | }; 152 | 153 | if (options.visible === false) { 154 | return false; 155 | } 156 | 157 | userOptions = merge(defaultOptions, options.yAxis); 158 | 159 | if (options.Axis === UNDEFINED) { 160 | index = addAxisPane(chart, userOptions); 161 | options.Axis = chart.yAxis[index]; 162 | } else { 163 | each(options.Axis.plotLinesAndBands, function (p, j) { 164 | p.options = merge(p.options, userOptions.plotLines[j]); 165 | p.render(); 166 | }); 167 | } 168 | 169 | yAxis = options.Axis; 170 | 171 | options.styles = attrs = merge({ 172 | 'stroke-width': 2, 173 | stroke: 'red', 174 | dashstyle: 'Dash' 175 | }, options.styles); 176 | 177 | path.push('M', xAxis.toPixels(atr[0][0]), yAxis.toPixels(atr[0][1])); 178 | for (i = 0; i < atrLen; i++) { 179 | atrX = atr[i][0]; 180 | atrY = atr[i][1]; 181 | path.push('L', xAxis.toPixels(atrX), yAxis.toPixels(atrY)); 182 | } 183 | 184 | return [chart.renderer.path(path).attr(attrs)]; 185 | }, 186 | utils: { 187 | sumArray: function (array) { 188 | // reduce VS loop => reduce 189 | return array.reduce(function (prev, cur) { 190 | return prev + cur; 191 | }); 192 | } 193 | } 194 | }; 195 | })); 196 | -------------------------------------------------------------------------------- /js/sma.js: -------------------------------------------------------------------------------- 1 | /* global Highcharts module:true */ 2 | (function (factory) { 3 | if (typeof module === 'object' && module.exports) { 4 | module.exports = factory; 5 | } else { 6 | factory(Highcharts); 7 | } 8 | }(function (HC) { 9 | 'use strict'; 10 | /** 11 | 12 | Each indicator requires mothods: 13 | 14 | - getDefaultOptions() - returns object with default parameters, like period etc. 15 | - getValues(chart, series, options, points) - returns array of calculated values for indicator 16 | - getGraph(chart, series, options, values) - returns path, or columns as SVG elements to add. 17 | Doesn't add to the chart via renderer! 18 | 19 | **/ 20 | 21 | 22 | var merge = HC.merge, 23 | minInArray = HC.Axis.prototype.minInArray, 24 | maxInArray = HC.Axis.prototype.maxInArray, 25 | isArray = HC.isArray; 26 | 27 | HC.Indicator.prototype.sma = { 28 | getDefaultOptions: function () { 29 | return { 30 | period: 14, 31 | index: 0, 32 | approximation: 'average' 33 | }; 34 | }, 35 | getValues: function (chart, series, options, extraPoints) { 36 | var utils = this.utils, 37 | params = options.params, 38 | period = params.period, 39 | xVal = extraPoints[0].concat(series.processedXData || []), // #22 40 | yVal = extraPoints[1].concat(series.processedYData || []), // #22 41 | yValLen = yVal ? yVal.length : 0, 42 | range = 1, 43 | xValue = xVal[0], 44 | yValue = yVal[0], 45 | SMA = [], 46 | xData = [], 47 | yData = [], 48 | index = -1, 49 | i, points, 50 | SMAPoint; 51 | 52 | if (xVal.length <= period) { 53 | return false; 54 | } 55 | 56 | // switch index for OHLC / Candlestick / Arearange 57 | if (isArray(yVal[0])) { 58 | index = params.index ? params.index : 0; 59 | yValue = yVal[0][index]; 60 | } 61 | // starting point 62 | points = [[xValue, yValue]]; 63 | 64 | // accumulate first N-points 65 | while (range !== period) { 66 | utils.accumulateAverage(points, xVal, yVal, range, index); 67 | range++; 68 | } 69 | 70 | // calculate value one-by-one for each perdio in visible data 71 | 72 | for (i = range; i < yValLen; i++) { 73 | SMAPoint = utils.populateAverage(points, xVal, yVal, i, period, index); 74 | SMA.push(SMAPoint); 75 | xData.push(SMAPoint[0]); 76 | yData.push(SMAPoint[1]); 77 | 78 | utils.accumulateAverage(points, xVal, yVal, i, index); 79 | } 80 | 81 | SMAPoint = utils.populateAverage(points, xVal, yVal, i, period, index); 82 | SMA.push(SMAPoint); 83 | xData.push(SMAPoint[0]); 84 | yData.push(SMAPoint[1]); 85 | 86 | // register extremes for axis; 87 | options.yAxisMax = maxInArray(SMA); 88 | options.yAxisMin = minInArray(SMA); 89 | 90 | return { 91 | values: SMA, 92 | xData: xData, 93 | yData: yData 94 | }; 95 | }, 96 | getGraph: function (chart, series, options, values) { 97 | var path = [], 98 | attrs = {}, 99 | xAxis = series.xAxis, 100 | yAxis = options.Axis = series.yAxis, 101 | sma = values, 102 | smaLen = sma.length, 103 | smaX, 104 | smaY, 105 | i; 106 | 107 | if (options.visible === false) { 108 | return false; 109 | } 110 | 111 | options.styles = attrs = merge({ 112 | 'stroke-width': 2, 113 | stroke: 'red', 114 | dashstyle: 'ShortDash' 115 | }, options.styles); 116 | 117 | path.push('M', xAxis.toPixels(sma[0][0]), yAxis.toPixels(sma[0][1])); 118 | 119 | for (i = 0; i < smaLen; i++) { 120 | smaX = sma[i][0]; 121 | smaY = sma[i][1]; 122 | 123 | path.push('L', xAxis.toPixels(smaX), yAxis.toPixels(smaY)); 124 | } 125 | 126 | return [chart.renderer.path(path).attr(attrs)]; 127 | }, 128 | utils: { 129 | accumulateAverage: function (points, xVal, yVal, i, index) { 130 | var xValue = xVal[i], 131 | yValue = index < 0 ? yVal[i] : yVal[i][index]; 132 | 133 | points.push([xValue, yValue]); 134 | }, 135 | populateAverage: function (points, xVal, yVal, i) { 136 | var pLen = points.length, 137 | smaY = this.sumArray(points) / pLen, 138 | smaX = xVal[i - 1]; 139 | 140 | points.shift(); // remove point until range < period 141 | 142 | return [smaX, smaY]; 143 | }, 144 | sumArray: function (array) { 145 | // reduce VS loop => reduce 146 | return array.reduce(function (prev, cur) { 147 | return [null, prev[1] + cur[1]]; 148 | })[1]; 149 | } 150 | } 151 | }; 152 | })); -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. 2 | BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 3 | 1. Definitions 4 | "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 5 | 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: 6 | to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; to Distribute and Publicly Perform the Work including as incorporated in Collections; and, to Distribute and Publicly Perform Adaptations. For the avoidance of doubt: 7 | Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 8 | 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 9 | You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(b), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(b), as requested. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Section 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 5. Representations, Warranties and Disclaimer 10 | UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 11 | 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 12 | 7. Termination 13 | This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 8. Miscellaneous 14 | Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Indicators", 3 | "version": "2.1.6", 4 | "title": "Indicators", 5 | "author": { 6 | "name": "Black Label", 7 | "url": "http://www.blacklabel.pl/" 8 | }, 9 | "licenses": [{ 10 | "type": "Creative Commons Attribution (CC)", 11 | "url": "https://github.com/blacklabel/indicators/blob/master/license.txt" 12 | }], 13 | "dependencies": { 14 | "highstock": "2.1.5+" 15 | }, 16 | "demo": [ 17 | "https://jsfiddle.net/BlackLabel/RE7sS/" 18 | ], 19 | "description": "Highstock plugin to add technical indicators to charts.", 20 | "keywords": [ 21 | "indicators", 22 | "sma", 23 | "ema", 24 | "atr", 25 | "rsi", 26 | "highcharts", 27 | "highstock", 28 | "highcharts-addon" 29 | ], 30 | "maintainers": [{ 31 | "name": "Sebastian Bochan", 32 | "email": "sebastian@blacklabel.pl", 33 | "url": "http://www.blacklabel.pl" 34 | },{ 35 | "name": "Paweł Fus", 36 | "email": "pawel@blacklabel.pl", 37 | "url": "http://www.blacklabel.pl" 38 | },{ 39 | "name": "Kacper Madej", 40 | "email": "kacper@blacklabel.pl", 41 | "url": "http://www.blacklabel.pl" 42 | }], 43 | "homepage": "http://blacklabel.github.io/indicators/", 44 | "docs": "https://github.com/blacklabel/indicators/", 45 | "bugs": "https://github.com/blacklabel/indicators/issues", 46 | "download": "https://github.com/blacklabel/indicators/archive/master.zip" 47 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "highcharts-indicators", 3 | "version": "2.1.6", 4 | "description": "Highstock plugin to add technical indicators to charts.", 5 | "main": "js/indicators.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/blacklabel/indicators.git" 9 | }, 10 | "keywords": [ 11 | "highcharts", 12 | "highstock", 13 | "technical indicators", 14 | "sma", 15 | "ema", 16 | "rsi", 17 | "atr", 18 | "highcharts-addon" 19 | ], 20 | "author": "Black Label (http://blacklabel.pl)", 21 | "license": "SEE LICENSE IN license.txt", 22 | "bugs": { 23 | "url": "https://github.com/blacklabel/indicators/issues" 24 | }, 25 | "homepage": "https://github.com/blacklabel/indicators#readme", 26 | "files": [ 27 | "js/indicators.js", 28 | "js/sma.js", 29 | "js/ema.js", 30 | "js/atr.js", 31 | "js/rsi.js" 32 | ], 33 | "devDependencies": { 34 | "gulp": "^3.9.1", 35 | "gulp-eslint": "^2.0.0" 36 | } 37 | } 38 | --------------------------------------------------------------------------------