public MacdPaneViewModel(CreateMultiPaneStockChartsViewModel parentViewModel, PriceSeries prices)
            : base(parentViewModel)
        {
            IEnumerable <MacdPoint> macdPoints = prices.CloseData.Macd(12, 26, 9).ToList();

            var histogramDataSeries = new XyDataSeries <DateTime, double>()
            {
                SeriesName = "Histogram"
            };

            histogramDataSeries.Append(prices.TimeData, macdPoints.Select(x => x.Divergence));
            ChartSeriesViewModels.Add(new ColumnRenderableSeriesViewModel {
                DataSeries = histogramDataSeries
            });

            var macdDataSeries = new XyyDataSeries <DateTime, double>()
            {
                SeriesName = "MACD"
            };

            macdDataSeries.Append(prices.TimeData, macdPoints.Select(x => x.Macd), macdPoints.Select(x => x.Signal));
            ChartSeriesViewModels.Add(new BandRenderableSeriesViewModel
            {
                DataSeries      = macdDataSeries,
                StrokeThickness = 2,
            });

            YAxisTextFormatting = "0.00";

            Height = 100;
        }
        public void AddOrUpdateLine(int id, int maxNumberOfPoints, string lineName)
        {
            if (lineDictionary.ContainsKey(id))
            {
                lineDictionary[id] = new XyDataSeries <double, double>(maxNumberOfPoints)
                {
                    SeriesName = lineName
                };
                //sciChart.RenderableSeries.RemoveAt(id);
            }
            else
            {
                lineDictionary.Add(id, new XyDataSeries <double, double>(maxNumberOfPoints)
                {
                    SeriesName = lineName
                });

                var lineRenderableSerie = new FastLineRenderableSeries();
                lineRenderableSerie.Name       = "lineRenderableSerie" + id.ToString();
                lineRenderableSerie.DataSeries = lineDictionary[id];
                lineRenderableSerie.DataSeries.AcceptsUnsortedData = true;

                //Ajout de la ligne dans le scichart
                sciChart.RenderableSeries.Add(lineRenderableSerie);
            }
        }
        void CreateDataSeries()
        {
            // Init line data series
            _lineDataSeries = new XyDataSeries <Double, Double>();
            // Setting fifo capacity, once new data values will be added, the old one will be removed
            _lineDataSeries.FifoCapacity = 500;
            // Naming data series, so its name will be shown in LegendModifier
            _lineDataSeries.SeriesName = "LineSeries";
            for (var i = 0; i < 500; i++)
            {
                _lineDataSeries.Append(i, Math.Sin(i * 0.1));
            }

            // Init scatter data series
            _scatterDataSeries = new XyDataSeries <Double, Double>();
            // Setting fifo capacity, once new data values will be added, the old one will be removed
            _scatterDataSeries.FifoCapacity = 500;
            // Naming data series, so its name will be shown in LegendModifier
            _scatterDataSeries.SeriesName = "ScatterSeries";
            for (var i = 0; i < 500; i++)
            {
                _scatterDataSeries.Append(i, Math.Cos(i * 0.1));
            }

            _i = _lineDataSeries.Count;
        }
        public MainViewModel()
        {
            var ds0 = new XyDataSeries<double, double>();
            var someData = new RandomWalkGenerator().GetRandomWalkSeries(200); // RandomWalkGenerator is found in the examples source code

            ds0.Append(someData.XData, someData.YData);

            // With SeriesSource API you do not need a DataSet. This is created automatically to match
            // the type of DataSeries<Tx,Ty>. All DataSeries must be the same type however

            // Create a list of ChartSeriesViewModel which unify dataseries and render series
            // This way you can add/remove your series and change the render series type easily
            // without worrying about DataSeriesIndex as per SciChart v1.3
            _chartSeries = new ObservableCollection<IChartSeriesViewModel>();
            _chartSeries.Add(new ChartSeriesViewModel(ds0, new FastLineRenderableSeries()));

            // Now create the labels
            _chartLabels = new[]
                               {
                                   new LabelViewModel(5, -2.5, "Label0", "Label0 Tooltip!"),
                                   new LabelViewModel(20, -2, "Label1", "Label1 Tooltip!"),
                                   new LabelViewModel(35, 3, "Label2", "Label2 Tooltip!"),
                                   new LabelViewModel(50, 1.5, "Label3", "Label3 Tooltip!"),
                                   new LabelViewModel(65, -0.5, "Label4", "Label4 Tooltip!"),
                               };
        }
        private void MouseDragToPanXOrY_Loaded(object sender, RoutedEventArgs e)
        {
            // Performing multiple updates in a SuspendUpdates block is efficient as only one redraw is performed
            using (sciChart.SuspendUpdates())
            {
                // Add some data series
                var dataSeries0 = new XyDataSeries <double, double>();
                var dataSeries1 = new XyDataSeries <double, double>();

                var data2 = DataManager.Instance.GetFourierSeries(1.0, 0.1);
                var data1 = DataManager.Instance.GetDampedSinewave(1500, 3.0, 0.0, 0.005, data2.Count);

                // Append data to series.
                dataSeries0.Append(data1.XData, data1.YData);
                dataSeries1.Append(data2.XData, data2.YData);

                // Assign data-series to renderable series
                sciChart.RenderableSeries[0].DataSeries = dataSeries0;
                sciChart.RenderableSeries[1].DataSeries = dataSeries1;

                // Set initial zoom
                sciChart.XAxis.VisibleRange = new DoubleRange(3, 6);
                sciChart.ZoomExtentsY();
            }
            panXYDirection.ItemsSource = Enum.GetNames(typeof(XyDirection));
        }
Beispiel #6
0
 private void UpdateVolumeChart(PriceSeries prices)
 {
     // Create a new series and append Open, High, Low, Close data
     VolumeData            = new XyDataSeries <DateTime, long>();
     VolumeData.SeriesName = string.Format("{0} Volume", prices.Symbol);
     VolumeData.Append(prices.TimeData, prices.VolumeData);
 }
        private void QuadLeftRightAxes_Loaded(object sender, RoutedEventArgs e)
        {
            // Batch updates with one redraw
            using (sciChart.SuspendUpdates())
            {
                // Add four data-series
                var dataSeries0 = new XyDataSeries <DateTime, double>();
                var dataSeries1 = new XyDataSeries <DateTime, double>();
                var dataSeries2 = new XyDataSeries <DateTime, double>();
                var dataSeries3 = new XyDataSeries <DateTime, double>();
                var dataSeries4 = new XyDataSeries <DateTime, double>();
                var dataSeries5 = new XyDataSeries <DateTime, double>();
                var dataSeries6 = new XyDataSeries <DateTime, double>();
                var dataSeries7 = new XyDataSeries <DateTime, double>();


                // Fill each data-series with 2,000 pts of X,Y values (Date,Double) and assign to RenderableSeries
                sciChart.RenderableSeries[0].DataSeries = FillData(dataSeries0, "Red Line");
                sciChart.RenderableSeries[1].DataSeries = FillData(dataSeries1, "Grey Line");
                sciChart.RenderableSeries[2].DataSeries = FillData(dataSeries2, "Orange Line");
                sciChart.RenderableSeries[3].DataSeries = FillData(dataSeries3, "Blue Line");
                sciChart.RenderableSeries[4].DataSeries = FillData(dataSeries4, "Another Blue");
                sciChart.RenderableSeries[5].DataSeries = FillData(dataSeries5, "Green Line");
                sciChart.RenderableSeries[6].DataSeries = FillData(dataSeries6, "Another Red");
                sciChart.RenderableSeries[7].DataSeries = FillData(dataSeries7, "Another Grey");
            }

            sciChart.ZoomExtents();
        }
