supertrend.src.js 19.3 KB
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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 155 156 157 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
/* *
 *
 *  License: www.highcharts.com/license
 *
 * */

'use strict';

import H from '../parts/Globals.js';

import U from '../parts/Utilities.js';
var isArray = U.isArray,
    objectEach = U.objectEach;

var ATR = H.seriesTypes.atr,
    SMA = H.seriesTypes.sma,
    merge = H.merge,
    correctFloat = H.correctFloat;

// Utils:
function createPointObj(mainSeries, index, close) {
    return {
        index: index,
        close: mainSeries.yData[index][close],
        x: mainSeries.xData[index]
    };
}

/**
 * The Supertrend series type.
 *
 * @private
 * @class
 * @name Highcharts.seriesTypes.supertrend
 *
 * @augments Highcharts.Series
 */
H.seriesType(
    'supertrend',
    'sma',
    /**
     * Supertrend indicator. This series requires the `linkedTo` option to be
     * set and should be loaded after the `stock/indicators/indicators.js` and
     * `stock/indicators/sma.js`.
     *
     * @sample {highstock} stock/indicators/supertrend
     *         Supertrend indicator
     *
     * @extends      plotOptions.sma
     * @since        7.0.0
     * @product      highstock
     * @excluding    allAreas, color, cropThreshold, negativeColor, colorAxis,
     *               joinBy, keys, navigatorOptions, pointInterval,
     *               pointIntervalUnit, pointPlacement, pointRange, pointStart,
     *               showInNavigator, stacking, threshold
     * @optionparent plotOptions.supertrend
     */
    {
        /**
         * Paramters used in calculation of Supertrend indicator series points.
         *
         * @excluding index
         */
        params: {
            /**
             * Multiplier for Supertrend Indicator.
             */
            multiplier: 3,
            /**
             * The base period for indicator Supertrend Indicator calculations.
             * This is the number of data points which are taken into account
             * for the indicator calculations.
             */
            period: 10
        },
        /**
         * Color of the Supertrend series line that is beneath the main series.
         *
         * @sample {highstock} stock/indicators/supertrend/
         *         Example with risingTrendColor
         *
         * @type {Highcharts.ColorString}
         */
        risingTrendColor: '#06B535',
        /**
         * Color of the Supertrend series line that is above the main series.
         *
         * @sample {highstock} stock/indicators/supertrend/
         *         Example with fallingTrendColor
         *
         * @type {Highcharts.ColorString}
         */
        fallingTrendColor: '#F21313',
        /**
         * The styles for the Supertrend line that intersect main series.
         *
         * @sample {highstock} stock/indicators/supertrend/
         *         Example with changeTrendLine
         */
        changeTrendLine: {
            styles: {
                /**
                 * Pixel width of the line.
                 */
                lineWidth: 1,

                /**
                 * Color of the line.
                 *
                 * @type {Highcharts.ColorString}
                 */
                lineColor: '#333333',

                /**
                 * The dash or dot style of the grid lines. For possible
                 * values, see
                 * [this demonstration](https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/).
                 *
                 * @sample {highcharts} highcharts/yaxis/gridlinedashstyle/
                 *         Long dashes
                 * @sample {highstock} stock/xaxis/gridlinedashstyle/
                 *         Long dashes
                 *
                 * @type  {Highcharts.DashStyleValue}
                 * @since 7.0.0
                 */
                dashStyle: 'LongDash'
            }
        }
    },
    /**
     * @lends Highcharts.Series.prototype
     */
    {
        nameBase: 'Supertrend',
        nameComponents: ['multiplier', 'period'],
        requiredIndicators: ['atr'],
        init: function () {
            var options,
                parentOptions;

            SMA.prototype.init.apply(this, arguments);

            options = this.options;
            parentOptions = this.linkedParent.options;

            // Indicator cropThreshold has to be equal linked series one
            // reduced by period due to points comparison in drawGraph method
            // (#9787)
            options.cropThreshold =
                parentOptions.cropThreshold - (options.params.period - 1);
        },
        drawGraph: function () {
            var indicator = this,
                indicOptions = indicator.options,

                // Series that indicator is linked to
                mainSeries = indicator.linkedParent,
                mainLinePoints = mainSeries ? mainSeries.points : [],
                indicPoints = indicator.points,
                indicPath = indicator.graph,
                indicPointsLen = indicPoints.length,

                // Points offset between lines
                tempOffset = mainLinePoints.length - indicPointsLen,
                offset = tempOffset > 0 ? tempOffset : 0,
                gappedExtend = {
                    options: {
                        gapSize: indicOptions.gapSize
                    }
                },

                // Sorted supertrend points array
                groupedPoitns = {
                    top: [], // Rising trend line points
                    bottom: [], // Falling trend line points
                    intersect: [] // Change trend line points
                },

                // Options for trend lines
                supertrendLineOptions = {
                    top: {
                        styles: {
                            lineWidth: indicOptions.lineWidth,
                            lineColor: indicOptions.fallingTrendColor,
                            dashStyle: indicOptions.dashStyle
                        }
                    },
                    bottom: {
                        styles: {
                            lineWidth: indicOptions.lineWidth,
                            lineColor: indicOptions.risingTrendColor,
                            dashStyle: indicOptions.dashStyle
                        }
                    },
                    intersect: indicOptions.changeTrendLine
                },
                close = 3,

                // Supertrend line point
                point,

                // Supertrend line next point (has smaller x pos than point)
                nextPoint,

                // Main series points
                mainPoint,
                nextMainPoint,

                // Used when supertrend and main points are shifted
                // relative to each other
                prevMainPoint,
                prevPrevMainPoint,

                // Used when particular point color is set
                pointColor,

                // Temporary points that fill groupedPoitns array
                newPoint,
                newNextPoint;

            // Loop which sort supertrend points
            while (indicPointsLen--) {
                point = indicPoints[indicPointsLen];
                nextPoint = indicPoints[indicPointsLen - 1];
                mainPoint = mainLinePoints[indicPointsLen - 1 + offset];
                nextMainPoint = mainLinePoints[indicPointsLen - 2 + offset];
                prevMainPoint = mainLinePoints[indicPointsLen + offset];
                prevPrevMainPoint = mainLinePoints[indicPointsLen + offset + 1];
                pointColor = point.options.color;
                newPoint = {
                    x: point.x,
                    plotX: point.plotX,
                    plotY: point.plotY,
                    isNull: false
                };

                // When mainPoint is the last one (left plot area edge)
                // but supertrend has additional one
                if (
                    !nextMainPoint &&
                    mainPoint &&
                    mainSeries.yData[mainPoint.index - 1]
                ) {
                    nextMainPoint = createPointObj(
                        mainSeries, mainPoint.index - 1, close
                    );
                }

                // When prevMainPoint is the last one (right plot area edge)
                // but supertrend has additional one (and points are shifted)
                if (
                    !prevPrevMainPoint &&
                    prevMainPoint &&
                    mainSeries.yData[prevMainPoint.index + 1]
                ) {
                    prevPrevMainPoint = createPointObj(
                        mainSeries, prevMainPoint.index + 1, close
                    );
                }

                // When points are shifted (right or left plot area edge)
                if (
                    !mainPoint &&
                    nextMainPoint &&
                    mainSeries.yData[nextMainPoint.index + 1]
                ) {
                    mainPoint = createPointObj(
                        mainSeries, nextMainPoint.index + 1, close
                    );
                } else if (
                    !mainPoint &&
                    prevMainPoint &&
                    mainSeries.yData[prevMainPoint.index - 1]
                ) {
                    mainPoint = createPointObj(
                        mainSeries, prevMainPoint.index - 1, close
                    );
                }

                // Check if points are shifted relative to each other
                if (
                    point &&
                    mainPoint &&
                    prevMainPoint &&
                    nextMainPoint &&
                    point.x !== mainPoint.x
                ) {
                    if (point.x === prevMainPoint.x) {
                        nextMainPoint = mainPoint;
                        mainPoint = prevMainPoint;
                    } else if (point.x === nextMainPoint.x) {
                        mainPoint = nextMainPoint;
                        nextMainPoint = {
                            close: mainSeries.yData[mainPoint.index - 1][close],
                            x: mainSeries.xData[mainPoint.index - 1]
                        };
                    } else if (
                        prevPrevMainPoint && point.x === prevPrevMainPoint.x
                    ) {
                        mainPoint = prevPrevMainPoint;
                        nextMainPoint = prevMainPoint;
                    }
                }

                if (nextPoint && nextMainPoint && mainPoint) {

                    newNextPoint = {
                        x: nextPoint.x,
                        plotX: nextPoint.plotX,
                        plotY: nextPoint.plotY,
                        isNull: false
                    };

                    if (
                        point.y >= mainPoint.close &&
                        nextPoint.y >= nextMainPoint.close
                    ) {
                        point.color =
                            pointColor || indicOptions.fallingTrendColor;
                        groupedPoitns.top.push(newPoint);

                    } else if (
                        point.y < mainPoint.close &&
                        nextPoint.y < nextMainPoint.close
                    ) {
                        point.color =
                            pointColor || indicOptions.risingTrendColor;
                        groupedPoitns.bottom.push(newPoint);

                    } else {
                        groupedPoitns.intersect.push(newPoint);
                        groupedPoitns.intersect.push(newNextPoint);

                        // Additional null point to make a gap in line
                        groupedPoitns.intersect.push(merge(newNextPoint, {
                            isNull: true
                        }));

                        if (
                            point.y >= mainPoint.close &&
                            nextPoint.y < nextMainPoint.close
                        ) {
                            point.color =
                                pointColor || indicOptions.fallingTrendColor;
                            nextPoint.color =
                                pointColor || indicOptions.risingTrendColor;
                            groupedPoitns.top.push(newPoint);
                            groupedPoitns.top.push(merge(newNextPoint, {
                                isNull: true
                            }));
                        } else if (
                            point.y < mainPoint.close &&
                            nextPoint.y >= nextMainPoint.close
                        ) {
                            point.color =
                                pointColor || indicOptions.risingTrendColor;
                            nextPoint.color =
                                pointColor || indicOptions.fallingTrendColor;
                            groupedPoitns.bottom.push(newPoint);
                            groupedPoitns.bottom.push(merge(newNextPoint, {
                                isNull: true
                            }));
                        }
                    }
                } else if (mainPoint) {
                    if (point.y >= mainPoint.close) {
                        point.color =
                            pointColor || indicOptions.fallingTrendColor;
                        groupedPoitns.top.push(newPoint);
                    } else {
                        point.color =
                            pointColor || indicOptions.risingTrendColor;
                        groupedPoitns.bottom.push(newPoint);
                    }
                }
            }

            // Generate lines:
            objectEach(groupedPoitns, function (values, lineName) {
                indicator.points = values;
                indicator.options = merge(
                    supertrendLineOptions[lineName].styles,
                    gappedExtend
                );
                indicator.graph = indicator['graph' + lineName + 'Line'];
                SMA.prototype.drawGraph.call(indicator);

                // Now save line
                indicator['graph' + lineName + 'Line'] = indicator.graph;
            });

            // Restore options:
            indicator.points = indicPoints;
            indicator.options = indicOptions;
            indicator.graph = indicPath;
        },

        // Supertrend (Multiplier, Period) Formula:

        // BASIC UPPERBAND = (HIGH + LOW) / 2 + Multiplier * ATR(Period)
        // BASIC LOWERBAND = (HIGH + LOW) / 2 - Multiplier * ATR(Period)

        // FINAL UPPERBAND =
        //     IF(
        //      Current BASICUPPERBAND  < Previous FINAL UPPERBAND AND
        //      Previous Close > Previous FINAL UPPERBAND
        //     ) THEN (Current BASIC UPPERBAND)
        //     ELSE (Previous FINALUPPERBAND)

        // FINAL LOWERBAND =
        //     IF(
        //      Current BASIC LOWERBAND  > Previous FINAL LOWERBAND AND
        //      Previous Close < Previous FINAL LOWERBAND
        //     ) THEN (Current BASIC LOWERBAND)
        //     ELSE (Previous FINAL LOWERBAND)

        // SUPERTREND =
        //     IF(
        //      Previous Supertrend == Previous FINAL UPPERBAND AND
        //      Current Close < Current FINAL UPPERBAND
        //     ) THAN Current FINAL UPPERBAND
        //     ELSE IF(
        //      Previous Supertrend == Previous FINAL LOWERBAND AND
        //      Current Close < Current FINAL LOWERBAND
        //     ) THAN Current FINAL UPPERBAND
        //     ELSE IF(
        //      Previous Supertrend == Previous FINAL UPPERBAND AND
        //      Current Close > Current FINAL UPPERBAND
        //     ) THAN Current FINAL LOWERBAND
        //     ELSE IF(
        //      Previous Supertrend == Previous FINAL LOWERBAND AND
        //      Current Close > Current FINAL LOWERBAND
        //     ) THAN Current FINAL LOWERBAND


        getValues: function (series, params) {
            var period = params.period,
                multiplier = params.multiplier,
                xVal = series.xData,
                yVal = series.yData,
                ATRData = [],
                ST = [], // 0- date, 1- Supertrend indicator
                xData = [],
                yData = [],
                close = 3,
                low = 2,
                high = 1,
                periodsOffset = (period === 0) ? 0 : period - 1,
                basicUp,
                basicDown,
                finalUp = [],
                finalDown = [],
                supertrend,
                prevFinalUp,
                prevFinalDown,
                prevST, // previous Supertrend
                prevY,
                y,
                i;

            if (
                (xVal.length <= period) || !isArray(yVal[0]) ||
                yVal[0].length !== 4 || period < 0
            ) {
                return false;
            }

            ATRData = ATR.prototype.getValues.call(this, series, {
                period: period
            }).yData;

            for (i = 0; i < ATRData.length; i++) {
                y = yVal[periodsOffset + i];
                prevY = yVal[periodsOffset + i - 1] || [];
                prevFinalUp = finalUp[i - 1];
                prevFinalDown = finalDown[i - 1];
                prevST = yData[i - 1];

                if (i === 0) {
                    prevFinalUp = prevFinalDown = prevST = 0;
                }

                basicUp = correctFloat(
                    (y[high] + y[low]) / 2 + multiplier * ATRData[i]
                );
                basicDown = correctFloat(
                    (y[high] + y[low]) / 2 - multiplier * ATRData[i]
                );

                if (
                    (basicUp < prevFinalUp) ||
                    (prevY[close] > prevFinalUp)
                ) {
                    finalUp[i] = basicUp;
                } else {
                    finalUp[i] = prevFinalUp;
                }

                if (
                    (basicDown > prevFinalDown) ||
                    (prevY[close] < prevFinalDown)
                ) {
                    finalDown[i] = basicDown;
                } else {
                    finalDown[i] = prevFinalDown;
                }

                if (prevST === prevFinalUp && y[close] < finalUp[i] ||
                    prevST === prevFinalDown && y[close] < finalDown[i]
                ) {
                    supertrend = finalUp[i];
                } else if (
                    prevST === prevFinalUp && y[close] > finalUp[i] ||
                    prevST === prevFinalDown && y[close] > finalDown[i]
                ) {
                    supertrend = finalDown[i];
                }

                ST.push([xVal[periodsOffset + i], supertrend]);
                xData.push(xVal[periodsOffset + i]);
                yData.push(supertrend);
            }

            return {
                values: ST,
                xData: xData,
                yData: yData
            };
        }
    }
);

/**
 * A `Supertrend indicator` series. If the [type](#series.supertrend.type)
 * option is not specified, it is inherited from [chart.type](#chart.type).
 *
 * @extends   series,plotOptions.supertrend
 * @since     7.0.0
 * @product   highstock
 * @excluding allAreas, color, colorAxis, cropThreshold, data, dataParser,
 *            dataURL, joinBy, keys, navigatorOptions, negativeColor,
 *            pointInterval, pointIntervalUnit, pointPlacement, pointRange,
 *            pointStart, showInNavigator, stacking, threshold
 * @apioption series.supertrend
 */