public void TestAverage() { MovingAverage avg = new MovingAverage(5); Assert.Equal(4, avg.Push(4)); Assert.Equal(6, avg.Push(8)); Assert.Equal(5, avg.Push(3)); Assert.Equal(5, avg.Push(5)); }
private void InitData(IMarketDataService marketDataService) { var prices = marketDataService.GetHistoricalData(DefaultPointCount); _lastPrice = prices.Last(); // Populate data series with some data _ohlcDataSeries.Append(prices.Select(x => x.DateTime), prices.Select(x => x.Open), prices.Select(x => x.High), prices.Select(x => x.Low), prices.Select(x => x.Close)); _xyDataSeries.Append(prices.Select(x => x.DateTime), prices.Select(y => _sma50.Push(y.Close).Current)); }
private void DoAppendLoop(Random random) { using (Surface.SuspendUpdates()) { _xValues.Clear(); _firstYValues.Clear(); _secondYValues.Clear(); _thirdYValues.Clear(); for (var i = 0; i < BufferSize; i++) { _xValue++; _yValue += random.NextDouble() - 0.5; _xValues.Add(_xValue); _firstYValues.Add((float)_yValue); _secondYValues.Add((float)_maLow.Push(_yValue).Current); _thirdYValues.Add((float)_maHigh.Push(_yValue).Current); } _mainSeries.Append(_xValues, _firstYValues); _maLowSeries.Append(_xValues, _secondYValues); _maHighSeries.Append(_xValues, _thirdYValues); var count = _mainSeries.Count + _maLowSeries.Count + _maHighSeries.Count; var text = "Amount of points: " + count; // need to set text from UI thread to prevent exception _uiThreadHandler.Post(() => { _textView.SetText(text, TextView.BufferType.Normal); }); } }
private void DoAppendLoop() { using (Surface.SuspendUpdates()) { _xValues.Clear(); _firstYValues.Clear(); _secondYValues.Clear(); _thirdYValues.Clear(); for (var i = 0; i < BufferSize; i++) { _xValue++; _yValue += _random.NextDouble() - 0.5; _xValues.Add(_xValue); _firstYValues.Add((float)_yValue); _secondYValues.Add((float)_maLow.Push(_yValue).Current); _thirdYValues.Add((float)_maHigh.Push(_yValue).Current); } _mainSeries.Append(_xValues, _firstYValues); _maLowSeries.Append(_xValues, _secondYValues); _maHighSeries.Append(_xValues, _thirdYValues); _countLabel.Text = "Amount of Points: " + _mainSeries.Count; } }
private void AppendData(int length, double noisyness) { int blocks = length / xBuffer.Length; for (int j = 0; j < blocks; j++) { for (int i = 0; i < xBuffer.Length; i++) { // Generate a new X,Y value in the random walk and buffer var next = _generator.Next(); xBuffer[i] = next.X; yBuffer[i] = next.Y + _rand.NextDouble() * noisyness; // Update moving averages maLowBuffer[i] = _maLow.Push(yBuffer[i]).Current; maHighBuffer[i] = _maHigh.Push(yBuffer[i]).Current; } // Append block of values to all three series _mainSeries.Append(xBuffer, yBuffer); _maLowSeries.Append(xBuffer, maLowBuffer); _maHighSeries.Append(xBuffer, maHighBuffer); } }
private void DataAppendLoop() { // By nesting multiple updates inside a SuspendUpdates using block, you get one redraw at the end using (sciChart.SuspendUpdates()) { // Preload previous value with k-1 sample, or 0.0 if the count is zero int xValue = _mainSeries.Count > 0 ? _mainSeries.XValues[_mainSeries.Count - 1] : 0; double yValue = _mainSeries.Count > 0 ? _mainSeries.YValues[_mainSeries.Count - 1] : 10.0f; // Add N points at a time. We want to get to the higher point counts // quickly to demonstrate performance. // Also, it is more efficient to buffer and block update the chart // even if you use SuspendUpdates due to the overhead of calculating min, max // for a series for (int i = 0; i < BufferSize; i++) { // Generate a new X,Y value in the random walk and buffer xValue = xValue + 1; yValue = (double)(yValue + (_random.NextDouble() - 0.5)); xBuffer[i] = xValue; yBuffer[i] = (float)yValue; // Update moving averages maLowBuffer[i] = (float)_maLow.Push(yValue).Current; maHighBuffer[i] = (float)_maHigh.Push(yValue).Current; } // Append block of values to all three series _mainSeries.Append(xBuffer, yBuffer); _maLowSeries.Append(xBuffer, maLowBuffer); _maHighSeries.Append(xBuffer, maHighBuffer); } }
private void OnSciChartRendered(object sender, EventArgs e) { // Compute the render time double frameTime = _stopWatch.ElapsedMilliseconds; double delta = frameTime - _lastFrameTime; double fps = 1000.0 / delta; double fpsAverageBefore = _fpsAverage.Current; // Push the fps to the movingaverage, we want to average the FPS to get a more reliable reading if (!double.IsInfinity(fps)) { _fpsAverage.Push(fps); } double fpsAverageAfter = _fpsAverage.Current; // Render the fps to the screen if (Math.Abs(fpsAverageAfter - fpsAverageBefore) >= 0.1) { FpsCounter.Text = double.IsNaN(_fpsAverage.Current) ? "-" : string.Format("{0:0}", _fpsAverage.Current); } // Render the total point count (all series) to the screen int numPoints = 3 * _mainSeries.Count; PointCount.Text = string.Format("{0:n0}", numPoints); if (numPoints > MaxCount) { this.PauseButton_Click(this, null); } _lastFrameTime = frameTime; }
public static IEnumerable <double> MovingAverage <T>(this IEnumerable <T> inputStream, Func <T, double> selector, int period) { var ma = new MovingAverage(period); foreach (var item in inputStream) { ma.Push(selector(item)); yield return(ma.Current); } }
public static IEnumerable <double> MovingAverage(this IEnumerable <double> inputStream, int period) { var ma = new MovingAverage(period); foreach (var item in inputStream) { ma.Push(item); yield return(ma.Current); } }
public CreateRealTimeTickingStockChartViewModel() { _seriesViewModels = new ObservableCollection <IRenderableSeriesViewModel>(); // Market data service simulates live ticks. We want to load the chart with 150 historical bars // then later do real-time ticking as new data comes in _marketDataService = new MarketDataService(new DateTime(2000, 08, 01, 12, 00, 00), 5, 20); // Add ChartSeriesViewModels for the candlestick and SMA series var ds0 = new OhlcDataSeries <DateTime, double> { SeriesName = "Price Series" }; _seriesViewModels.Add(new OhlcRenderableSeriesViewModel { DataSeries = ds0, StyleKey = "BaseRenderableSeriesStyle" }); var ds1 = new XyDataSeries <DateTime, double> { SeriesName = "50-Period SMA" }; _seriesViewModels.Add(new LineRenderableSeriesViewModel { DataSeries = ds1, StyleKey = "LineStyle" }); // Append 150 historical bars to data series var prices = _marketDataService.GetHistoricalData(100); ds0.Append( prices.Select(x => x.DateTime), prices.Select(x => x.Open), prices.Select(x => x.High), prices.Select(x => x.Low), prices.Select(x => x.Close)); ds1.Append(prices.Select(x => x.DateTime), prices.Select(y => _sma50.Push(y.Close).Current)); SelectedSeriesStyle = "Ohlc"; }
private void ComRec(byte[] data) { int length = this.recStringBuilder.Length; int idx = 0; if (data == null) { return; } var datas = SerialProtocolParseHelper.Parse(data); Console.WriteLine(string.Join(",", datas) + "\r\n"); if (datas.Contains(calibrate)) { return; } var ds = Constant.solver2D.Update(datas.Select <long, double>(x => x).ToList()); Console.WriteLine(string.Join(",", ds) + "\r\n"); bool flag = false; if (Math.Abs(Global.Position[0] - ds[0] / 1000) > tolerance || double.IsNaN(Global.Position[0]) || XMovingAverage.Length < ringLength) { XMovingAverage.Push(ds[0]); Global.Position[0] = XMovingAverage.Current / 1000; flag = true; } if (Math.Abs(Global.Position[1] - ds[1] / 1000) > tolerance || double.IsNaN(Global.Position[1]) || YMovingAverage.Length < ringLength) { YMovingAverage.Push(ds[1]); Global.Position[1] = YMovingAverage.Current / 1000; flag = true; } if (flag) { Constant.DrawingHelper.Update(Global.Position[0] * 1000, Global.Position[1] * 1000); } Global.Position[2] = refHeight / 1000; SerialDataReceived?.Invoke(this, string.Join(",", ds) + "\r\n"); }
public void TestDifferentWindowSizes(int iSize) { MovingAverage m_Avg = new MovingAverage(iSize); Queue <long> queue = new Queue <long>(); Random random = new Random(0); for (int i = 0; i < 10 * iSize; ++i) { int value = random.Next(); queue.Enqueue(value); if (queue.Count > iSize) { queue.Dequeue(); } Assert.True(0.0001 > Math.Abs(queue.Average() - m_Avg.Push(value))); } }
public void Update(TimeSpan frameTime) { ++iCounter; OnTick.Set(); lock (Lock) { } if (m_Timer == null) { m_Timer = Stopwatch.StartNew(); } else { AverageTicksPerFrame.Push(m_Timer.ElapsedTicks); m_Timer.Restart(); } }
public void TestDifferentWindowSizes(int iSize) { MovingAverage m_Avg = new MovingAverage(iSize); Queue <long> queue = new Queue <long>(); Random random = new Random(0); for (int i = 0; i < 10 * iSize; ++i) { long value = random.Next(); queue.Enqueue(i); if (queue.Count > iSize) { queue.Dequeue(); } Assert.Equal(queue.Average(), m_Avg.Push(i)); } }
/// <summary> /// Purely for stats reporting (FPS). Not needed for SciChart rendering /// </summary> private void CompositionTarget_Rendering(object sender, EventArgs e) { // Compute the render time double frameTime = _stopWatch.ElapsedMilliseconds; double delta = frameTime - _lastFrameTime; double fps = 1000.0 / delta; // Push the fps to the movingaverage, we want to average the FPS to get a more reliable reading _fpsAverage.Push(fps); // Render the fps to the screen fpsCounter.Text = _fpsAverage.Current == double.NaN ? "-" : string.Format("{0:0}", _fpsAverage.Current); // Render the total point count (all series) to the screen var eegExampleViewModel = (DataContext as EEGExampleViewModel); pointCount.Text = eegExampleViewModel != null?eegExampleViewModel.PointCount.ToString() : "Na"; _lastFrameTime = frameTime; }
private void DoAppendLoop() { _xValues.Clear(); _firstYValues.Clear(); _secondYValues.Clear(); _thirdYValues.Clear(); for (var i = 0; i < BufferSize; i++) { _xValue++; _yValue += _random.NextDouble() - 0.5; _xValues.Add(_xValue); _firstYValues.Add((float)_yValue); _secondYValues.Add((float)_maLow.Push(_yValue).Current); _thirdYValues.Add((float)_maHigh.Push(_yValue).Current); } _mainSeries.Append(_xValues, _firstYValues); _maLowSeries.Append(_xValues, _secondYValues); _maHighSeries.Append(_xValues, _thirdYValues); }
public void LoadRandomData(int candlesCount, int ticksPerCandle) { _ticksPerCandle = ticksPerCandle; _data = null; var dataSource = new RandomWalkGenerator(); var ticksCount = (candlesCount + 1) * ticksPerCandle; _data = dataSource.GetRandomWalkSeries(ticksCount).YData.ToArray(); _index = 0; //var baseDate = DateTime.Now; for (int j = 0; j < candlesCount; j++) { var date = _baseTime.AddMinutes(j * 30); var volume = _random.Next(100); var bidOrAsk = _random.Next(2) == 0 ? BidOrAsk.Bid : BidOrAsk.Ask; var cumulativeVolume = default(double); var metaData = new CandlestickMetaData(); metaData.AddTick(new CandleTick { BidOrAsk = bidOrAsk, Price = _data[_index], Volume = volume, TimeStamp = date }); cumulativeVolume += bidOrAsk.Equals(BidOrAsk.Ask) ? volume : -volume; var high = cumulativeVolume > 0 ? cumulativeVolume : 0; var low = cumulativeVolume < 0 ? cumulativeVolume : 0; _dataSeries1.Append(date, cumulativeVolume, high, low, cumulativeVolume); _dataSeries0.Append(date, _data[_index], _data[_index], _data[_index], _data[_index], metaData); _candleCount = _dataSeries0.Count; for (int i = 0; i < ticksPerCandle; i++) { _index++; volume = _random.Next(100); bidOrAsk = _random.Next(2) == 0 ? BidOrAsk.Bid : BidOrAsk.Ask; //date = date; var newTick = _data[_index]; var open = _dataSeries0.OpenValues[_candleCount - 1]; high = _dataSeries0.HighValues[_candleCount - 1]; high = high > newTick ? high : newTick; low = _dataSeries0.LowValues[_candleCount - 1]; low = low < newTick ? low : newTick; var meta = (CandlestickMetaData)_dataSeries0.Metadata[_candleCount - 1]; meta.AddTick(new CandleTick { BidOrAsk = bidOrAsk, Price = newTick, Volume = volume, TimeStamp = date }); _dataSeries0.Update(_candleCount - 1, open, high, low, newTick); cumulativeVolume += bidOrAsk.Equals(BidOrAsk.Ask) ? volume : -volume; open = _dataSeries1.OpenValues[_candleCount - 1]; high = _dataSeries1.HighValues[_candleCount - 1]; high = high > cumulativeVolume ? high : cumulativeVolume; low = _dataSeries1.LowValues[_candleCount - 1]; low = low < cumulativeVolume ? low : cumulativeVolume; _dataSeries1.Update(_candleCount - 1, open, high, low, cumulativeVolume); } _filterDataSeries.Append(date, _movingAverage.Push(cumulativeVolume).Current); } }
private void DataAppendLoop() { // if timer was released in another thread - skip all further processing if (_timer == null) { return; } // By nesting multiple updates inside a SuspendUpdates using block, you get one redraw at the end using (_mainSeries.SuspendUpdates()) { // Preload previous value with k-1 sample, or 0.0 if the count is zero int xValue = _mainSeries.Count > 0 ? _mainSeries.XValues[_mainSeries.Count - 1] : 0; double yValue = _mainSeries.Count > 0 ? _mainSeries.YValues[_mainSeries.Count - 1] : 10.0f; // Add N points at a time. We want to get to the higher point counts // quickly to demonstrate performance. // Also, it is more efficient to buffer and block update the chart // even if you use SuspendUpdates due to the overhead of calculating min, max // for a series for (int i = 0; i < BufferSize; i++) { // Generate a new X,Y value in the random walk and buffer xValue = xValue + 1; yValue = (double)(yValue + (_random.NextDouble() - 0.5)); _xBuffer[i] = xValue; _yBuffer[i] = yValue; // Update moving averages _maLowBuffer[i] = (double)_maLow.Push(yValue).Current; _maHighBuffer[i] = (double)_maHigh.Push(yValue).Current; } // Append block of values to all three series _mainSeries.Append(_xBuffer, _yBuffer); _maLowSeries.Append(_xBuffer, _maLowBuffer); _maHighSeries.Append(_xBuffer, _maHighBuffer); } // Render the total point count (all series) to the screen int numPoints = 3 * _mainSeries.Count; if (numPoints > 10000 && _reached < 10000) { _reached = 10000; } if (numPoints > 100000 && _reached < 100000) { _reached = 100000; } if (numPoints > 300000 && _reached < 300000) { _reached = 300000; } if (numPoints > 500000 && _reached < 500000) { _reached = 500000; } if (numPoints > 1000000 && _reached < 1000000) { _reached = 1000000; } if (numPoints > 3000000 && _reached < 3000000) { Messages.Add("Reached 3,000,000 Points!"); _reached = 3000000; } if (numPoints > 5000000 && _reached < 5000000) { Messages.Add("Reached 5,000,000 Points!"); _reached = 5000000; } if (numPoints > MaxCount) { Messages.Add("Reached 10M points!"); Messages.Add(".. and I'm still going!"); _timer.Stop(); _timer = null; BoundRange = AutoRange.Never; this.ShowInstructionsToUser(); } }
private void Redraw() { if (GraphControl == null) { return; } GraphControl.GraphPane.CurveList.Clear(); GraphPane pane = GraphControl.GraphPane; pane.YAxisList.Clear(); pane.Title.Text = ""; //var graphs = m_Graphs.SelectMany(g => g.Value).ToList(); if (m_Graphs.SelectMany(g => g.Value).Count() == 0) { pane.XAxis.Title.Text = ""; return; } var yAxises = new Dictionary <string, int>(); int color = 0; foreach (var keyValue in m_Graphs) { var lineColor = GraphSettings.CurveLines[color++].LineColor; for (int i = 0; i < keyValue.Value.Count(); i++) { Graph graph = keyValue.Value[i]; var line = graph.GetLineItem(); if (GraphSettings.Smooth) { var curList = (IPointList)line.Points.Clone(); var average = new MovingAverage(GraphSettings.SmoothPeriod); switch (GraphSettings.SmoothType) { case SmoothModel.Average: for (int j = 0; j < curList.Count; j++) { average.Push(curList[j].Y); curList[j].Y = average.Average; } break; case SmoothModel.Median: for (int j = 0; j < curList.Count; j++) { average.Push(curList[i].Y); curList[j].Y = average.Median; } break; default: break; } line.Points = curList; } var yAxisLabel = graph.YAxis + (string.IsNullOrEmpty(graph.Y_Unit) ? "" : (", " + graph.Y_Unit)); if (!yAxises.ContainsKey(yAxisLabel)) { yAxises.Add(yAxisLabel, pane.AddYAxis(yAxisLabel)); } line.YAxisIndex = yAxises[yAxisLabel]; line.Line.Style = (System.Drawing.Drawing2D.DashStyle)i; line.Line.Color = lineColor; pane.CurveList.Add(line); } } pane.XAxis.Title.Text = m_Graphs.First().Value.First().XAxis + (string.IsNullOrEmpty(m_Graphs.First().Value.First().X_Unit) ? "" : (", " + m_Graphs.First().Value.First().X_Unit)); pane.Title.Text = ""; GraphControl.AxisChange(); LegendRedraw(GraphSettings.LegendVisible); AxisTitleRedraw(GraphSettings.AxisLabelVisible); #region AxisGrids pane.XAxis.MajorGrid.IsVisible = GraphSettings.MajorGrid; pane.YAxis.MajorGrid.IsVisible = GraphSettings.MajorGrid; pane.XAxis.MinorGrid.IsVisible = GraphSettings.MinorGrid; pane.YAxis.MinorGrid.IsVisible = GraphSettings.MinorGrid; pane.YAxis.MajorGrid.DashOn = 10; pane.YAxis.MajorGrid.DashOff = 5; pane.XAxis.MajorGrid.DashOn = 10; pane.XAxis.MajorGrid.DashOff = 5; pane.YAxis.MajorGrid.DashOn = 10; pane.YAxis.MajorGrid.DashOff = 5; pane.XAxis.MinorGrid.DashOn = 1; pane.XAxis.MinorGrid.DashOff = 2; pane.YAxis.MinorGrid.DashOn = 1; pane.YAxis.MinorGrid.DashOff = 2; #endregion DashOnOff GraphControl.Invalidate(); GraphControl.Refresh(); }
public void Redraw() { if (GraphControl == null) { return; } GraphControl.GraphPane.CurveList.Clear(); GraphPane pane = GraphControl.GraphPane; pane.YAxisList.Clear(); if (Graphs.Count == 0) { pane.XAxis.Title.Text = ""; return; } var yAxises = new Dictionary <string, int>(); for (int k = 0; k < Graphs.Count; k++) { Graph graph = Graphs[k]; LineItem line = k < GraphSettings.CurveLines.Count ? graph.GetLineItem(GraphSettings.CurveLines[k].LineColor, SymbolType.None, 2.0f) : graph.GetLineItem(); if (GraphSettings.Smooth) { var curList = (IPointList)line.Points.Clone(); var average = new MovingAverage(GraphSettings.SmoothPeriod); switch (GraphSettings.SmoothType) { case SmoothModel.Average: for (int i = 0; i < curList.Count; i++) { average.Push(curList[i].Y); curList[i].Y = average.Average; } break; case SmoothModel.Median: for (int i = 0; i < curList.Count; i++) { average.Push(curList[i].Y); curList[i].Y = average.Median; } break; default: break; } line.Points = curList; } var yAxisLabel = graph.YAxis + (string.IsNullOrEmpty(graph.Y_Unit) ? "" : (", " + graph.Y_Unit)); if (!yAxises.ContainsKey(yAxisLabel)) { yAxises.Add(yAxisLabel, pane.AddYAxis(yAxisLabel)); } line.YAxisIndex = yAxises[yAxisLabel]; pane.CurveList.Add(line); } pane.XAxis.Title.Text = Graphs.Last().XAxis + (string.IsNullOrEmpty(Graphs.Last().X_Unit) ? "" : (", " + Graphs.Last().X_Unit)); pane.Title.Text = ""; GraphControl.AxisChange(); LegendRedraw(GraphSettings.LegendVisible); AxisTitleRedraw(GraphSettings.AxisLabelVisible); #region AxisGrids pane.XAxis.MajorGrid.IsVisible = GraphSettings.MajorGrid; pane.YAxis.MajorGrid.IsVisible = GraphSettings.MajorGrid; pane.XAxis.MinorGrid.IsVisible = GraphSettings.MinorGrid; pane.YAxis.MinorGrid.IsVisible = GraphSettings.MinorGrid; pane.YAxis.MajorGrid.DashOn = 10; pane.YAxis.MajorGrid.DashOff = 5; pane.XAxis.MajorGrid.DashOn = 10; pane.XAxis.MajorGrid.DashOff = 5; pane.YAxis.MajorGrid.DashOn = 10; pane.YAxis.MajorGrid.DashOff = 5; pane.XAxis.MinorGrid.DashOn = 1; pane.XAxis.MinorGrid.DashOff = 2; pane.YAxis.MinorGrid.DashOn = 1; pane.YAxis.MinorGrid.DashOff = 2; #endregion DashOnOff GraphControl.Invalidate(); GraphControl.Refresh(); }