C#利用開源NPlot實現K線圖(蠟燭圖)
阿新 • • 發佈:2019-01-31
NPlot是.Net平臺下開源的圖表控制元件,包括K線圖、柱狀圖、餅圖、曲線圖、散點圖等。這裡主要講講怎麼利用NPlot實現股票K線圖。NPlot中PlotSurface2D物件是整個NPlot的圖表的容器,所有的圖表都需要新增到PlotSurface2D中才能進行顯示。在WinForm程式中我們引用的是Windows.PlotSurface2D類,此類整合自Control。這裡利用的K線圖資料來自OKEX比特幣交易的日線資料。主要包括時間、開盤價、最高價、最低價、收盤價等資料。資料儲存資料庫中的,Nplot提供資料來源繫結功能,通過資料庫查詢查出的DataTable物件可以直接繫結到蠟燭物件上。
PlotSurface2D初始化:
private void InitKLinePS() { KLinePS = new NPlot.Windows.PlotSurface2D(); this.KLinePS.AutoScaleAutoGeneratedAxes = true; this.KLinePS.AutoScaleTitle = false ; this.KLinePS.DateTimeToolTip = true; this.KLinePS.DateTimeToolTip = true; this.KLinePS.Legend = null; this.KLinePS.LegendZOrder = -1; this.KLinePS.Location = new System.Drawing.Point(0, 0); this.KLinePS.Name = "costPS"; this.KLinePS.RightMenu = null; this.KLinePS.Padding = 10; //滑鼠tooltips 時間+價格 this.KLinePS.ShowCoordinates = true; this.KLinePS.Size = new System.Drawing.Size(969, 595); this.KLinePS.Width = 1300; this.KLinePS.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; this.KLinePS.TabIndex = 2; this.KLinePS.Title = "123"; this.KLinePS.TitleFont = new System.Drawing.Font("Arial", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); }
SetCandlePlot方法為類的外部呼叫方法,包括K線資料查詢、CandlePlot物件建立、資料來源繫結及把CandlePlot物件新增到PlotSurface2D中去,最後通過PlotSurface2D的Refresh重新整理顯示。
public void SetCandlePlot(string klineTable, string startTime, string endTime, Dictionary<int, GridStrategyEntity> dicGridStrategyEntity, DataTable backTestResult) { string sql; dicAutoGridStrategy = dicGridStrategyEntity; this.backTestResult = backTestResult; backTestStartTime = startTime; backTestEndTime = endTime; // dealedCount = 0; sql = "select * from " + klineTable + "kline where datetime>#" + startTime + "#" + " and datetime<#" + endTime + "# order by datetime asc"; DataTable dt = oleDbHelper.queryDataForDataTable(sql); CandlePlot cp = new CandlePlot(); cp.DataSource = dt; cp.AbscissaData = "datetime"; cp.OpenData = "open"; cp.LowData = "low"; cp.HighData = "high"; cp.CloseData = "close"; cp.Label = "蠟燭圖"; //開跌色 cp.BearishColor = System.Drawing.Color.FromArgb(255, 255, 0, 0); //看漲色 cp.BullishColor = System.Drawing.Color.FromArgb(255, 0, 255, 0); cp.Style = CandlePlot.Styles.Filled; //K線寬度 cp.StickWidth = 4; this.KLinePS.Add(cp); //隱藏日期刻度標示 this.KLinePS.XAxis1.HideTickText = true ; this.KLinePS.Refresh(); }