Beispiel #8
0
        public StackedMountainChartExampleView()
        {
            InitializeComponent();

            var yValues1 = new[] { 4.0, 7, 5.2, 9.4, 3.8, 5.1, 7.5, 12.4, 14.6, 8.1, 11.7, 14.4, 16.0, 3.7, 5.1, 6.4, 3.5, 2.5, 12.4, 16.4, 7.1, 8.0, 9.0 };
            var yValues2 = new[] { 15.0, 10.1, 10.2, 10.4, 10.8, 1.1, 11.5, 3.4, 4.6, 0.1, 1.7, 14.4, 6.0, 13.7, 10.1, 8.4, 8.5, 12.5, 1.4, 0.4, 10.1, 5.0, 0.0 };

            var dataSeries1 = new XyDataSeries <double, double>()
            {
                SeriesName = "data1"
            };
            var dataSeries2 = new XyDataSeries <double, double>()
            {
                SeriesName = "data2"
            };;

            for (int i = 0; i < yValues1.Length; i++)
            {
                dataSeries1.Append(i, yValues1[i]);
            }
            for (int i = 0; i < yValues2.Length; i++)
            {
                dataSeries2.Append(i, yValues2[i]);
            }

            using (this.sciChart.SuspendUpdates())
            {
                this.mountainSeries1.DataSeries = dataSeries1;
                this.mountainSeries2.DataSeries = dataSeries2;
            }
        }
            public static ChartTypeModel NewVerticallyStackedMountains(Context context, bool isOneHundredPercent)
            {
                var collection = new VerticallyStackedMountainsCollection {
                    IsOneHundredPercent = isOneHundredPercent
                };

                for (var i = 0; i < 5; i++)
                {
                    var dataSeries = new XyDataSeries <double, double> {
                        SeriesName = "Series " + (i + 1)
                    };
                    dataSeries.Append(DashboardDataHelper.XValues, DashboardDataHelper.YValues[i]);

                    var rSeries = new StackedMountainRenderableSeries
                    {
                        DataSeries  = dataSeries,
                        StrokeStyle = new SolidPenStyle(context, new Color(SeriesColors[i * 2])),
                        AreaStyle   = new LinearGradientBrushStyle(0, 0, 0, 1, new Color(SeriesColors[i * 2 + 1]), new Color(SeriesColors[i * 2]))
                    };
                    collection.Add(rSeries);
                }

                var name = isOneHundredPercent ? "100% " : "";

                name += "Stacked mountains";
                return(new ChartTypeModel(collection, name));
            }
        private void UpdatePriceChart(PriceSeries priceData)
        {
            // Create a new series and append Open, High, Low, Close data
            var ohlcDataSeries = new OhlcDataSeries <DateTime, double>();

            ohlcDataSeries.Append(priceData.TimeData, priceData.OpenData, priceData.HighData, priceData.LowData, priceData.CloseData);
            PriceData            = (IOhlcDataSeries <DateTime, double>) new DiscontinuousAxisFilter <double>(ohlcDataSeries, Calendar).FilteredDataSeries;
            PriceData.SeriesName = priceData.Symbol;

            var xyDataSeries = new XyDataSeries <DateTime, double>();

            xyDataSeries.Append(priceData.TimeData, priceData.CloseData);
            var discontinuousSeries = new DiscontinuousAxisFilter <double>(xyDataSeries, Calendar).FilteredDataSeries as IDataSeries <DateTime, double>;

            // Create a series for the 200 period SMA which will be plotted as a line chart
            Sma200Series            = (IXyDataSeries <DateTime, double>) new MovingAverageFilter <DateTime>(discontinuousSeries, 200).FilteredDataSeries;
            Sma200Series.SeriesName = "200 SMA";

            // Create a series for the 50 period SMA which will be plotted as a line chart
            Sma50Series            = (IXyDataSeries <DateTime, double>) new MovingAverageFilter <DateTime>(discontinuousSeries, 50).FilteredDataSeries;
            Sma50Series.SeriesName = "50 SMA";

            // Update the chart type and timeframe with current settings
            UpdateChartType(_chartType);
            UpdateAnnoations();
        }
        public ScrollbarMvvmAxisViewModel()
        {
            YAxes            = new ObservableCollection <IAxisViewModel>();
            XAxes            = new ObservableCollection <IAxisViewModel>();
            RenderableSeries = new ObservableCollection <IRenderableSeriesViewModel>();

            YAxes.Add(new NumericAxisViewModelWithScrollbar()
            {
                HasScrollbar = false, StyleKey = "ScrollbarAxisStyle"
            });
            XAxes.Add(new NumericAxisViewModelWithScrollbar()
            {
                HasScrollbar = true, StyleKey = "ScrollbarAxisStyle"
            });

            var xyData = new XyDataSeries <double>();

            for (int i = 0; i < 100; i++)
            {
                xyData.Append(i, Math.Sin(i * 0.1));
            }

            RenderableSeries.Add(new LineRenderableSeriesViewModel()
            {
                DataSeries = xyData
            });
        }
        public void ModifyAxisPropertiesLoaded(object sender, EventArgs e)
        {
            using (sciChart.SuspendUpdates())
            {
                // Add a data series
                var dataSeries0 = new XyDataSeries <DateTime, double>();
                var dataSeries1 = new OhlcDataSeries <DateTime, double>();
                var dataSeries2 = new XyDataSeries <DateTime, double>();

                var dataSource = DataManager.Instance;

                // Prices are in the format Time, Open, High, Low, Close (all IList)
                var prices = dataSource.GetPriceData(Instrument.Indu.Value, TimeFrame.Daily);

                // Append data to series.
                dataSeries0.Append(prices.TimeData, dataSource.Offset(prices.LowData, -1000));
                dataSeries1.Append(prices.TimeData, prices.OpenData, prices.HighData, prices.LowData, prices.CloseData);
                dataSeries2.Append(prices.TimeData, dataSource.ComputeMovingAverage(prices.CloseData, 50));

                columnSeries.DataSeries = dataSeries0;
                ohlcSeries.DataSeries   = dataSeries1;
                lineSeries.DataSeries   = dataSeries2;

                sciChart.ZoomExtents();
            }
        }
        private void OnAxisMarkerAnnotationMove()
        {
            var doubleSeries = new XyDataSeries <double, double>();
            var axisInfo     = AxisMarkerAnnotation.AxisInfo;
            var dataIndex    = 0;

            if (axisInfo != null)
            {
                var position = (double)axisInfo.DataValue;
                dataIndex = sciChart.RenderableSeries[0].DataSeries.XValues.FindIndex(true, position, SearchMode.Nearest);
            }
            else
            {
                dataIndex = Convert.ToInt32(AxisMarkerAnnotation.X1);
            }

            if (_paletteProvider != null)
            {
                _paletteProvider.SelectedIndex = dataIndex;
            }

            for (var i = 0; i < sciChart.RenderableSeries.Count; i++)
            {
                doubleSeries.Append(i, (double)sciChart.RenderableSeries[i].DataSeries.YValues[dataIndex]);
                _paletteProvider.OnBeginSeriesDraw(sciChart.RenderableSeries[i]);
            }

            if (sciChart3 != null && sciChart3.RenderableSeries.Any())
            {
                sciChart3.RenderableSeries[0].DataSeries = doubleSeries;
                sciChart3.ZoomExtents();
            }
        }
        private XyDataSeries <double, double> UpdateXyDataSeries()
        {
            var doubleSeries = new XyDataSeries <double, double>();

            var _re = new double[1024];
            var _im = new double[1024];

            for (var i = 0; i < 1024; i++)
            {
                _re[i] = 2.0 * Math.Sin(2 * Math.PI * i / 20) +
                         5 * Math.Sin(2 * Math.PI * i / 10) +
                         2.0 * _random.NextDouble();
                _im[i] = -10;
            }

            _transform.run(_re, _im);
            var _re2 = new double[500];
            var _im2 = new double[500];

            for (var i = 0; i < 500; i++)
            {
                var mag  = Math.Sqrt(_re[i] * _re[i] + _im[i] * _im[i]);
                var yVal = 20 * Math.Log10(mag / 500);
                _re2[i] = (yVal <-25 || yVal> -5)
                    ? (yVal < -25) ? -25 : _random.Next(-6, -3)
                    : yVal;

                _im2[i] = i;
            }
            _re2[0] = -25;
            doubleSeries.Append(_im2, _re2);

            return(doubleSeries);
        }
        public void AddOrUpdateLine(int lineId, int maxNumberOfPoints, string lineName, bool useYAxisRight = true)
        {
            if (LineExist(lineId))
            {
                lineDictionary[lineId] = new XyDataSeries <double, double>(maxNumberOfPoints)
                {
                    SeriesName = lineName
                };
                //sciChart.RenderableSeries.RemoveAt(id);
            }
            else
            {
                lineDictionary.Add(lineId, new XyDataSeries <double, double>(maxNumberOfPoints)
                {
                    SeriesName = lineName
                });

                var lineRenderableSerie = new FastLineRenderableSeries();
                lineRenderableSerie.Name       = "lineRenderableSerie" + lineId.ToString();
                lineRenderableSerie.DataSeries = lineDictionary[lineId];
                lineRenderableSerie.DataSeries.AcceptsUnsortedData = true;
                if (useYAxisRight)
                {
                    lineRenderableSerie.YAxisId = "RightYAxis";
                }
                else
                {
                    lineRenderableSerie.YAxisId = "LeftYAxis";
                }

                //Ajout de la ligne dans le scichart
                sciChart.RenderableSeries.Add(lineRenderableSerie);
            }
        }
