Candlesticks.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.charting.plot2d.Candlesticks"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.charting.plot2d.Candlesticks"] = true;
  8. dojo.provide("dojox.charting.plot2d.Candlesticks");
  9. dojo.require("dojox.charting.plot2d.common");
  10. dojo.require("dojox.charting.plot2d.Base");
  11. dojo.require("dojox.lang.utils");
  12. dojo.require("dojox.lang.functional");
  13. dojo.require("dojox.lang.functional.reversed");
  14. (function(){
  15. var df = dojox.lang.functional, du = dojox.lang.utils,
  16. dc = dojox.charting.plot2d.common,
  17. purgeGroup = df.lambda("item.purgeGroup()");
  18. // Candlesticks are based on the Bars plot type; we expect the following passed
  19. // as values in a series:
  20. // { x?, open, close, high, low, mid? }
  21. // if x is not provided, the array index is used.
  22. // failing to provide the OHLC values will throw an error.
  23. dojo.declare("dojox.charting.plot2d.Candlesticks", dojox.charting.plot2d.Base, {
  24. // summary:
  25. // A plot that represents typical candlesticks (financial reporting, primarily).
  26. // Unlike most charts, the Candlestick expects data points to be represented by
  27. // an object of the form { x?, open, close, high, low, mid? }, where both
  28. // x and mid are optional parameters. If x is not provided, the index of the
  29. // data array is used.
  30. defaultParams: {
  31. hAxis: "x", // use a horizontal axis named "x"
  32. vAxis: "y", // use a vertical axis named "y"
  33. gap: 2, // gap between columns in pixels
  34. animate: null // animate bars into place
  35. },
  36. optionalParams: {
  37. minBarSize: 1, // minimal candle width in pixels
  38. maxBarSize: 1, // maximal candle width in pixels
  39. // theme component
  40. stroke: {},
  41. outline: {},
  42. shadow: {},
  43. fill: {},
  44. font: "",
  45. fontColor: ""
  46. },
  47. constructor: function(chart, kwArgs){
  48. // summary:
  49. // The constructor for a candlestick chart.
  50. // chart: dojox.charting.Chart2D
  51. // The chart this plot belongs to.
  52. // kwArgs: dojox.charting.plot2d.__BarCtorArgs?
  53. // An optional keyword arguments object to help define the plot.
  54. this.opt = dojo.clone(this.defaultParams);
  55. du.updateWithObject(this.opt, kwArgs);
  56. du.updateWithPattern(this.opt, kwArgs, this.optionalParams);
  57. this.series = [];
  58. this.hAxis = this.opt.hAxis;
  59. this.vAxis = this.opt.vAxis;
  60. this.animate = this.opt.animate;
  61. },
  62. collectStats: function(series){
  63. // summary:
  64. // Collect all statistics for drawing this chart. Since the common
  65. // functionality only assumes x and y, Candlesticks must create it's own
  66. // stats (since data has no y value, but open/close/high/low instead).
  67. // series: dojox.charting.Series[]
  68. // The data series array to be drawn on this plot.
  69. // returns: Object
  70. // Returns an object in the form of { hmin, hmax, vmin, vmax }.
  71. // we have to roll our own, since we need to use all four passed
  72. // values to figure out our stats, and common only assumes x and y.
  73. var stats = dojo.delegate(dc.defaultStats);
  74. for(var i=0; i<series.length; i++){
  75. var run = series[i];
  76. if(!run.data.length){ continue; }
  77. var old_vmin = stats.vmin, old_vmax = stats.vmax;
  78. if(!("ymin" in run) || !("ymax" in run)){
  79. dojo.forEach(run.data, function(val, idx){
  80. if(val !== null){
  81. var x = val.x || idx + 1;
  82. stats.hmin = Math.min(stats.hmin, x);
  83. stats.hmax = Math.max(stats.hmax, x);
  84. stats.vmin = Math.min(stats.vmin, val.open, val.close, val.high, val.low);
  85. stats.vmax = Math.max(stats.vmax, val.open, val.close, val.high, val.low);
  86. }
  87. });
  88. }
  89. if("ymin" in run){ stats.vmin = Math.min(old_vmin, run.ymin); }
  90. if("ymax" in run){ stats.vmax = Math.max(old_vmax, run.ymax); }
  91. }
  92. return stats; // Object
  93. },
  94. getSeriesStats: function(){
  95. // summary:
  96. // Calculate the min/max on all attached series in both directions.
  97. // returns: Object
  98. // {hmin, hmax, vmin, vmax} min/max in both directions.
  99. var stats = this.collectStats(this.series);
  100. stats.hmin -= 0.5;
  101. stats.hmax += 0.5;
  102. return stats;
  103. },
  104. render: function(dim, offsets){
  105. // summary:
  106. // Run the calculations for any axes for this plot.
  107. // dim: Object
  108. // An object in the form of { width, height }
  109. // offsets: Object
  110. // An object of the form { l, r, t, b}.
  111. // returns: dojox.charting.plot2d.Candlesticks
  112. // A reference to this plot for functional chaining.
  113. if(this.zoom && !this.isDataDirty()){
  114. return this.performZoom(dim, offsets);
  115. }
  116. this.resetEvents();
  117. this.dirty = this.isDirty();
  118. if(this.dirty){
  119. dojo.forEach(this.series, purgeGroup);
  120. this._eventSeries = {};
  121. this.cleanGroup();
  122. var s = this.group;
  123. df.forEachRev(this.series, function(item){ item.cleanGroup(s); });
  124. }
  125. var t = this.chart.theme, f, gap, width,
  126. ht = this._hScaler.scaler.getTransformerFromModel(this._hScaler),
  127. vt = this._vScaler.scaler.getTransformerFromModel(this._vScaler),
  128. baseline = Math.max(0, this._vScaler.bounds.lower),
  129. baselineHeight = vt(baseline),
  130. events = this.events();
  131. f = dc.calculateBarSize(this._hScaler.bounds.scale, this.opt);
  132. gap = f.gap;
  133. width = f.size;
  134. for(var i = this.series.length - 1; i >= 0; --i){
  135. var run = this.series[i];
  136. if(!this.dirty && !run.dirty){
  137. t.skip();
  138. this._reconnectEvents(run.name);
  139. continue;
  140. }
  141. run.cleanGroup();
  142. var theme = t.next("candlestick", [this.opt, run]), s = run.group,
  143. eventSeries = new Array(run.data.length);
  144. for(var j = 0; j < run.data.length; ++j){
  145. var v = run.data[j];
  146. if(v !== null){
  147. var finalTheme = t.addMixin(theme, "candlestick", v, true);
  148. // calculate the points we need for OHLC
  149. var x = ht(v.x || (j+0.5)) + offsets.l + gap,
  150. y = dim.height - offsets.b,
  151. open = vt(v.open),
  152. close = vt(v.close),
  153. high = vt(v.high),
  154. low = vt(v.low);
  155. if("mid" in v){
  156. var mid = vt(v.mid);
  157. }
  158. if(low > high){
  159. var tmp = high;
  160. high = low;
  161. low = tmp;
  162. }
  163. if(width >= 1){
  164. // draw the line and rect, set up as a group and pass that to the events.
  165. var doFill = open > close;
  166. var line = { x1: width/2, x2: width/2, y1: y - high, y2: y - low },
  167. rect = {
  168. x: 0, y: y-Math.max(open, close),
  169. width: width, height: Math.max(doFill ? open-close : close-open, 1)
  170. };
  171. shape = s.createGroup();
  172. shape.setTransform({dx: x, dy: 0 });
  173. var inner = shape.createGroup();
  174. inner.createLine(line).setStroke(finalTheme.series.stroke);
  175. inner.createRect(rect).setStroke(finalTheme.series.stroke).
  176. setFill(doFill ? finalTheme.series.fill : "white");
  177. if("mid" in v){
  178. // add the mid line.
  179. inner.createLine({
  180. x1: (finalTheme.series.stroke.width||1), x2: width - (finalTheme.series.stroke.width || 1),
  181. y1: y - mid, y2: y - mid
  182. }).setStroke(doFill ? "white" : finalTheme.series.stroke);
  183. }
  184. // TODO: double check this.
  185. run.dyn.fill = finalTheme.series.fill;
  186. run.dyn.stroke = finalTheme.series.stroke;
  187. if(events){
  188. var o = {
  189. element: "candlestick",
  190. index: j,
  191. run: run,
  192. shape: inner,
  193. x: x,
  194. y: y-Math.max(open, close),
  195. cx: width/2,
  196. cy: (y-Math.max(open, close)) + (Math.max(doFill ? open-close : close-open, 1)/2),
  197. width: width,
  198. height: Math.max(doFill ? open-close : close-open, 1),
  199. data: v
  200. };
  201. this._connectEvents(o);
  202. eventSeries[j] = o;
  203. }
  204. }
  205. if(this.animate){
  206. this._animateCandlesticks(shape, y - low, high - low);
  207. }
  208. }
  209. }
  210. this._eventSeries[run.name] = eventSeries;
  211. run.dirty = false;
  212. }
  213. this.dirty = false;
  214. return this; // dojox.charting.plot2d.Candlesticks
  215. },
  216. _animateCandlesticks: function(shape, voffset, vsize){
  217. dojox.gfx.fx.animateTransform(dojo.delegate({
  218. shape: shape,
  219. duration: 1200,
  220. transform: [
  221. {name: "translate", start: [0, voffset - (voffset/vsize)], end: [0, 0]},
  222. {name: "scale", start: [1, 1/vsize], end: [1, 1]},
  223. {name: "original"}
  224. ]
  225. }, this.animate)).play();
  226. }
  227. });
  228. })();
  229. }