Spaces:
Runtime error
Runtime error
File size: 14,575 Bytes
c109682 |
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 |
/*!
* @license
* chartjs-chart-financial
* http://chartjs.org/
* Version: 0.1.0
*
* Copyright 2021 Chart.js Contributors
* Released under the MIT license
* https://github.com/chartjs/chartjs-chart-financial/blob/master/LICENSE.md
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js'), require('chart.js/helpers')) :
typeof define === 'function' && define.amd ? define(['chart.js', 'chart.js/helpers'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Chart, global.Chart.helpers));
}(this, (function (chart_js, helpers) { 'use strict';
/**
* Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
* @private
*/
function computeMinSampleSize(scale, pixels) {
let min = scale._length;
let prev, curr, i, ilen;
for (i = 1, ilen = pixels.length; i < ilen; ++i) {
min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
}
for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
curr = scale.getPixelForTick(i);
min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
prev = curr;
}
return min;
}
/**
* This class is based off controller.bar.js from the upstream Chart.js library
*/
class FinancialController extends chart_js.BarController {
getLabelAndValue(index) {
const me = this;
const parsed = me.getParsed(index);
const axis = me._cachedMeta.iScale.axis;
const {o, h, l, c} = parsed;
const value = `O: ${o} H: ${h} L: ${l} C: ${c}`;
return {
label: `${me._cachedMeta.iScale.getLabelForValue(parsed[axis])}`,
value
};
}
getAllParsedValues() {
const meta = this._cachedMeta;
const axis = meta.iScale.axis;
const parsed = meta._parsed;
const values = [];
for (let i = 0; i < parsed.length; ++i) {
values.push(parsed[i][axis]);
}
return values;
}
/**
* Implement this ourselves since it doesn't handle high and low values
* https://github.com/chartjs/Chart.js/issues/7328
* @protected
*/
getMinMax(scale) {
const meta = this._cachedMeta;
const _parsed = meta._parsed;
const axis = meta.iScale.axis;
if (_parsed.length < 2) {
return {min: 0, max: 1};
}
if (scale === meta.iScale) {
return {min: _parsed[0][axis], max: _parsed[_parsed.length - 1][axis]};
}
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (let i = 0; i < _parsed.length; i++) {
const data = _parsed[i];
min = Math.min(min, data.l);
max = Math.max(max, data.h);
}
return {min, max};
}
_getRuler() {
const me = this;
const opts = me.options;
const meta = me._cachedMeta;
const iScale = meta.iScale;
const axis = iScale.axis;
const pixels = [];
for (let i = 0; i < meta.data.length; ++i) {
pixels.push(iScale.getPixelForValue(me.getParsed(i)[axis]));
}
const barThickness = opts.barThickness;
const min = computeMinSampleSize(iScale, pixels);
return {
min,
pixels,
start: iScale._startPixel,
end: iScale._endPixel,
stackCount: me._getStackCount(),
scale: iScale,
ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
};
}
/**
* @protected
*/
calculateElementProperties(index, ruler, reset, options) {
const me = this;
const vscale = me._cachedMeta.vScale;
const base = vscale.getBasePixel();
const ipixels = me._calculateBarIndexPixels(index, ruler, options);
const data = me.chart.data.datasets[me.index].data[index];
const open = vscale.getPixelForValue(data.o);
const high = vscale.getPixelForValue(data.h);
const low = vscale.getPixelForValue(data.l);
const close = vscale.getPixelForValue(data.c);
return {
base: reset ? base : low,
x: ipixels.center,
y: (low + high) / 2,
width: ipixels.size,
open,
high,
low,
close
};
}
draw() {
const me = this;
const chart = me.chart;
const rects = me._cachedMeta.data;
helpers.clipArea(chart.ctx, chart.chartArea);
for (let i = 0; i < rects.length; ++i) {
rects[i].draw(me._ctx);
}
helpers.unclipArea(chart.ctx);
}
}
FinancialController.overrides = {
label: '',
parsing: false,
hover: {
mode: 'label'
},
datasets: {
categoryPercentage: 0.8,
barPercentage: 0.9,
animation: {
numbers: {
type: 'number',
properties: ['x', 'y', 'base', 'width', 'open', 'high', 'low', 'close']
}
}
},
scales: {
x: {
type: 'timeseries',
offset: true,
ticks: {
major: {
enabled: true,
},
fontStyle: context => context.tick.major ? 'bold' : undefined,
source: 'data',
maxRotation: 0,
autoSkip: true,
autoSkipPadding: 75,
sampleSize: 100
},
afterBuildTicks: scale => {
const DateTime = window && window.luxon && window.luxon.DateTime;
if (!DateTime) {
return;
}
const majorUnit = scale._majorUnit;
const ticks = scale.ticks;
const firstTick = ticks[0];
if (!firstTick) {
return;
}
let val = DateTime.fromMillis(firstTick.value);
if ((majorUnit === 'minute' && val.second === 0)
|| (majorUnit === 'hour' && val.minute === 0)
|| (majorUnit === 'day' && val.hour === 9)
|| (majorUnit === 'month' && val.day <= 3 && val.weekday === 1)
|| (majorUnit === 'year' && val.month === 1)) {
firstTick.major = true;
} else {
firstTick.major = false;
}
let lastMajor = val.get(majorUnit);
for (let i = 1; i < ticks.length; i++) {
const tick = ticks[i];
val = DateTime.fromMillis(tick.value);
const currMajor = val.get(majorUnit);
tick.major = currMajor !== lastMajor;
lastMajor = currMajor;
}
scale.ticks = ticks;
}
},
y: {
type: 'linear'
}
},
plugins: {
tooltip: {
intersect: false,
mode: 'index',
callbacks: {
label(ctx) {
const point = ctx.parsed;
if (!helpers.isNullOrUndef(point.y)) {
return chart_js.defaults.plugins.tooltip.callbacks.label(ctx);
}
const {o, h, l, c} = point;
return `O: ${o} H: ${h} L: ${l} C: ${c}`;
}
}
}
}
};
const globalOpts$2 = chart_js.Chart.defaults;
globalOpts$2.elements.financial = {
color: {
up: 'rgba(255, 0, 0, 1)',
down: 'rgba(0, 0, 255, 1)',
unchanged: 'rgba(90, 90, 90, 1)',
}
};
/**
* Helper function to get the bounds of the bar regardless of the orientation
* @param {Rectangle} bar the bar
* @param {boolean} [useFinalPosition]
* @return {object} bounds of the bar
* @private
*/
function getBarBounds(bar, useFinalPosition) {
const {x, y, base, width, height} = bar.getProps(['x', 'low', 'high', 'width', 'height'], useFinalPosition);
let left, right, top, bottom, half;
if (bar.horizontal) {
half = height / 2;
left = Math.min(x, base);
right = Math.max(x, base);
top = y - half;
bottom = y + half;
} else {
half = width / 2;
left = x - half;
right = x + half;
top = Math.min(y, base); // use min because 0 pixel at top of screen
bottom = Math.max(y, base);
}
return {left, top, right, bottom};
}
function inRange(bar, x, y, useFinalPosition) {
const skipX = x === null;
const skipY = y === null;
const bounds = !bar || (skipX && skipY) ? false : getBarBounds(bar, useFinalPosition);
return bounds
&& (skipX || x >= bounds.left && x <= bounds.right)
&& (skipY || y >= bounds.top && y <= bounds.bottom);
}
class FinancialElement extends chart_js.Element {
height() {
return this.base - this.y;
}
inRange(mouseX, mouseY, useFinalPosition) {
return inRange(this, mouseX, mouseY, useFinalPosition);
}
inXRange(mouseX, useFinalPosition) {
return inRange(this, mouseX, null, useFinalPosition);
}
inYRange(mouseY, useFinalPosition) {
return inRange(this, null, mouseY, useFinalPosition);
}
getRange(axis) {
return axis === 'x' ? this.width / 2 : this.height / 2;
}
getCenterPoint(useFinalPosition) {
const {x, low, high} = this.getProps(['x', 'low', 'high'], useFinalPosition);
return {
x,
y: (high + low) / 2
};
}
tooltipPosition(useFinalPosition) {
const {x, open, close} = this.getProps(['x', 'open', 'close'], useFinalPosition);
return {
x,
y: (open + close) / 2
};
}
}
const globalOpts$1 = chart_js.Chart.defaults;
class CandlestickElement extends FinancialElement {
draw(ctx) {
const me = this;
const {x, open, high, low, close} = me;
let borderColors = me.borderColor;
if (typeof borderColors === 'string') {
borderColors = {
up: borderColors,
down: borderColors,
unchanged: borderColors
};
}
let borderColor;
if (close < open) {
borderColor = helpers.valueOrDefault(borderColors ? borderColors.up : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.up : undefined, globalOpts$1.elements.candlestick.color.up);
} else if (close > open) {
borderColor = helpers.valueOrDefault(borderColors ? borderColors.down : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.down : undefined, globalOpts$1.elements.candlestick.color.down);
} else {
borderColor = helpers.valueOrDefault(borderColors ? borderColors.unchanged : undefined, globalOpts$1.elements.candlestick.borderColor);
ctx.fillStyle = helpers.valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts$1.elements.candlestick.color.unchanged);
}
ctx.lineWidth = helpers.valueOrDefault(me.borderWidth, globalOpts$1.elements.candlestick.borderWidth);
ctx.strokeStyle = helpers.valueOrDefault(borderColor, globalOpts$1.elements.candlestick.borderColor);
ctx.beginPath();
ctx.moveTo(x, high);
ctx.lineTo(x, Math.min(open, close));
ctx.moveTo(x, low);
ctx.lineTo(x, Math.max(open, close));
ctx.stroke();
ctx.fillRect(x - me.width / 2, close, me.width, open - close);
ctx.strokeRect(x - me.width / 2, close, me.width, open - close);
ctx.closePath();
}
}
CandlestickElement.id = 'candlestick';
CandlestickElement.defaults = helpers.merge({}, [globalOpts$1.elements.financial, {
borderColor: globalOpts$1.elements.financial.color.unchanged,
borderWidth: 1,
}]);
class CandlestickController extends FinancialController {
updateElements(elements, start, count, mode) {
const me = this;
const dataset = me.getDataset();
const ruler = me._ruler || me._getRuler();
const firstOpts = me.resolveDataElementOptions(start, mode);
const sharedOptions = me.getSharedOptions(firstOpts);
const includeOptions = me.includeOptions(mode, sharedOptions);
me.updateSharedOptions(sharedOptions, mode, firstOpts);
for (let i = start; i < count; i++) {
const options = sharedOptions || me.resolveDataElementOptions(i, mode);
const lineColor = (elements[i]['close'] - elements[i]['open'] < 0)? "rgb(255, 0, 0, 1)" : "rgb(0, 0, 255, 1)";
const baseProperties = me.calculateElementProperties(i, ruler, mode === 'reset', options);
const properties = {
...baseProperties,
datasetLabel: dataset.label || '',
// label: '', // to get label value please use dataset.data[index].label
// Appearance
color: dataset.color,
borderColor: lineColor,
// borderColor: dataset.borderColor,
borderWidth: dataset.borderWidth,
};
if (includeOptions) {
properties.options = options;
}
me.updateElement(elements[i], i, properties, mode);
}
}
}
CandlestickController.id = 'candlestick';
CandlestickController.defaults = helpers.merge({
dataElementType: CandlestickElement.id
}, chart_js.Chart.defaults.financial);
const globalOpts = chart_js.Chart.defaults;
class OhlcElement extends FinancialElement {
draw(ctx) {
const me = this;
const {x, open, high, low, close} = me;
const armLengthRatio = helpers.valueOrDefault(me.armLengthRatio, globalOpts.elements.ohlc.armLengthRatio);
let armLength = helpers.valueOrDefault(me.armLength, globalOpts.elements.ohlc.armLength);
if (armLength === null) {
// The width of an ohlc is affected by barPercentage and categoryPercentage
// This behavior is caused by extending controller.financial, which extends controller.bar
// barPercentage and categoryPercentage are now set to 1.0 (see controller.ohlc)
// and armLengthRatio is multipled by 0.5,
// so that when armLengthRatio=1.0, the arms from neighbour ohcl touch,
// and when armLengthRatio=0.0, ohcl are just vertical lines.
armLength = me.width * armLengthRatio * 0.5;
}
if (close < open) {
ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.up : undefined, globalOpts.elements.ohlc.color.up);
} else if (close > open) {
ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.down : undefined, globalOpts.elements.ohlc.color.down);
} else {
ctx.strokeStyle = helpers.valueOrDefault(me.color ? me.color.unchanged : undefined, globalOpts.elements.ohlc.color.unchanged);
}
ctx.lineWidth = helpers.valueOrDefault(me.lineWidth, globalOpts.elements.ohlc.lineWidth);
ctx.beginPath();
ctx.moveTo(x, high);
ctx.lineTo(x, low);
ctx.moveTo(x - armLength, open);
ctx.lineTo(x, open);
ctx.moveTo(x + armLength, close);
ctx.lineTo(x, close);
ctx.stroke();
}
}
OhlcElement.id = 'ohlc';
OhlcElement.defaults = helpers.merge({}, [globalOpts.elements.financial, {
lineWidth: 2,
armLength: null,
armLengthRatio: 0.8,
}]);
class OhlcController extends FinancialController {
updateElements(elements, start, count, mode) {
const me = this;
const dataset = me.getDataset();
const ruler = me._ruler || me._getRuler();
const firstOpts = me.resolveDataElementOptions(start, mode);
const sharedOptions = me.getSharedOptions(firstOpts);
const includeOptions = me.includeOptions(mode, sharedOptions);
for (let i = 0; i < count; i++) {
const options = sharedOptions || me.resolveDataElementOptions(i, mode);
const baseProperties = me.calculateElementProperties(i, ruler, mode === 'reset', options);
const properties = {
...baseProperties,
datasetLabel: dataset.label || '',
lineWidth: dataset.lineWidth,
armLength: dataset.armLength,
armLengthRatio: dataset.armLengthRatio,
color: dataset.color,
};
if (includeOptions) {
properties.options = options;
}
me.updateElement(elements[i], i, properties, mode);
}
}
}
OhlcController.id = 'ohlc';
OhlcController.defaults = helpers.merge({
dataElementType: OhlcElement.id,
datasets: {
barPercentage: 1.0,
categoryPercentage: 1.0
}
}, chart_js.Chart.defaults.financial);
chart_js.Chart.register(CandlestickController, OhlcController, CandlestickElement, OhlcElement);
})));
|