Beispiel #16
0
        private void StartUpdate(object obj) {
            _isIdle = false;

            Task.Run(() => {
                _uiContext.Post(_ => {
                    Line1Data = new XyDataSeries<int, double>();
                    Line2Data = new XyDataSeries<int, double>();
                }, null);

                var line1Value = 99.5;
                var line2Value = 100.5;
                var rnd = new Random();
                for (var i = 1; i < 1000; i++) {
                    _uiContext.Post(_ => {
                        Line1Data.Append(i, line1Value);
                        Line2Data.Append(i, line2Value);
                    }, null);
                    line1Value += rnd.NextDouble() - 0.5;
                    line2Value += rnd.NextDouble() - 0.5;
                    Thread.Sleep(5);
                }

                _isIdle = true;
            });
        }
        private void FanChartExampleViewLoaded(object sender, RoutedEventArgs e)
        {
            // Variance data is a 2D table containing actual values and several levels of projected high, low values
            IEnumerable <VarPoint> varianceData = GetVarianceData().ToArray();

            // To render the Fan, we use an XyDataSeries and three band series'
            var actualDataSeries = new XyDataSeries <DateTime, double>();
            var var3DataSeries   = new XyyDataSeries <DateTime, double>();
            var var2DataSeries   = new XyyDataSeries <DateTime, double>();
            var var1DataSeries   = new XyyDataSeries <DateTime, double>();

            // Append data values from the Variance table
            actualDataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Actual));
            var3DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.VarMin), varianceData.Select(x => x.VarMax));
            var2DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Var1), varianceData.Select(x => x.Var4));
            var1DataSeries.Append(varianceData.Select(x => x.Date), varianceData.Select(x => x.Var2), varianceData.Select(x => x.Var3));

            // Assign data to renderableseries
            lineSeries.DataSeries    = actualDataSeries;
            projectedVar3.DataSeries = var3DataSeries;
            projectedVar2.DataSeries = var2DataSeries;
            projectedVar1.DataSeries = var1DataSeries;

            sciChart.ZoomExtents();
        }
        private void RolloverFeedbackLoaded(object sender, RoutedEventArgs e)
        {
            sciChartSurface.YAxis.GrowBy = new DoubleRange(0.2, 0.2);

            var seriesA = new XyDataSeries <double, double>();
            var seriesB = new XyDataSeries <double, double>();
            var seriesC = new XyDataSeries <double, double>();

            seriesA.SeriesName = "Sinewave A";
            seriesB.SeriesName = "Sinewave B";
            seriesC.SeriesName = "Sinewave C";

            double count = 100.0;
            double k     = 2 * Math.PI / 30.0;

            for (int i = 0; i < (int)count; i++)
            {
                var phi = k * i;
                seriesA.Append(i, (1.0 + i / count) * Math.Sin(phi));
                seriesB.Append(i, (0.5 + i / count) * Math.Sin(phi));
                seriesC.Append(i, (i / count) * Math.Sin(phi));
            }

            sciChartSurface.RenderableSeries[0].DataSeries = seriesA;
            sciChartSurface.RenderableSeries[1].DataSeries = seriesB;
            sciChartSurface.RenderableSeries[2].DataSeries = seriesC;
        }
        public HitTestDatapoints()
        {
            InitializeComponent();

            // Append some data
            var series0 = new XyDataSeries <double, double> {
                SeriesName = "Line Series"
            };

            series0.Append(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new double[] { 0, 0.1, 0.3, 0.5, 0.4, 0.35, 0.3, 0.25, 0.2, 0.1 });
            renderableLineSeries.DataSeries = series0;

            var series1 = new XyDataSeries <double, double> {
                SeriesName = "Column Series"
            };

            series1.Append(series0.XValues, series0.YValues.Select(x => x * 0.7));
            renderableColumnSeries.DataSeries = series1;

            var series2 = new OhlcDataSeries <double, double> {
                SeriesName = "Candlestick Series"
            };

            series2.Append(series0.XValues, series0.YValues.Select(x => x + 0.5), series0.YValues.Select(x => x + 1.0), series0.YValues.Select(x => x + 0.3), series0.YValues.Select(x => x + 0.7));
            renderableCandlestickSeries.DataSeries = series2;
        }
        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            // Create our data in another thread to stop the UI from being stalled.
            // It's not appending to SciChart Dataseries that is the problem, its Calling Rand.Next() two million times which is pretty slow :)
            TimedMethod.Invoke(() =>
            {
                var dataSeries = new XyDataSeries <double, double>()
                {
                    AcceptsUnsortedData = true
                };
                var rand = new FasterRandom();

                // Allow 1M points in WPF/DirectX. In Silverlight or software rendering, 100k points is enough to stress the renderer
                int count = FeaturesHelper.Instance.SupportsHardwareAcceleration ? (int)1E6 : (int)1E5;

                // Append some data
                for (int i = 0; i < count; i++)
                {
                    dataSeries.Append(rand.NextDouble(), rand.NextDouble());
                }

                // Bind to scichart
                Action bindData = () => { BindData(dataSeries); };
                Dispatcher.BeginInvoke(bindData);
            }).After(200).OnThread(TimedMethodThread.Background).Go();
        }
        public CreateRealTimeTickingStockChartViewModel()
        {
            _seriesViewModels = new ObservableCollection <IRenderableSeriesViewModel>();

            DateTime localDate = DateTime.Now; //Начальное время

            //Загрузка данных которые хранятся в памяти
            _marketDataService = new MarketDataService(localDate, 1, 1); //Время и период изменения

            //Добавление модели для представления графиков
            var ds0 = new XyDataSeries <DateTime, double> {
                SeriesName = "Температура (*С)"
            };

            _seriesViewModels.Add(new LineRenderableSeriesViewModel {
                DataSeries = ds0, StyleKey = "LineStyle"
            });

            //Добавление модели для представления графиков
            var ds1 = new XyDataSeries <DateTime, double> {
                SeriesName = "Давление (hPa)"
            };

            _seriesViewModels.Add(new LineRenderableSeriesViewModel {
                DataSeries = ds1, StyleKey = "LineStyle1"
            });

            //Добавление модели для представления графиков
            var ds2 = new XyDataSeries <DateTime, double> {
                SeriesName = "Высота (м)"
            };

            _seriesViewModels.Add(new LineRenderableSeriesViewModel {
                DataSeries = ds2, StyleKey = "LineStyle2"
            });

            //Добавление модели для представления графиков
            var ds3 = new XyDataSeries <DateTime, double> {
                SeriesName = "Влажность (%)"
            };

            _seriesViewModels.Add(new LineRenderableSeriesViewModel {
                DataSeries = ds3, StyleKey = "LineStyle"
            });

            double y0 = 0;
            double y1 = 0;
            double y2 = 0;
            double y3 = 0;

            var indicators = _marketDataService.GetHistoricalData(0); //начальное значение (история)

            ds0.Append(localDate, y0);
            ds1.Append(localDate, y1);
            ds2.Append(localDate, y2);
            ds3.Append(localDate, y3);

            SelectedSeriesStyle = "Line";
        }
        protected override void InitExample()
        {
            var xAxis = new SCIDateTimeAxis {
                GrowBy = new SCIDoubleRange(0.1, 0.1), TextFormatting = "dd/MM/YYYY"
            };
            var yAxis = new SCINumericAxis {
                GrowBy = new SCIDoubleRange(0.1, 0.1)
            };

            var dataSeries = new XyDataSeries <DateTime, double> {
                DataDistributionCalculator = new SCIUserDefinedDistributionCalculator()
            };
            var xyyDataSeries = new XyyDataSeries <DateTime, double> {
                DataDistributionCalculator = new SCIUserDefinedDistributionCalculator()
            };
            var xyyDataSeries1 = new XyyDataSeries <DateTime, double> {
                DataDistributionCalculator = new SCIUserDefinedDistributionCalculator()
            };
            var xyyDataSeries2 = new XyyDataSeries <DateTime, double> {
                DataDistributionCalculator = new SCIUserDefinedDistributionCalculator()
            };

            DataManager.Instance.GetFanData(10, result =>
            {
                dataSeries.Append(result.Date, result.ActualValue);
                xyyDataSeries.Append(result.Date, result.MaxValue, result.MinValue);
                xyyDataSeries1.Append(result.Date, result.Value1, result.Value4);
                xyyDataSeries2.Append(result.Date, result.Value2, result.Value3);
            });

            var dataRenderSeries = new SCIFastLineRenderableSeries
            {
                DataSeries  = dataSeries,
                StrokeStyle = new SCISolidPenStyle(UIColor.Red, 1.0f)
            };

            var animation = new SCIWaveRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut);

            animation.StartAfterDelay(0.3f);
            dataRenderSeries.AddAnimation(animation);

            using (Surface.SuspendUpdates())
            {
                Surface.XAxes.Add(xAxis);
                Surface.YAxes.Add(yAxis);

                Surface.RenderableSeries.Add(createRenderableSeriesWith(xyyDataSeries));
                Surface.RenderableSeries.Add(createRenderableSeriesWith(xyyDataSeries1));
                Surface.RenderableSeries.Add(createRenderableSeriesWith(xyyDataSeries2));
                Surface.RenderableSeries.Add(dataRenderSeries);

                Surface.ChartModifiers = new SCIChartModifierCollection
                {
                    new SCIZoomPanModifier(),
                    new SCIPinchZoomModifier(),
                    new SCIZoomExtentsModifier()
                };
            }
        }
        protected override void InitExample()
        {
            var xAxis = new SCINumericAxis();
            var yAxis = new SCINumericAxis();

            var ds1 = new XyDataSeries <double, double> {
                SeriesName = "Curve A"
            };
            var ds2 = new XyDataSeries <double, double> {
                SeriesName = "Curve B"
            };
            var ds3 = new XyDataSeries <double, double> {
                SeriesName = "Curve C"
            };
            var ds4 = new XyDataSeries <double, double> {
                SeriesName = "Curve D"
            };

            var ds1Points = DataManager.Instance.GetStraightLine(4000, 1.0, 10);
            var ds2Points = DataManager.Instance.GetStraightLine(3000, 1.0, 10);
            var ds3Points = DataManager.Instance.GetStraightLine(2000, 1.0, 10);
            var ds4Points = DataManager.Instance.GetStraightLine(1000, 1.0, 10);

            ds1.Append(ds1Points.XData, ds1Points.YData);
            ds2.Append(ds2Points.XData, ds2Points.YData);
            ds3.Append(ds3Points.XData, ds3Points.YData);
            ds4.Append(ds4Points.XData, ds4Points.YData);

            var rs1 = new SCIFastLineRenderableSeries {
                DataSeries = ds1, StrokeStyle = new SCISolidPenStyle(0xFFFFFF00, 2f)
            };
            var rs2 = new SCIFastLineRenderableSeries {
                DataSeries = ds2, StrokeStyle = new SCISolidPenStyle(0xFF279B27, 2f)
            };
            var rs3 = new SCIFastLineRenderableSeries {
                DataSeries = ds3, StrokeStyle = new SCISolidPenStyle(0xFFFF1919, 2f)
            };
            var rs4 = new SCIFastLineRenderableSeries {
                DataSeries = ds4, IsVisible = false, StrokeStyle = new SCISolidPenStyle(0xFF1964FF, 2f)
            };

            using (Surface.SuspendUpdates())
            {
                Surface.XAxes.Add(xAxis);
                Surface.YAxes.Add(yAxis);
                Surface.RenderableSeries.Add(rs1);
                Surface.RenderableSeries.Add(rs2);
                Surface.RenderableSeries.Add(rs3);
                Surface.RenderableSeries.Add(rs4);
                Surface.ChartModifiers.Add(new SCILegendModifier {
                    SourceMode = SCISourceMode.AllSeries
                });

                rs1.AddAnimation(new SCISweepRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut));
                rs2.AddAnimation(new SCISweepRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut));
                rs3.AddAnimation(new SCISweepRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut));
                rs4.AddAnimation(new SCISweepRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut));
            }
        }
