/
rocketcharts.js
1828 lines (1489 loc) · 60.4 KB
/
rocketcharts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Base class, keeps track of our panels, settings, metrics and data, also exposes indicator enum
* @alias rocketcharts
* @return {bool}
* @method
*/
function Rocketchart() {
this.panels = [];
this.panelOverlays = [];
this.data = [];
this.element;
this.indicators = [{name: 'Simple Moving Average', id: 'simplemovingaverage'},
{name: 'Weighted Moving Average', id: 'weightedmovingaverage'},
{name: 'Moving Average Convergance/Divergance', id: 'movingaverageconvergencedivergence'},
{name: 'Parabolic SAR', id: 'parabolicsar'},
{name: 'Bollinger Bands', id: 'bollingerbands'},
{name: 'Stochastic Oscillator Fast', id: 'stochasticfast'}];
// Used internally to assign IDs to indicators across panel boundaries,
// i.e. indicatorIndex[0] = {panelID: 1, indicatorID: 0}
// so I can call removeIndicator(0), rather than looking up a panel and
// calling remove on the panel directly.
this.indicatorIndex = [];
this.priceAxisWidth = 75;
this.settings = {
debug: false,
minimumPanelHeight:200,
defaultUpColor:"#00EAFF",
defaultDownColor:"#005F6B",
backgroundColor:"#343838"
};
this.view = {
horizontalPixelsPerPoint : 0,
halfHorizontalPixelsPerPoint : 0,
startingPoint : 0,
endingPoint : 0
};
this.initComplete = function() {};
return true;
}
/**
* Appends markup to passed element, hooks into mouse-events, sets up our raster text, other bootup stuff
* @alias rocketcharts.init(element, settings)
* @param {string} element The string identifier of the html element to attach to
* @param {Object} settings Holds any number of settings
* @return {void}
* @method
*/
Rocketchart.prototype.init = function(element, settings){
var self = this;
// store parent element after looking it up with jquery
self.element = $(element);
self.width = self.element.width();
self.element.css("position", "relative");
self.element.append("<div id=\"panels\" style=\"height: 100%; width: 100%; position: relative;\"></div>");
var panelsElement = $("#panels", self.element);
panelsElement.css("overflow", "auto");
panelsElement.css("margin", "0");
panelsElement.css("padding", "0");
$(window).resize(function() {
self.resize(self.element.width(), self.element.height());
self.draw();
});
panelsElement.bind("mousedown", function(event, ui) {
$(this).bind( "mousemove", function(event, ui) {
var rect = self.panels[0]._canvas.getBoundingClientRect();
var relativeX = event.pageX - rect.left;
var relativeY = event.pageY - self.element.offset().top + $(this).scrollTop();
self.headsUpDisplay(relativeX, relativeY);
});
this.style.cursor = 'crosshair';
var rect = self.panels[0]._canvas.getBoundingClientRect();
var relativeX = event.pageX - rect.left;
var relativeY = event.pageY - self.element.offset().top + $(this).scrollTop();
self.headsUpDisplay(relativeX, relativeY);
return false; // Prevents browser from changing cursor to 'I-Beam', thinking we are trying to select text
});
panelsElement.bind("mouseup", function(event, ui) {
$(this).unbind( "mousemove" );
this.style.cursor = 'default';
self.clearHUD();
});
//If settings were passed in, apply them to the instance settings.
if (!!settings) {
$.extend(self.settings, settings);
}
self.settings.defaultUpColor = hexToRgb(self.settings.defaultUpColor);
self.settings.defaultDownColor = hexToRgb(self.settings.defaultDownColor);
self.settings.backgroundColor = hexToRgb(self.settings.backgroundColor);
if (self.settings.resizable)
self.element.resizable();
self.element.append("<div style=\"height: 15px; font-size: 1em; line-height: 1em; width: 100%; position: absolute; bottom: 0; z-index: 2; background-color: " + rgbToHex(self.settings.backgroundColor.r, self.settings.backgroundColor.g, self.settings.backgroundColor.b) + ";\">" +
"<canvas id=\"dateAxisCanvas\" width=\"" + self.width + "\" height=\"15\"></canvas>" +
"</div>");
self.dateAxisCanvas = $("#dateAxisCanvas", self.element).get(0);
};
/**
* Handles element resizing
* @alias rocketcharts.resize(w, h)
* @param {int} w Width
* @param {int} h Height
* @return {void}
* @method
*/
Rocketchart.prototype.resize = function(w, h){
var self = this;
/*
* The code relating to calcHeight was for dynamically resizing the height of the panels
* when the end-user resized them via JQueryUI - putting this on hold for the moment
*/
// var calcHeight = 0;
self.width = w;
self.dateAxisCanvas.setAttribute("width", w);
var simpleHeight = Math.floor(h / self.panels.length) - 1;
if (simpleHeight < self.settings.minimumPanelHeight) {
simpleHeight = self.settings.minimumPanelHeight;
}
for (var i=0; i < self.panels.length; i++) {
/*
if (this.panels[i]._userHeight <= 1){
calcHeight = this.panels[i]._userHeight * h;
} else {
calcHeight = this.panels[i]._userHeight;
}
*/
// update the width and height of the canvas
self.panels[i]._canvas.setAttribute("width", w - 1);
self.panels[i]._canvas.setAttribute("height", simpleHeight);
self.panels[i]._canvas.style.top = simpleHeight * i;
self.panelOverlays[i].setAttribute("width", w - 1);
self.panelOverlays[i].setAttribute("height", simpleHeight);
self.panelOverlays[i].style.top = simpleHeight * i;
}
}
/**
* Calculates point for HUD, sets draw flags based on mouse position
* @alias rocketcharts.headsUpDisplay(x, y)
* @param {int} x
* @param {int} y
* @return {void}
* @method
*/
Rocketchart.prototype.headsUpDisplay = function(x, y){
var self = this;
var dateAxisWidth = self.width - self.priceAxisWidth;
var displayedPoints = self.view.endingPoint - self.view.startingPoint;
var horizontalPixelsPerPoint = self.view.horizontalPixelsPerPoint;
var halfhorizSpacing = self.view.halfHorizontalPixelsPerPoint;
var point = -1;
if (x > dateAxisWidth) {
// flag the removal of info box
return;
} else {
point = Math.floor(x / horizontalPixelsPerPoint);
}
var pointX = (point * horizontalPixelsPerPoint) + halfhorizSpacing;
point = point + self.view.startingPoint;
var height = 0;
var width = 0;
var bottom = 0;
var calcY = 0;
var legendLines = [];
for (var i=0; i < self.panelOverlays.length; i++) {
// grab the datacontext of the canvas
var context = self.panelOverlays[i].getContext("2d");
// read the height of the canvas
height = parseInt(self.panelOverlays[i].getAttribute("height"));
width = parseInt(self.panelOverlays[i].getAttribute("width"));
// create a new pixel array
var imageData = context.createImageData(width, height);
line(imageData, pointX, 0, pointX, height, 255, 255, 255, 255, 1);
bottom = self.panelOverlays[i].offsetTop + self.panelOverlays[i].height;
if ((y > self.panelOverlays[i].offsetTop) && (y < bottom) ) {
calcY = y - self.panelOverlays[i].offsetTop;
line(imageData, 0, calcY, width, calcY, 255, 255, 255, 255, 1);
}
// HUD:
for (var s=0; s < self.panels[i]._series.length; s++) {
legendLines[legendLines.length] = self.panels[i]._series[s].title + " [OPEN]: " + formatRate(self.panels[i]._series[s].data[point]["open"]);
legendLines[legendLines.length] = self.panels[i]._series[s].title + " [HIGH]: " + formatRate(self.panels[i]._series[s].data[point]["high"]);
legendLines[legendLines.length] = self.panels[i]._series[s].title + " [LOW]: " + formatRate(self.panels[i]._series[s].data[point]["low"]);
legendLines[legendLines.length] = self.panels[i]._series[s].title + " [CLOSE]: " + formatRate(self.panels[i]._series[s].data[point]["close"]);
legendLines[legendLines.length] = self.panels[i]._series[s].title + " [DATE]: " + self.panels[i]._series[s].data[point]["date"];
}
for (var s=0; s < self.panels[i]._indicators.length; s++) {
for (var j=0; j < self.panels[i]._indicators[s]._indicator._series.length; j++) {
legendLines[legendLines.length] = self.panels[i]._indicators[s]._indicator._series[j].title + ": " + formatRate(self.panels[i]._indicators[s]._indicator._data[j][point]);
}
}
boxBlend(imageData, 10, 10, 210, (legendLines.length * 15) + 10, 25, 25, 25, 60);// 0xFF);
for (var s=0; s < legendLines.length; s++) {
rasterText(imageData, legendLines[s] , 12, 15 * (s+1));
}
// copy the image data back onto the canvas
context.putImageData(imageData, 0, 0);
legendLines = [];
}
};
Rocketchart.prototype.clearHUD = function(){
for (var i=0; i < this.panelOverlays.length; i++) {
// This clears the canvas:
var context = this.panelOverlays[i].getContext("2d");
context.clearRect(0,0,this.panelOverlays[i].width,this.panelOverlays[i].height);
// Hacky way, slower except in earlier canvas implementations:
//this.panelOverlays[i].setAttribute("width", this.panelOverlays[i].width);
}
};
/**
* Adds a canvas to our root element and tracks it in our panels array
* @alias rocketcharts.addPanel()
* @return {int} The ID of the panel that was added
* @method
*/
Rocketchart.prototype.addPanel = function(){
var calcHeight = 0;
var calcY = 0;
var panelID = this.panels.length;
var panelHeightPercent = 1 / (panelID + 1);
var actualHeight = panelHeightPercent * this.element.height();
if (actualHeight < this.settings.minimumPanelHeight) {
actualHeight = this.settings.minimumPanelHeight;
}
var panelsElement = $("#panels", this.element);
for (var i=0; i < this.panels.length; i++) {
/*
if (this.panels[i]._userHeight <= 1){
calcHeight = this.panels[i]._userHeight * h;
} else {
calcHeight = this.panels[i]._userHeight;
}
if (calcHeight < this.settings.minimumPanelHeight) {
calcHeight = this.settings.minimumPanelHeight;
}
*/
// update the width and height of the canvas
this.panels[i]._canvas.setAttribute("height", actualHeight);
calcY += actualHeight;
}
// this.element.append
panelsElement.append('<canvas style="padding: 0px; margin: 0px; z-index: 0; position: absolute; left: 0px; top: ' + calcY + 'px;" id="panel' + panelID + '" width="' + (this.element.width() - 20) + '" height="' + actualHeight + '">rocketchart panel</canvas>');
this.panels[panelID] = new Rocketpanel($('#panel' + panelID, this.element).get(0), actualHeight, this);
panelsElement.append('<canvas style="padding: 0px; margin: 0px; z-index: 1; position: absolute; left: 0px; top: ' + calcY + 'px;" id="panelOverlay' + panelID + '" width="' + (this.element.width() - 20) + '" height="' + actualHeight + '">rocketchart panel</canvas>');
this.panelOverlays[panelID] = $("#panelOverlay" + panelID, this.element).get(0);
return panelID;
};
Rocketchart.prototype.options = function() {
}
/**
* Adds a new primary series to the chart
* @alias rocketcharts.addSeries(title, data, type, panel)
* @param {string} title The string identifier for this series
* @param {Array} data Array of {Object}s with the properties: Open, High, Low, Close, Date
* @param {int} type Enum identifier describing chart type
* @param {Object} style Object containing colors, line thickness, transparency, etc...
* @param {int} panel ID of the panel to add the series to
* @return {void}
* @method
*/
Rocketchart.prototype.addSeries = function(title, data, type, style, panel){
var self = this;
var panelID = -1;
var panelHeight = -1;
panelID = panel || self.addPanel();
if (data === undefined){
data = GeneratePriceHistory();
} else {
// TODO: Verify the integrity of the data before blindly accepting it.
}
type = type || 'candlesticks';// Default to candlesticks
// Keep track of all series data in a root array for quick lookups
self.data.push({title: title, data: data});
self.panels[panelID].addSeries(new Rocketseries(self.data[self.data.length - 1].data, type, title, style, self));
self.view.startingPoint = Math.round(data.length / 2);
self.view.endingPoint = data.length;
self.draw();
};
/**
* Adds a new indicator to the chart
* @alias rocketcharts.addIndicator(id, params, series, panel)
* @param {string} id The string identifier of the indicator to add, i.e. 'simplemovingaverage'
* @param {Array} params The array of user-supplied parameters specific to the indicator
* @param {int} series The id of the series' data we want to calculate this indicator from
* @param {int} panel the id of the panel to add this series to, if undefined, we create a new panel
* @return {int} The ID in the indicatorIndex that points to this indicator
* @method
*/
Rocketchart.prototype.addIndicator = function(id, params, series, panel){
var panelID = -1;
var indicatorID = -1;
if ((panel == undefined) || (panel == -1)){
panelID = this.addPanel();
} else {
panelID = panel;
}
if (series == undefined) {
series = 0;
}
indicatorID = this.panels[panelID].addIndicator(new Rocketindicator(this, id, this.data[series].data, params));
this.indicatorIndex[this.indicatorIndex.length] = {panel: panelID, indicator: indicatorID};
this.refreshPanels();
this.draw();
return (this.indicatorIndex.length - 1);
};
Rocketchart.prototype.removeIndicator = function(id) {
this.panels[this.indicatorIndex[id].panel]._indicators.splice(this.indicatorIndex[id].indicator, 1);
this.indicatorIndex.splice(id, 1);
this.refreshPanels();
this.draw();
};
Rocketchart.prototype.refreshPanels = function() {
var self = this,
i = 0,
simpleHeight = 0;
// Check panels:
for (i=0; i < self.panels.length; i++) {
// Remove if empty:
if ((self.panels[i]._series.length == 0) && (self.panels[i]._indicators.length == 0)) {
$(self.panels[i]._canvas).remove();
$(self.panelOverlays[i]).remove();
self.panels.splice(i, 1);
self.panelOverlays.splice(i, 1);
// Set the iterator back one to account for the shift taking place in the arrays
i--;
}
}
// Resize panels:
simpleHeight = Math.floor(self.element.height() / self.panels.length) - 1;
if (simpleHeight < this.settings.minimumPanelHeight) {
simpleHeight = this.settings.minimumPanelHeight;
}
for (i=0; i < self.panels.length; i++) {
// update the width and height of the canvas
self.panels[i]._canvas.setAttribute("height", simpleHeight);
self.panels[i]._canvas.style.top = simpleHeight * i;
self.panelOverlays[i].setAttribute("height", simpleHeight);
self.panelOverlays[i].style.top = simpleHeight * i;
}
}
/**
* Beginning of a chain of function calls to draw chart - creates image data for each canvas
* we are tracking, in turn passes that imageData to each panel in our array for drawing
* @alias rocketcharts.draw()
* @return {void}
* @method
*/
Rocketchart.prototype.draw = function(){
var self = this;
var height = 0;
var displayedPoints = self.view.endingPoint - self.view.startingPoint;
var dateAxisWidth = self.width - self.priceAxisWidth;
self.view.horizontalPixelsPerPoint = dateAxisWidth / displayedPoints;
self.view.halfHorizontalPixelsPerPoint = Math.round(self.view.horizontalPixelsPerPoint / 2.0) - 1;
// Draw panels:
for (var i=0; i < self.panels.length; i++) {
// grab the datacontext of the canvas
var context = self.panels[i]._canvas.getContext("2d");
// read the height of the canvas
height = parseInt(self.panels[i]._canvas.getAttribute("height"));
if (self.settings.debug) {
console.log("draw called, width: " + self.width + " height: " + height);
}
// create a new pixel array
var imageData = context.createImageData(self.width, height);
self.panels[i].draw(imageData, self.width - self.priceAxisWidth);
// copy the image data back onto the canvas
context.putImageData(imageData, 0, 0);
}
// Draw date axis:
var context = self.dateAxisCanvas.getContext("2d");
var imageData = context.createImageData(self.width, 15);
// Take the last date string, calculate it's width in pixels
// TODO: Perhaps calculate the average length to avoid one-off long or short strings?
var averageDateSpace = (self.data[0].data[displayedPoints - 1].date.length * 6) + 20;
var minorStep = 4;
var majorStep = Math.ceil(averageDateSpace / (minorStep * self.view.horizontalPixelsPerPoint));
var k = 0;
var tickCount = 0;
for (var i=1; i < displayedPoints; i++) {
if (i % minorStep == 0) {
k = (i * self.view.horizontalPixelsPerPoint) + self.view.halfHorizontalPixelsPerPoint;
line(imageData, k, 0, k, 1, 100, 100, 100, 0xFF);
tickCount++;
if (tickCount % majorStep == 0) {
//k = i * horizontalPixelsPerPoint;
line(imageData, k, 0, k, 3, 255,255,255, 0xFF);
//rasterText(imageData, this.data[0].data[i].date, k - 60, 6);
rasterText(imageData, self.data[0].data[self.view.startingPoint + i].date, k - (averageDateSpace / 2) + 10, 6);
}
}
}
context.putImageData(imageData, 0, 0);
};
/**
* Utility function exposed to indicators allowing quick calculation of an SMA on any dataset
* @alias Rocketindicatorcalculations.calculateSMA(periods, data);
* @param {int} periods
* @param {Array} data The array of data to calculate SMA from...
* @return {Array}
* @method
*/
Rocketchart.prototype.calculateSMA = function(periods, data) {
var count = data.length;
var returnArray = [];
var total = 0;
for (var j = 0; j<count; j++)
{
returnArray[j] = null;
}
var startIndex = 0;
for (var k = 0; k < count; k++)
{
if (data[k] != null)
{
startIndex = k + periods;
break;
}
}
for (var i = startIndex; i < count; i++)
{
for (var j = 0; j < periods; j++)
{
total += data[i - j];
}
returnArray[i] = total / periods;
total = 0;
}
return returnArray;
};
/**
* Base class for our series
* @alias new rocketseries(data, type, title)
* @param {Array} data Array of OHLC data
* @param {string} type The string identifier of the series type enum
* @param {string} title The string identifier for this series
* @param {Object} style Object containing series draw thickness, colors, transparency, etc...
* @return {bool}
* @method
*/
function Rocketseries(data, type, title, style, rocketchart){
this.data = data;
this.type = type;
this.title = title;
this.style = style || {};
this.rocketchart = rocketchart;
this.style.UpColor = this.style.UpColor || rocketchart.settings.defaultUpColor;
this.style.DownColor = this.style.DownColor || rocketchart.settings.defaultDownColor;
return true;
}
/**
* Switches between series type and calls subsequent draw methods
* @alias rocketseries.draw(imageData, verticalPixelPerPoint, gridMin, w, h)
* @param {Array} imageData Array of pixel data
* @param {float} verticalPixelPerPoint The amount of pixels that represent one value point
* @param {float} gridMin The low end value of the chart
* @param {int} w Width of panel
* @param {int} h Height of panel
* @return {bool}
* @method
*/
Rocketseries.prototype.draw = function(imageData, verticalPixelPerPoint, gridMin, w, h){
this[this.type].apply(this, arguments);//type === function name. apply passes all the same arguments.
};
Rocketseries.prototype.candlesticks = function(imageData, verticalPixelPerPoint, gridMin, w, h){
var yCloseOld = 0;
var valueOpen;
var valueHigh;
var valueLow;
var valueClose;
var yvalueOpen;
var yvalueHigh;
var yvalueLow;
var yvalueClose;
var horizSpacing = this.rocketchart.view.horizontalPixelsPerPoint;
var halfhorizSpacing = this.rocketchart.view.halfHorizontalPixelsPerPoint;
var lineAreaStart = h;
var X = halfhorizSpacing;
var i = 0;
for (i = this.rocketchart.view.startingPoint; i < this.rocketchart.view.endingPoint; i++) //dataCount
{
if ( this.data[i]["empty"] != true ) // Null means a market gap
{
valueOpen = this.data[i]["open"];
valueHigh = this.data[i]["high"];
valueLow = this.data[i]["low"];
valueClose = this.data[i]["close"];
yvalueOpen = lineAreaStart - (verticalPixelPerPoint * (valueOpen - gridMin));
yvalueHigh = lineAreaStart - (verticalPixelPerPoint * (valueHigh - gridMin));
yvalueLow = lineAreaStart - (verticalPixelPerPoint * (valueLow - gridMin));
yvalueClose = lineAreaStart - (verticalPixelPerPoint * (valueClose - gridMin));
if (valueOpen < valueClose)
{
line(imageData, X, yvalueHigh, X, yvalueLow, this.style.UpColor.r, this.style.UpColor.g, this.style.UpColor.b, 0xff);
box(imageData, X-halfhorizSpacing, yvalueClose, X+halfhorizSpacing, yvalueOpen, this.style.UpColor.r, this.style.UpColor.g, this.style.UpColor.b, 0xff, false);
}
else
{
line(imageData, X, yvalueHigh, X, yvalueLow, this.style.DownColor.r, this.style.DownColor.g, this.style.DownColor.b, 0xff);
box(imageData, X-halfhorizSpacing, yvalueOpen, X+halfhorizSpacing, yvalueClose, this.style.DownColor.r, this.style.DownColor.g, this.style.DownColor.b, 0xff, false);
}
}
X += horizSpacing;
}
};
function Rocketpanel(canvas, height, rocketchart){
this._canvas = canvas;
this._gridMax = -100000;
this._gridMin = 100000;
this._series = [];
this._indicators = [];
this._height = 0;
this._verticalPixelsPerPoint = 0;
this._userHeight = height || .50;// Default to 50% - the formula is: if userHeight <= 1, it's percentage, else it's pixels
this.rocketchart = rocketchart;
return true;
}
Rocketpanel.prototype.draw = function(imageData, w){
this.calculate();
// Draw axis/grid:
var valueAtPoint = 0;
var yValue = 0;
var oldY = 0;
for (var i=1; i < 10; i++) {
yValue = this._canvas.height - (this._verticalPixelsPerPoint * (i * this._gridStep));
valueAtPoint = ((i * this._gridStep) + this._gridMin);
rasterText(imageData, valueAtPoint.toFixed(4), w + 5, yValue - 3);
//line(imageData, w, yValue, w + 3, yValue, 255,255,255,0xFF);
if ((i % 2) == 0) {
box(imageData, 0, yValue, w, oldY, 45, 45, 45, 0xFF);
}
oldY = yValue;
}
var legendLines = [];
// Draw series
for (var i=0; i < this._series.length; i++) {
this._series[i].draw(imageData, this._verticalPixelsPerPoint, this._gridMin, w, this._height);
legendLines.push(this._series[i].title);
}
// Draw indicators
for (var i=0; i < this._indicators.length; i++) {
this._indicators[i].draw(imageData, this._verticalPixelsPerPoint, this._gridMin, w, this._height);
for (var j=0; j < this._indicators[i]._indicator._series.length; j++) {
legendLines.push(this._indicators[i]._indicator._series[j].title);
}
}
boxBlend(imageData, 10, 10, 210, (legendLines.length * 15) + 10, 25, 25, 25, 60);// 0xFF);
for (var i=0; i < legendLines.length; i++) {
rasterText(imageData, legendLines[i] , 12, 15 * (i+1));
}
};
Rocketpanel.prototype.addSeries = function(series){
this._series.push(series);
};
Rocketpanel.prototype.addIndicator = function(indicator){
this._indicators.push(indicator);
return (this._indicators.length - 1);
};
Rocketpanel.prototype.calculate = function(){
this._height = $(this._canvas).attr("height");
this._gridMax = -100000;
this._gridMin = 100000;
var value = 0;
for (var i=0; i < this._series.length; i++)
{
//var len = this._series[i].data.length; //_sizing.StartingTick + _sizing.VisibleTicks;
//var startValue = 0;//_sizing.StartingTick;
for (var j = this.rocketchart.view.startingPoint; j < this.rocketchart.view.endingPoint; j++)
{
if (this._series[i].data[j]["high"] > this._gridMax)
this._gridMax = this._series[i].data[j]["high"];
if (this._series[i].data[j]["low"] < this._gridMin)
this._gridMin = this._series[i].data[j]["low"];
}
}
for (var i=0; i < this._indicators.length; i++)
{
for (var j=0; j < this._indicators[i]._indicator._series.length; j++){
//var len = this._indicators[i]._indicator._data[j].length; //_sizing.StartingTick + _sizing.VisibleTicks;
//var startValue = 0;//_sizing.StartingTick;
for (var k = this.rocketchart.view.startingPoint; k < this.rocketchart.view.endingPoint; k++){
value = this._indicators[i]._indicator._data[j][k];
if (value != null) {
if (value > this._gridMax)
this._gridMax = value;
if (value < this._gridMin)
this._gridMin = value;
}
}
}
}
this._gridStep = (this._gridMax - this._gridMin) / 10;
this._gridMin -= (this._gridStep * .25);
this._gridMax += (this._gridStep * .25);
this._gridStep = (this._gridMax - this._gridMin) / 10;
this._verticalPixelsPerPoint = this._height / (this._gridMax - this._gridMin);
if (this.rocketchart.settings.debug) {
console.log("Calculate called, _height: " + this._height + ", _verticalPixelsPerPoint: " + this._verticalPixelsPerPoint)
}
};
// id = lookup in public indicator array
function Rocketindicator(rocketchart, id, data, params, series){
// lookup the right function (object) to create based on the id and pass it the data
var calc = new Rocketindicatorcalculations();
this.rocketchart = rocketchart;
this._indicator = new calc[id](data, params, series);
// TODO: Better lookup?
for(var i=0; i<rocketchart.indicators.length; i++) {
if (rocketchart.indicators[i].id == id) {
this.name = rocketchart.indicators[i].name;
break;
}
}
}
Rocketindicator.prototype.draw = function(imageData, verticalPixelPerPoint, gridMin, w, h){
for(var i=0; i<this._indicator._series.length; i++){
this[this._indicator._series[i].type](imageData, verticalPixelPerPoint, gridMin, w, h, i);
}
var yValue = 0;
if (this._indicator._constantLines != undefined) {
for (var i=0; i<this._indicator._constantLines.length; i++) {
yValue = h - (verticalPixelPerPoint * (this._indicator._constantLines[i].value - gridMin));
line(imageData, 0, yValue, w, yValue, 255, 255, 255, 255, 1);
}
}
};
Rocketindicator.prototype.line = function(imageData, verticalPixelPerPoint, gridMin, w, h, s){
var indicatorData = this._indicator._data;
var seriesLength = 0;
var lastValue = 0;
var lastValueOld = 0;
var i = 0;
var horizSpacing = this.rocketchart.view.horizontalPixelsPerPoint;
var halfhorizSpacing = this.rocketchart.view.halfHorizontalPixelsPerPoint;
var barHeight = 0;
var X = halfhorizSpacing;
var smoothing = false; //Preferences.EnableSmoothing;
seriesLength = indicatorData[s].length;
var seriesColor = hexToRgb(intToHex(this._indicator._series[s].color));
// ENSURE COLOR is 100% ALPHA:
/*
var c = indicator.seriesColor(s);
var r1:uint= ((c & 0x00FF0000) >> 16);
var g1:uint= ((c & 0x0000FF00) >> 8);
var b1:uint= ((c & 0x000000FF));
var ac:Number=0xFF;
var n:uint=(ac<<24)+(r1<<16)+(g1<<8)+b1;
*/
for (i = this.rocketchart.view.startingPoint; i < this.rocketchart.view.endingPoint; i++)
{
if (indicatorData[s][i] != null)
{
lastValue = h - (verticalPixelPerPoint * (indicatorData[s][i] - gridMin));
if (lastValueOld != 0)
{
if (smoothing)
{
//Raster.aaLine(bd, X - _sizing.HorizontalPixelsPerPoint, lastValueOld, X, lastValue, n);
}
else
{
line(imageData, X - horizSpacing, lastValueOld, X, lastValue, seriesColor.r, seriesColor.g, seriesColor.b, 255, 2);
}
lastValue = h - (verticalPixelPerPoint * (indicatorData[s][i] - gridMin));
}
lastValueOld = lastValue;
}
X += horizSpacing;
}
};
Rocketindicator.prototype.dot = function(imageData, verticalPixelPerPoint, gridMin, w, h, s){
var indicatorData = this._indicator._data;
var seriesLength = 0;
var lastValue = 0;
var lastValueOld = 0;
var i = 0;
var horizSpacing = this.rocketchart.view.horizontalPixelsPerPoint;
var halfhorizSpacing = this.rocketchart.view.halfHorizontalPixelsPerPoint;
var X = halfhorizSpacing;
seriesLength = indicatorData[s].length;
var seriesColor = hexToRgb(intToHex(this._indicator._series[s].color));
for (i = this.rocketchart.view.startingPoint; i < this.rocketchart.view.endingPoint; i++)
{
if (indicatorData[s][i] != null)
{
lastValue = h - (verticalPixelPerPoint * (indicatorData[s][i] - gridMin));
box(imageData, X - 1, lastValue - 1, X, lastValue, seriesColor.r, seriesColor.g, seriesColor.b, 255);
}
X += horizSpacing;
}
};
Rocketindicator.prototype.histogram = function(imageData, verticalPixelPerPoint, gridMin, w, h, s){
var indicatorData = this._indicator._data;
var seriesCount = indicatorData.length;
var seriesLength = 0;
var lastValue = 0;
var i = 0;
var x = 0;
var horizSpacing = this.rocketchart.view.horizontalPixelsPerPoint;
var halfhorizSpacing = this.rocketchart.view.halfHorizontalPixelsPerPoint;
var barHeight = 0;
var counter = halfhorizSpacing;
var smoothing = false; //Preferences.EnableSmoothing;
seriesLength = indicatorData[s].length;
var seriesColor = hexToRgb(intToHex(this._indicator._series[s].color));
// ENSURE COLOR is 100% ALPHA:
/*
var c = indicator.seriesColor(s);
var r1:uint= ((c & 0x00FF0000) >> 16);
var g1:uint= ((c & 0x0000FF00) >> 8);
var b1:uint= ((c & 0x000000FF));
var ac:Number=0xFF;
var n:uint=(ac<<24)+(r1<<16)+(g1<<8)+b1;
*/
for (i = this.rocketchart.view.startingPoint; i < this.rocketchart.view.endingPoint; i++)
{
if (indicatorData[s][i] != null)
{
/**
* Optimizing code; Math.abs is slow, using bitwise is fast
* Note: This only works with integer math; thus, the optimizations are
* used in drawing code, where the result will need to be int's anyways
* */
/** Original code: **/
// barHeight = verticalPixelPerPoint * (Math.abs(indicatorData[s][i]));
/** Optimized code: **/
barHeight = indicatorData[s][i] * verticalPixelPerPoint;
x = barHeight;
barHeight = ((x ^ (x >> 31)) - (x >> 31));
if (barHeight == 0)
barHeight++;
if (indicatorData[s][i] > 0)
{
box(imageData,
counter - halfhorizSpacing + 1,
h - (verticalPixelPerPoint * (indicatorData[s][i] - gridMin)),
counter + halfhorizSpacing - 1,
h - (verticalPixelPerPoint * (0 - gridMin)),
seriesColor.r, seriesColor.g, seriesColor.b,
0xFF,
false);
}
else
{
box(imageData,
counter - halfhorizSpacing + 1,
h - (verticalPixelPerPoint * (0 - gridMin)),
counter + halfhorizSpacing - 1,
h - (verticalPixelPerPoint * (0 - gridMin)) + barHeight,
seriesColor.r, seriesColor.g, seriesColor.b,
0xFF,
false);
}
}
counter += horizSpacing;
}
};
/**
* Create a new framework of utility functions.
* @classDescription Creates a new framework of utility functions.
* @type {Object}
* @return {Boolean} Returns true.
* @constructor
*/
function Rocketindicatorcalculations() {
return true;
}
/**
* Accept an array of OHLC data and an array of parameters, then performs the simple moving average calculation.
* @alias MHUtils.objConvert(arr)
* @param {Array} data The array of OHLC data
* @param {Array} params The array of user-supplied parameters
* @return {Object} Returns the indicator data
* @method
*/
Rocketindicatorcalculations.prototype.simplemovingaverage = function (data, params, series) {
this._params = params;
this._series = series;
this._sourceData = data;
this._data = [];
this._series = this._series || [{type: 'line', title: "SMA", color: 0xFF0000}];
this._params = this._params || [{name: 'Periods', type: 'numeric', value: 9, step: 1, min: 1, max: 100}];
this.calculate = function(){
if (this._sourceData != null) {
var total = 0;
var j = 0;
var count = this._sourceData.length;
this._data = [];
for (var i = 0; i<this._series.length; i++){
this._data[i] = [];
}