Beispiel #24
0
        private void OnTimerElapsed(object sender, EventArgs e)
        {
            if (_working)
            {
                return;
            }

            lock (_timer)
            {
                _working = true;

                // The simulation is very computationally expensive, so we update in parallel
                // What we observe is 400ms is required to update position of 1,000,000 elements
                var sw = Stopwatch.StartNew();
                _simulation.Tick(4);
                sw.Stop();
                //Console.WriteLine("Tick: {0}ms", sw.ElapsedMilliseconds);

                // By creating and filling a new series per-frame, we avoid the need
                // to call SuspendUpdates on the series, which will lock the parent chart.
                //
                // Therefore we can append on another thread (other than UI Thread) and the UI will
                // draw the last series on the UI thread, while we are filling this series on the background thread
                //
                // The trade-off is memory usage. Each time you create and discard an XyDataSeries you are putting additional
                // pressure on the garbage collector.

                var victims   = _seriesPool.Get();
                var defenders = _seriesPool.Get();

                using (victims.SuspendUpdates())
                    using (defenders.SuspendUpdates())
                    {
                        victims.Clear();
                        defenders.Clear();

                        var persons = _simulation.People;
                        for (int i = 0; i < persons.Length; ++i)
                        {
                            Person person = persons[i];
                            if (person.IsVictim)
                            {
                                victims.Append(person.Pos.X, person.Pos.Y);
                            }
                            else
                            {
                                defenders.Append(person.Pos.X, person.Pos.Y);
                            }
                        }

                        _seriesPool.Put((XyDataSeries <double>)Victims);
                        _seriesPool.Put((XyDataSeries <double>)Defenders);
                        Victims   = victims;
                        Defenders = defenders;
                    }

                _working = false;
            }
        }
        private WaterfallDataSeries3D <double> ResampleDataSeries(WaterfallDataSeries3D <double> dataSeries, double[] slicePositions)
        {
            var pointsPerSlice = dataSeries.XSize;
            var sliceCount     = dataSeries.ZSize;

            var resamplerFactory = new PointResamplerFactory();

            var resamplingParams = new ResamplingParams
            {
                IsSortedData        = true,
                IsEvenlySpacedData  = true,
                IsCategoryData      = false,
                ContainsNaN         = false,
                ZeroLineY           = 0.0,
                PointRange          = new IndexRange(0, pointsPerSlice - 1),
                VisibleRange        = dataSeries.XRange,
                ViewportWidth       = Width > 0.0 ? (int)Width : 640,
                ResamplingPrecision = 1
            };

            var resampledSeriesesArray = new IPointSeries[sliceCount];
            var sliceAsXySeries        = new XyDataSeries <double>(pointsPerSlice);
            var sliceAsXySeriesYValues = sliceAsXySeries.YValues as ISciList <double>;

            sliceAsXySeriesYValues.SetCount(pointsPerSlice);

            var xValues   = new double[pointsPerSlice];
            var xRangeMin = (double)dataSeries.XRange.Min;
            var stepX     = dataSeries.StepX;

            for (int i = 0; i < pointsPerSlice; i++)
            {
                xValues[i] = xRangeMin + stepX * i;
            }

            // Init the XY series by first slice of the waterfall data series
            sliceAsXySeries.InsertRange(0, xValues, dataSeries.InternalArray[0]);
            resampledSeriesesArray[0] = sliceAsXySeries.ToPointSeries(resamplingParams, ResamplingMode.Auto, resamplerFactory, null);

            for (int i = 1; i < sliceCount; i++)
            {
                var curRow = dataSeries.GetRowAt(i);
                Array.Copy(curRow, sliceAsXySeriesYValues.ItemsArray, pointsPerSlice);

                resampledSeriesesArray[i] = sliceAsXySeries.ToPointSeries(resamplingParams, ResamplingMode.Auto, resamplerFactory, null);
            }

            var resampledPerPointsPerSlice = resampledSeriesesArray[0].Count;
            var resampledDataSeries        = new WaterfallDataSeries3D <double>(resampledPerPointsPerSlice, slicePositions);

            resampledDataSeries.StartX = dataSeries.StartX;
            resampledDataSeries.StepX  = dataSeries.StepX;
            for (int i = 0; i < sliceCount; i++)
            {
                resampledDataSeries.SetRowAt(i, resampledSeriesesArray[i].YValues.Items);
            }

            return(resampledDataSeries);
        }
Beispiel #26
0
        public AnimatedDataSeriesFilter(XyDataSeries <double, double> originalDataSeries) : base(originalDataSeries)
        {
            _originalDataSeries = originalDataSeries;

            FilteredDataSeries = _filteredDataSeries;

            FilterAll();
        }
// ReSharper disable PossibleMultipleEnumeration
        private static IXyDataSeries <double, double> GetXyDataSeries(IEnumerable <double> data)
        {
            var dataSeries = new XyDataSeries <double, double>();

            dataSeries.Append(data, data);

            return(dataSeries);
        }
Beispiel #28
0
        private static IXyDataSeries <double, double> GetXyDataSeries(double[] data)
        {
            var dataSeries = new XyDataSeries <double, double>();

            dataSeries.Append(GetXValues(data), data);

            return(dataSeries);
        }
        private IDataSeries GetData()
        {
            var data = new XyDataSeries <double>();

            data.Append(0, 0);
            data.Append(1, 1);
            data.Append(2, 2);
            return(data);
        }
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     var depthAndCurves = value as ObservableCollection<DepthCurveInfo>;
     var lstToBeUsed = depthAndCurves.Except(depthAndCurves.Where(u => u.Curve <= -999 && u.Curve >= (decimal)-999.99)).ToList();
     var dataSeries = new XyDataSeries<double, double>();
     dataSeries.AcceptsUnsortedData = true;
     lstToBeUsed.ForEach(u => dataSeries.Append((double)u.Curve, (double)u.Depth));
     return lstToBeUsed;
 }
        protected override void InitExample()
        {
            var xAxis = new SCINumericAxis {
                VisibleRange = new SCIDoubleRange(3, 6)
            };
            var yAxis = new SCINumericAxis {
                AutoRange = SCIAutoRange.Always, GrowBy = new SCIDoubleRange(0.05d, 0.05d)
            };

            var ds1 = new XyDataSeries <double, double> {
                SeriesName = "Green Series"
            };
            var ds2 = new XyDataSeries <double, double> {
                SeriesName = "Red Series"
            };
            var ds3 = new XyDataSeries <double, double> {
                SeriesName = "Gray Series"
            };
            var ds4 = new XyDataSeries <double, double> {
                SeriesName = "Gold Series"
            };

            var data1 = DataManager.Instance.GetNoisySinewave(300, 1, PointsCount, 0.25);
            var data2 = DataManager.Instance.GetSinewave(100, 2, PointsCount);
            var data3 = DataManager.Instance.GetSinewave(200, 1.5, PointsCount);
            var data4 = DataManager.Instance.GetSinewave(50, 0.1, PointsCount);

            ds1.Append(data1.XData, data1.YData);
            ds2.Append(data2.XData, data2.YData);
            ds3.Append(data3.XData, data3.YData);
            ds4.Append(data4.XData, data4.YData);

            using (Surface.SuspendUpdates())
            {
                Surface.XAxes.Add(xAxis);
                Surface.YAxes.Add(yAxis);
                Surface.RenderableSeries = new SCIRenderableSeriesCollection
                {
                    new SCIFastLineRenderableSeries {
                        DataSeries = ds1, StrokeStyle = new SCISolidPenStyle(0xFF177B17, 2f)
                    },
                    new SCIFastLineRenderableSeries {
                        DataSeries = ds2, StrokeStyle = new SCISolidPenStyle(0xFFDD0909, 2f)
                    },
                    new SCIFastLineRenderableSeries {
                        DataSeries = ds3, StrokeStyle = new SCISolidPenStyle(0xFF808080, 2f)
                    },
                    new SCIFastLineRenderableSeries {
                        DataSeries = ds4, StrokeStyle = new SCISolidPenStyle(0xFFFFD700, 2f), IsVisible = false
                    },
                };
                Surface.ChartModifiers.Add(new SCICursorModifier
                {
                    Style = { ShowAxisLabels = true, ShowTooltip = true, HitTestMode = SCIHitTestMode.Interpolate }
                });
            }
        }
        protected override void InitExample()
        {
            var xAxis = new SCINumericAxis {
                AxisAlignment = SCIAxisAlignment.Left
            };
            var yAxis = new SCINumericAxis {
                AxisAlignment = SCIAxisAlignment.Bottom, FlipCoordinates = true
            };

            var yValues1 = new[] { 0.0, 0.1, 0.2, 0.4, 0.8, 1.1, 1.5, 2.4, 4.6, 8.1, 11.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 5.4, 6.4, 7.1, 8.0, 9.0 };
            var yValues2 = new[] { 2.0, 10.1, 10.2, 10.4, 10.8, 1.1, 11.5, 3.4, 4.6, 0.1, 1.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 1.4, 0.4, 10.1, 0.0, 0.0 };
            var yValues3 = new[] { 20.0, 4.1, 4.2, 10.4, 10.8, 1.1, 11.5, 3.4, 4.6, 5.1, 5.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 1.4, 10.4, 8.1, 10.0, 15.0 };

            var ds1 = new XyDataSeries <double, double> {
                SeriesName = "data 1"
            };
            var ds2 = new XyDataSeries <double, double> {
                SeriesName = "data 2"
            };
            var ds3 = new XyDataSeries <double, double> {
                SeriesName = "data 3"
            };

            for (var i = 0; i < yValues1.Length; i++)
            {
                ds1.Append(i, yValues1[i]);
                ds2.Append(i, yValues2[i]);
                ds3.Append(i, yValues3[i]);
            }

            var series1 = GetRenderableSeries(ds1, 0xFF567893, 0xFF567893, 0xFF3D5568);
            var series2 = GetRenderableSeries(ds2, 0xFFACBCCA, 0xFFACBCCA, 0xFF439AAF);
            var series3 = GetRenderableSeries(ds3, 0xFFDBE0E1, 0xFFDBE0E1, 0xFFB6C1C3);

            var columnsCollection = new SCIVerticallyStackedColumnsCollection();

            columnsCollection.Add(series1);
            columnsCollection.Add(series2);
            columnsCollection.Add(series3);

            var animation = new SCIWaveRenderableSeriesAnimation(3, SCIAnimationCurve.EaseOut);

            animation.StartAfterDelay(0.3f);
            columnsCollection.AddAnimation(animation);

            using (Surface.SuspendUpdates())
            {
                Surface.XAxes.Add(xAxis);
                Surface.YAxes.Add(yAxis);
                Surface.RenderableSeries.Add(columnsCollection);
                Surface.ChartModifiers = new SCIChartModifierCollection
                {
                    new SCICursorModifier(),
                    new SCIZoomExtentsModifier()
                };
            }
        }
Beispiel #33
0
        private XyDataSeries <double> GetData()
        {
            var xyDataSeries = new XyDataSeries <double>();

            xyDataSeries.Append(0, 0);
            xyDataSeries.Append(1, 1);
            xyDataSeries.Append(2, 2);
            return(xyDataSeries);
        }
Beispiel #34
0
        public void AddLithologiesToTrack(TrackToShow track)
        {
            var renderableSeries = track.CurveRenderableSeries.Where(u => u.GetType() == typeof(FastLineRenderableSeries)).Select(v => v as FastLineRenderableSeries);

            FastLineRenderableSeries actualLithologySeries = null;
            actualLithologySeries = renderableSeries.SingleOrDefault(u => u.Name == "Lithology" && u.XAxisId == "Lithology");

            if (actualLithologySeries == null)
            {
                LithologyManager.Instance.AddLithologyAxisInChart(track);
                actualLithologySeries = renderableSeries.SingleOrDefault(u => u.Name == "Lithology" && u.XAxisId == "Lithology");
            }
            var lst = track.TrackObject.Lithologies;

            actualLithologySeries.IsVisible = true;
            var grouped = lst.GroupBy(u => u.LithologyName).ToList();
            var seriesCollection = new ObservableCollection<FastLineRenderableSeries>();

            var trackObject = track.TrackObject;
            var curveToShowObject = track.Curves.SingleOrDefault(u => u.RefChart == trackObject.RefChart && u.RefTrack == trackObject.ID && u.RefDataset == "Lithology");

            foreach (var obj in grouped)
            {
                var dataSeries = new XyDataSeries<double, double>();
                var fullDataSeries = new XyDataSeries<double, double>();

                string imageName = obj.Key;

                FastLineRenderableSeries normalLithologySeries = GetNormalLithologySeries(dataSeries, imageName);
                FastLineRenderableSeries fullLithologySeries = GetFullLithologySeries(fullDataSeries, imageName, track);
                ApplyBindingToNormalLithology(actualLithologySeries, normalLithologySeries);
                ApplyBindingToFullLithology(actualLithologySeries, fullLithologySeries);

                seriesCollection.Add(normalLithologySeries);
                seriesCollection.Add(fullLithologySeries);

                foreach (var item in obj)
                {
                    decimal initialDepth = item.InitialDepth;
                    decimal finalDepth = item.FinalDepth;
                    for (decimal i = initialDepth; i <= finalDepth; i++)
                    {
                        dataSeries.Append(9.5, double.Parse(i.ToString()));
                        fullDataSeries.Append(5, double.Parse(i.ToString()));
                    }
                }
                if (curveToShowObject != null)
                    actualLithologySeries.IsVisible = curveToShowObject.IsSeriesVisible;
            }
            foreach (var series in seriesCollection)
                track.CurveRenderableSeries.Add(series);
        }
Beispiel #35
0
 private static FastLineRenderableSeries GetNormalLithologySeries(XyDataSeries<double, double> dataSeries, string imageName)
 {
     return new FastLineRenderableSeries
     {
         Tag = imageName,
         DataSeries = dataSeries,
         XAxisId = "Lithology",
         ResamplingMode = ResamplingMode.None,
         PointMarker = new LithologyMarker(imageName)
         {
             Width = 50
         },
     };
 }
Beispiel #36
0
        // Business logic
        /// <summary>
        /// Add data for a symbol to the chart
        /// </summary>
        /// <param name="quoteList">Retrieved quotes</param>
        /// <param name="seriesName">Name for the series (symbol + moving average length)</param>
        private void AddSeries(SortedList<DateTime, double> quoteList, string seriesName)
        {
            // Create a new data series
            var series = new XyDataSeries<DateTime, double>();
            series.Append(quoteList.Keys, quoteList.Values);
            series.SeriesName = seriesName;
            stockChart.DataSet.Add(series);

            // Display the data via RenderableSeries
            var renderSeries = new FastMountainRenderableSeries();
            stockChart.RenderableSeries.Add(renderSeries);

            stockChart.DataSet.InvalidateParentSurface(RangeMode.ZoomToFit);
            stockChart.ZoomExtents();
        }
Beispiel #37
0
        public void AddLithologyObject(LithologyInfo lithology, ChartToShow chartToShow = null, IEnumerable<Chart> charts = null)
        {
            if (chartToShow == null)
                chartToShow = IoC.Kernel.Get<IGlobalDataModel>().MainViewModel.Charts.SingleOrDefault(u => u.ChartObject.ID == lithology.RefChart);

            if (chartToShow == null) return;

            var trackToShowObject = chartToShow.Tracks.SingleOrDefault(u => u.TrackObject.ID == lithology.RefTrack);
            if (trackToShowObject == null) return;

            if (trackToShowObject.TrackObject == null)
                throw new Exception("Track not found against track to show object while adding lithology");
            //while loading project track object would already have lithologies in it, so we dont have to re-add it in the object
            if (!trackToShowObject.TrackObject.Lithologies.Any(u => u.ID == lithology.ID))
                trackToShowObject.TrackObject.Lithologies.Add(lithology);
            FastLineRenderableSeries actualLithologySeries = null;

            //track to show object has renderable series  for lithologies
            //get the proper renderable series and add an annotation to it
            if (!trackToShowObject.CurveRenderableSeries.Any(u => (u as FastLineRenderableSeries).Name == "Lithology"))
            {
                AddLithologyAxisInChart(trackToShowObject, charts);
            }
            var normalDataSeries = new XyDataSeries<double, double>();
            var fullDataSeries = new XyDataSeries<double, double>();

            var renderableSeries = trackToShowObject.CurveRenderableSeries.Where(u => u.GetType() == typeof(FastLineRenderableSeries)).Select(v => v as FastLineRenderableSeries);
            actualLithologySeries = renderableSeries.SingleOrDefault(u => u.Name == "Lithology" && u.XAxisId == "Lithology");

            FastLineRenderableSeries normalLithologySeries = null;
            FastLineRenderableSeries fullLithologySeries = null;
            var subSeries = renderableSeries.Where(u => u.Tag != null && u.Tag.ToString() == lithology.LithologyName);
            if (!subSeries.Any())
            {
                normalLithologySeries = GetNormalLithologySeries(normalDataSeries, lithology.LithologyName);
                fullLithologySeries = GetFullLithologySeries(fullDataSeries, lithology.LithologyName, trackToShowObject);
                trackToShowObject.CurveRenderableSeries.Add(normalLithologySeries);
                trackToShowObject.CurveRenderableSeries.Add(fullLithologySeries);
                ApplyBindingToNormalLithology(actualLithologySeries, normalLithologySeries);
                ApplyBindingToFullLithology(actualLithologySeries, fullLithologySeries);

            }
            else
            {
                foreach (var series in subSeries)
                {
                    if (series.PointMarker.Width == 50)
                    {
                        normalLithologySeries = series;
                        normalDataSeries = normalLithologySeries.DataSeries as XyDataSeries<double, double>;
                    }
                    else
                    {
                        fullLithologySeries = series;
                        fullDataSeries = fullLithologySeries.DataSeries as XyDataSeries<double, double>;
                    }
                }
            }

            var startingPoint = int.Parse(lithology.InitialDepth.ToString());
            var endingPoint = int.Parse(lithology.FinalDepth.ToString());

            for (decimal i = startingPoint; i <= endingPoint; i++)
            {
                normalDataSeries.Append(9.5, double.Parse(i.ToString()));
                fullDataSeries.Append(5, double.Parse(i.ToString()));
            }
        }
		/// <summary>
		/// To analyze.
		/// </summary>
		protected override void OnAnalyze()
		{
			var chart = Chart;
			var grid = Grid;

			var chartSeries = new XyDataSeries<double, double>();
			ThreadSafeObservableCollection<GridRow> gridSeries = null;

			chart.GuiSync(() =>
			{
				// clear prev values
				chart.RenderableSeries.Clear();
				grid.Columns.Clear();

				chart.RenderableSeries.Add(new FastColumnRenderableSeries
				{
					ResamplingMode = ResamplingMode.None,
					DataPointWidth = 1,
					SeriesColor = Colors.Chocolate,
					DataSeries = chartSeries
				});

				chart.XAxis = new NumericAxis { AxisTitle = LocalizedStrings.Price };
				chart.YAxis = new NumericAxis { AxisTitle = LocalizedStrings.Volume, GrowBy = new DoubleRange(0, 0.1) };

				grid.AddTextColumn("Price", LocalizedStrings.Price).Width = 150;
				var volumeColumn = grid.AddTextColumn("Volume", LocalizedStrings.Volume);
				volumeColumn.Width = 100;

				var gridSource = new ObservableCollectionEx<GridRow>();
				grid.ItemsSource = gridSource;
				gridSeries = new ThreadSafeObservableCollection<GridRow>(gridSource);

				grid.SetSort(volumeColumn, ListSortDirection.Descending);
			});

			// get candle storage
			var storage = StorateRegistry.GetCandleStorage(typeof(TimeFrameCandle), Security, TimeFrame, format: StorageFormat);

			// get available dates for the specified period
			var dates = storage.GetDates(From, To).ToArray();

			var rows = new Dictionary<decimal, GridRow>();

			foreach (var loadDate in dates)
			{
				// check if stopped
				if (ProcessState != ProcessStates.Started)
					break;

				// load candles
				var candles = storage.Load(loadDate);

				// groupping candles by candle's middle price
				var groupedCandles = candles.GroupBy(c => c.LowPrice + c.GetLength() / 2);

				foreach (var group in groupedCandles.OrderBy(g => g.Key))
				{
					// check if stopped
					if (ProcessState != ProcessStates.Started)
						break;

					var price = group.Key;

					// calc total volume for the specified time frame
					var sumVol = group.Sum(c => c.TotalVolume);

					var row = rows.TryGetValue(price);
					if (row == null)
					{
						// new price level
						rows.Add(price, row = new GridRow { Price = price, Volume = sumVol });

						// draw on chart
						chartSeries.Append((double)price, (double)sumVol);

						// draw on table
						gridSeries.Add(row);
					}
					else
					{
						// update existing price level
						row.Volume += sumVol;

						// update chart
						chartSeries.Update((double)price, (double)row.Volume);
					}
				}

				chart.GuiAsync(() =>
				{
					// update grid sorting
					grid.RefreshSort();

					// scale chart
					chart.ZoomExtents();
				});
			}

			// notify the script stopped
			Stop();
		}
		/// <summary>
		/// To analyze.
		/// </summary>
		protected override void OnAnalyze()
		{
			var chart = Chart;
			var grid = Grid;

			var chartSeries = new XyDataSeries<double, double>();
			ThreadSafeObservableCollection<GridRow> gridSeries = null;

			chart.GuiSync(() =>
			{
				// очищаем данные с предыдущего запуска скрипта
				chart.RenderableSeries.Clear();
				grid.Columns.Clear();

				chart.RenderableSeries.Add(new FastColumnRenderableSeries
				{
					ResamplingMode = ResamplingMode.None,
					DataPointWidth = 1,
					SeriesColor = Colors.Chocolate,
					DataSeries = chartSeries
				});

				chart.XAxis = new NumericAxis { AxisTitle = LocalizedStrings.Price };
				chart.YAxis = new NumericAxis { AxisTitle = LocalizedStrings.Volume, GrowBy = new DoubleRange(0, 0.1) };

				grid.AddTextColumn("Price", LocalizedStrings.Price).Width = 150;
				var volumeColumn = grid.AddTextColumn("Volume", LocalizedStrings.Volume);
				volumeColumn.Width = 100;

				var gridSource = new ObservableCollectionEx<GridRow>();
				grid.ItemsSource = gridSource;
				gridSeries = new ThreadSafeObservableCollection<GridRow>(gridSource);

				grid.SetSort(volumeColumn, ListSortDirection.Descending);
			});

			// получаем хранилище свечек
			var storage = StorateRegistry.GetCandleStorage(typeof(TimeFrameCandle), Security, TimeFrame, format: StorageFormat);

			// получаем набор доступных дат за указанный период
			var dates = storage.GetDates(From, To).ToArray();

			var rows = new Dictionary<decimal, GridRow>();

			foreach (var loadDate in dates)
			{
				// проверяем флаг остановки
				if (ProcessState != ProcessStates.Started)
					break;

				// загружаем свечки
				var candles = storage.Load(loadDate);

				// группируем свечки по цене (середина свечи)
				var groupedCandles = candles.GroupBy(c => c.LowPrice + c.GetLength() / 2);

				foreach (var group in groupedCandles.OrderBy(g => g.Key))
				{
					// проверяем флаг остановки
					if (ProcessState != ProcessStates.Started)
						break;

					var price = group.Key;

					// получаем суммарный объем в пределах ценового уровня за день
					var sumVol = group.Sum(c => c.TotalVolume);

					var row = rows.TryGetValue(price);
					if (row == null)
					{
						// пришел новый уровень - добавляем новую запись
						rows.Add(price, row = new GridRow { Price = price, Volume = sumVol });

						// выводим на график
						chartSeries.Append((double)price, (double)sumVol);

						// выводит в таблицу
						gridSeries.Add(row);
					}
					else
					{
						// увеличиваем суммарный объем
						row.Volume += sumVol;

						// обновляем график
						chartSeries.Update((double)price, (double)row.Volume);
					}
				}

				chart.GuiAsync(() =>
				{
					// обновление сортировки в таблице
					grid.RefreshSort();

					// автомасштабирование графика
					chart.ZoomExtents();
				});
			}

			// оповещаем программу об окончании выполнения скрипта
			base.Stop();
		}
        public ChartViewModel()
        {
            this.SetDefaults();

            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
                _marketDataService = new MarketDataService(new DateTime(2015, 08, 11), 1, 5000);
            }
            else
            {
                // Code runs "for real"
                _marketDataService = new MarketDataService(new DateTime(2015, 08, 11), 1, 1000);
            }

            var ds0 = new OhlcDataSeries<DateTime, double>();
            _seriesViewModels.Add(new ChartSeriesViewModel(ds0, new FastOhlcRenderableSeries() { Name = "Series1", XAxisId = "dateTimeXAxis", YAxisId = "Y1" }));
            // Append 500 historical bars to data series
            var prices = _marketDataService.GetHistoricalData(500);
            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));

            //Create price/volume distribution
            double minPrice = prices.Select(x => x.Low).Min();
            double maxPrice = prices.Select(x => x.High).Max();

            int numBins = 5;
            double interval = (maxPrice - minPrice) / numBins;
            var bins = new Tuple<double, double>[numBins];
            double binLower = minPrice;
            for (int i = 0; i < numBins; i++)
            {
                bins[i] = new Tuple<double, double>(binLower, binLower + interval);
                binLower += interval;
            }

            var dsVolByPrice = new XyDataSeries<double, double>();
            _seriesViewModels.Add(new ChartSeriesViewModel(dsVolByPrice, new FastColumnRenderableSeries() { Name = "PriceByVol", XAxisId = "verticalXAxis", YAxisId = "Y2" }));

            var dblVolume = new List<double>();
            for (int i = 0; i < numBins; i++) dblVolume.Add(10 - i);

            dsVolByPrice.Append(bins.Select(x => x.Item1), dblVolume);

            _marketDataService.SubscribePriceUpdate(OnNewPrice);
            _xVisibleRange = new IndexRange(0, 1000);

            SelectedChartType = ChartType.FastOhlc;

            //this.DeleteCommand = new RelayCommand(DeleteCommandExecuted);
        }
Beispiel #41
0
 private static FastLineRenderableSeries GetFullLithologySeries(XyDataSeries<double, double> dataSeries, string imageName, TrackToShow track)
 {
     var marker = new LithologyMarker(imageName)
     {
         Fill = Colors.Red,
         Stroke = Colors.Green
     };
     FastLineRenderableSeries series = new FastLineRenderableSeries
     {
         Tag = imageName,
         DataSeries = dataSeries,
         XAxisId = "Lithology",
         ResamplingMode = ResamplingMode.None,
         PointMarker = marker
     };
     BindingOperations.SetBinding(marker, LithologyMarker.WidthProperty, new Binding("Width")
     {
         Source = track.TrackObject
     });
     return series;
 }