예제 #1
0
파일: FTest.cs 프로젝트: Dev9er/ChartStudy
        /// <summary>
        /// Fill Data points with values from F distribution
        /// </summary>
        private void FillFDistribution(int n, int m)
        {
            // Clear all data points
            chart1.Series[2].Points.Clear();

            // Set axis values
            chart1.ChartAreas[1].AxisX.Minimum = 0;
            chart1.ChartAreas[1].AxisX.Maximum = 6;
            chart1.ChartAreas[1].AxisY.Minimum = 0;
            chart1.ChartAreas[1].AxisY.Maximum = 1.0;

            // Calculate Beta function
            double beta = chart1.DataManipulator.Statistics.BetaFunction(n / 2.0, m / 2.0);

            // Find coefficient
            double y;
            double coef = Math.Pow((double)(n) / (double)(m), n / 2.0) / beta;
            double doubleX;

            // Go throw all data points and calculate values
            for (double x = 0.01; x <= 15; x += 0.1)
            {
                doubleX = x;
                y       = coef * Math.Pow(doubleX, n / 2.0 - 1.0) / Math.Pow(1.0 + n * doubleX / m, (n + m) / 2.0);

                // Add data point
                chart1.Series[2].Points.AddXY(doubleX, y);
            }

            // Refresh chart
            chart1.Invalidate();
        }
예제 #2
0
파일: TTest.cs 프로젝트: Dev9er/ChartStudy
        /// <summary>
        /// Fill Data points with T Distribution
        /// </summary>
        private void FillTDistribution( )
        {
            // Clear all existing data points
            chart1.Series[2].Points.Clear();

            // Set Axis values
            chart1.ChartAreas[1].AxisX.Minimum                = -5;
            chart1.ChartAreas[1].AxisX.Maximum                = 5;
            chart1.ChartAreas[1].AxisY.Minimum                = 0;
            chart1.ChartAreas[1].AxisY.Maximum                = 0.5;
            chart1.ChartAreas[1].AxisX.LabelStyle.Interval    = 2;
            chart1.ChartAreas[1].AxisX.MajorTickMark.Interval = 2;

            // Calculate Beta function
            double n    = 6;
            double beta = chart1.DataManipulator.Statistics.BetaFunction(0.5, n / 2.0);

            // Calculate coefficient of T Distribution
            double y;
            double coef = Math.Pow(n, -0.5) / beta;
            double doubleX;

            // Calculate Data Points
            for (int x = -120; x <= 120; x++)
            {
                doubleX = x / 10.0;
                y       = coef / Math.Pow(1.0 + doubleX * doubleX / n, (n + 1.0) / 2.0);

                // Add X and Y values to data points
                chart1.Series[2].Points.AddXY(doubleX, y);
            }

            // Refresh chart
            chart1.Invalidate();
        }
예제 #3
0
        private void StartTest()
        {
            // Calculate probability
            double probability = double.Parse(this.comboBox2.Text);

            probability = 1.0 - probability / 100.0;

            // Make FTest
            AnovaResult result = chart1.DataManipulator.Statistics.Anova(probability, "Group1,Group2,Group3");

            // Fill labels with results
            this.label9.Text  = result.SumOfSquaresBetweenGroups.ToString("G3");
            this.label12.Text = result.SumOfSquaresWithinGroups.ToString("G3");
            this.label15.Text = result.SumOfSquaresTotal.ToString("G3");
            this.label10.Text = result.DegreeOfFreedomBetweenGroups.ToString("G3");
            this.label13.Text = result.DegreeOfFreedomWithinGroups.ToString("G3");
            this.label16.Text = result.DegreeOfFreedomTotal.ToString("G3");
            this.label11.Text = result.MeanSquareVarianceBetweenGroups.ToString("G3");
            this.label14.Text = result.MeanSquareVarianceWithinGroups.ToString("G3");
            this.label19.Text = result.FRatio.ToString("G3");
            this.label20.Text = result.FCriticalValue.ToString("G3");

            // Refresh Chart
            chart1.Invalidate();
        }
예제 #4
0
        private void StartTest()
        {
            // Calculate descriptive statistics
            double mean     = chart1.DataManipulator.Statistics.Mean("Series1");
            double median   = chart1.DataManipulator.Statistics.Median("Series1");
            double variance = chart1.DataManipulator.Statistics.Variance("Series1", true);

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[0].IntervalOffset = mean - Math.Sqrt(variance);
            chart1.ChartAreas[0].AxisY.StripLines[0].StripWidth     = 2.0 * Math.Sqrt(variance);

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[1].IntervalOffset = mean;

            // Set Strip line item
            chart1.ChartAreas[0].AxisY.StripLines[2].IntervalOffset = median;

            // Fill labels
            this.label2.Text = mean.ToString("G5");
            this.label3.Text = Math.Sqrt(variance).ToString("G5");
            this.label5.Text = median.ToString("G5");

            // Refresh Chart
            chart1.Invalidate();
        }
예제 #5
0
 private void numericUpDownWidth_ValueChanged(object sender, System.EventArgs e)
 {
     foreach (Series ser in Chart1.Series)
     {
         ser["PixelPointWidth"] = numericUpDownWidth.Value.ToString();
     }
     Chart1.Invalidate();
 }
예제 #6
0
        /// <summary>
        /// Mouse Move Event
        /// </summary>
        private void Chart1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // Check if data point selected
            if (selectedDataPoint != null)
            {
                // Mouse coordinates should not be outside of the chart
                int coordinate = e.Y;
                if (coordinate < 0)
                {
                    coordinate = 0;
                }
                if (coordinate > Chart1.Size.Height - 1)
                {
                    coordinate = Chart1.Size.Height - 1;
                }

                // Calculate new Y value from current cursor position
                double yValue = Chart1.ChartAreas["Default"].AxisY.PixelPositionToValue(coordinate);
                yValue = Math.Min(yValue, Chart1.ChartAreas["Default"].AxisY.Maximum);
                yValue = Math.Max(yValue, Chart1.ChartAreas["Default"].AxisY.Minimum);


                if ((yValue <= 0) &&
                    (Chart1.Series["Default"].ChartType == SeriesChartType.Column))
                {
                    yValue = 0.01;
                }

                // Update selected point Y value
                selectedDataPoint.YValues[0] = yValue;


                // Invalidate chart
                Chart1.Invalidate();

                // Force the chart to redraw
                Chart1.Update();
            }
            else
            {
                // Set different shape of cursor over the data points
                HitTestResult hitResult = Chart1.HitTest(e.X, e.Y);
                if (hitResult.ChartElementType == ChartElementType.DataPoint)
                {
                    Chart1.Cursor = Cursors.Hand;
                }
                else
                {
                    Chart1.Cursor = Cursors.Default;
                }
            }
        }
예제 #7
0
        private void Chart1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.X != 0 && e.Y != 0)
            {
                ElementPosition position = Chart1.Legends[0].Position;
                // Conver pixels to percentage coordinates and set legend position
                position.X = e.X * 100F / ((float)(Chart1.Size.Width - 1));
                position.Y = e.Y * 100F / ((float)(Chart1.Size.Height - 1));

                AdjustLegendControls();

                Chart1.Invalidate();
            }
        }
예제 #8
0
 public void AddPlot(List<double> values, string title = "")
 {
     Chart chart = new Chart();
     Series series = new Series();
     ChartArea chartArea1 = new ChartArea();
     chartArea1.Name = "ChartArea1";
     chart.ChartAreas.Add(chartArea1);
     series.BorderWidth = 2;
     series.BorderDashStyle = ChartDashStyle.Solid;
     series.ChartType = SeriesChartType.Line;
     series.Color = Color.Green;
     for (int i = 0; i < values.Count; i++)
     {
         series.Points.AddXY(i, values[i]);
     }
     chart.BorderlineColor = Color.Red;
     chart.BorderlineWidth = 1;
     chart.Series.Add(series);
     chart.Titles.Add(title);
     chart.Invalidate();
     chart.Palette = ChartColorPalette.Fire;
     chartArea1.AxisY.Minimum = values.Min();
     chartArea1.AxisY.Maximum = values.Max();
     AddChartInRuntime(chart);
 }
예제 #9
0
        public void CreateChart(string name)
        {
            Run(() =>
            {
                ControlInvoke(pnlCharts, new Action(() => pnlCharts.Controls.Clear()));

                chartControl      = new System.Windows.Forms.DataVisualization.Charting.Chart();
                chartControl.Name = name;
                chartControl.Titles.Add(name);

                chartControl.Height            = chartHeight;
                chartControl.Width             = chartWidth;
                chartControl.Visible           = true;
                ChartArea chartArea            = new ChartArea();
                chartArea.Area3DStyle.Enable3D = false;

                chartControl.ChartAreas.Add(chartArea);
                chartControl.Dock = DockStyle.Fill;
                chartControl.Invalidate();

                ControlInvoke(pnlCharts, new Action(() =>
                {
                    pnlCharts.Controls.Add(chartControl);
                }));
            });
        }
예제 #10
0
        private void RenderChart(Chart chart, string chartName)
        {
            chart.Invalidate();

            var path = Path.Combine(_directory, chartName.Replace(":", "-"));
            path = Path.ChangeExtension(path, "png");
            chart.SaveImage(path, ChartImageFormat.Png);
        }
예제 #11
0
        /// <summary>
        /// Random Stock Data Generator
        /// </summary>
        /// <param name="series">Data series</param>
        private void Data(Series series)
        {
            Random rand;

            // Use a number to calculate a starting value for
            // the pseudo-random number sequence
            rand = new Random(randomSeed);

            // The number of days for stock data
            int period = int.Parse(comboBoxNumberOfDays.Text);

            chart1.Series["Input"].Points.Clear();

            // The first High value
            double high = rand.NextDouble() * 40;

            // The first Close value
            double close = high - rand.NextDouble();

            // The first Low value
            double low = close - rand.NextDouble();

            // The first Open value
            double open = (high - low) * rand.NextDouble() + low;

            // The first day X and Y values
            chart1.Series["Input"].Points.AddXY(DateTime.Parse("1/1/2002"), high);
            chart1.Series["Input"].Points[0].YValues[1] = low;

            // The Open value is not used.
            chart1.Series["Input"].Points[0].YValues[2] = open;
            chart1.Series["Input"].Points[0].YValues[3] = close;

            // Days loop
            for (int day = 1; day < period; day++)
            {
                // Calculate High, Low and Close values
                high  = chart1.Series["Input"].Points[day - 1].YValues[2] + rand.NextDouble();
                close = high - rand.NextDouble();
                low   = close - rand.NextDouble();
                open  = (high - low) * rand.NextDouble() + low;

                // The low cannot be less than yesterday close value.
                if (low > chart1.Series["Input"].Points[day - 1].YValues[2])
                {
                    low = chart1.Series["Input"].Points[day - 1].YValues[2];
                }

                // Set data points values
                chart1.Series["Input"].Points.AddXY(day, high);
                chart1.Series["Input"].Points[day].XValue     = chart1.Series["Input"].Points[day - 1].XValue + 1;
                chart1.Series["Input"].Points[day].YValues[1] = low;
                chart1.Series["Input"].Points[day].YValues[2] = open;
                chart1.Series["Input"].Points[day].YValues[3] = close;
            }

            chart1.Invalidate();
        }
        private void ResetPosition_Click(object sender, System.EventArgs e)
        {
            Chart1.Annotations[0].AnchorX         = double.NaN;
            Chart1.Annotations[0].AnchorY         = double.NaN;
            Chart1.Annotations[0].AnchorDataPoint = Chart1.Series[0].Points[2];

            UpdateAnnotationPosition(Chart1.Annotations[0]);

            Chart1.Invalidate();
        }
        /// <summary>
        /// This method calculates Envelopes or Bollinger Bands
        /// formulas
        /// </summary>
        private void Calculations()
        {
            // Set Formula Name
            string formulaName = comboBoxFormulaName.Text;

            // Formulas with one input value
            chart1.DataManipulator.FinancialFormula(FinancialFormula.MovingAverage, "10", "Input:Y", "Moving Average");

            // Bollinger Bands
            if (formulaName == "BollingerBands")
            {
                chart1.DataManipulator.FinancialFormula(FinancialFormula.BollingerBands, "10,2", "Input:Y", "Indicators,Indicators:Y2");
            }
            // Envelopes
            else if (formulaName == "Envelopes")
            {
                chart1.DataManipulator.FinancialFormula(FinancialFormula.Envelopes, "10,5", "Input:Y", "Indicators,Indicators:Y2");
            }

            chart1.Invalidate();
        }
        public void FillData()
        {
            // Populate series data
            Random random = new Random();

            chart1.Series["Series1"].Points.Clear();
            for (int pointIndex = 0; pointIndex < 100; pointIndex++)
            {
                chart1.Series["Series1"].Points.AddXY(random.Next(1, 19), random.Next(1, 19), random.Next(1, 19));
            }
            chart1.Invalidate();
        }
        /// <summary>
        /// Fill data points with values from Normal distribution
        /// </summary>
        private void FillNormalDistribution( )
        {
            // Remove all data points from series
            chart1.Series[0].Points.Clear();

            // Disable combo boxes for degree of freedom
            this.comboBox3.Enabled = false;
            this.comboBox4.Enabled = false;
            this.checkBox1.Enabled = true;

            // Set formula background image
            chart1.ChartAreas[0].BackImage = GetImage("Normal.gif");

            // Set axis values
            chart1.ChartAreas[0].AxisX.Minimum        = -5;
            chart1.ChartAreas[0].AxisX.Maximum        = 5;
            chart1.ChartAreas[0].AxisY.Minimum        = 0;
            chart1.ChartAreas[0].AxisY.Maximum        = 0.5;
            chart1.ChartAreas[0].AxisX.Interval       = 2;
            chart1.ChartAreas[0].AxisX.IntervalOffset = 1;

            // Calculate coefficient
            double y;
            double coef = 1.0 / Math.Sqrt(2 * Math.PI);
            double doubleX;

            // Fill data points with values from Normal distribution
            for (int x = -50; x <= 50; x++)
            {
                doubleX = x / 10.0;
                y       = coef * Math.Exp(doubleX * doubleX / -2);
                chart1.Series[0].Points.AddXY(doubleX - 0.05, y);
            }

            // Selection mode for normal distribution
            this.SelectNormalDistribution();

            // Refresh chart
            chart1.Invalidate();
        }
예제 #16
0
        private void PointsNumberList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Populate series data
            Random   random      = new Random();
            DateTime dateCurrent = DateTime.Now.Date;

            Chart1.Series["Series1"].Points.Clear();
            for (int pointIndex = 0; pointIndex < int.Parse(PointsNumberList.GetItemText(PointsNumberList.SelectedItem)); pointIndex++)
            {
                Chart1.Series["Series1"].Points.AddXY(dateCurrent.AddDays(pointIndex), random.Next(100, 1000));
            }
            Chart1.Invalidate();
        }
예제 #17
0
        /// <summary>
        /// This method calculates Time series.
        /// </summary>
        private void Calculations()
        {
            if (comboBoxRegressionType.Text != "Polynomial")
            {
                comboBoxOrder.Enabled = false;
            }
            else
            {
                comboBoxOrder.Enabled = true;
            }

            string typeRegression;

            if (comboBoxRegressionType.Text != "Polynomial")
            {
                typeRegression = comboBoxRegressionType.Text;
            }
            else
            {
                typeRegression = comboBoxOrder.Text;
            }

            // The number of days for Forecasting
            int forecasting = int.Parse(comboBoxForecasting.Text);

            // Show Error as a range chart
            string error = checkBoxError.Checked.ToString();

            // Show Error as a range chart
            string forecastingError = checkBoxForecastingError.Checked.ToString();

            //  Formula parameters
            string parameters = typeRegression + ',' + forecasting + ',' + error + ',' + forecastingError;

            chart1.DataManipulator.FinancialFormula(FinancialFormula.Forecasting, parameters, "Input:Y", "Forecasting:Y,Range:Y,Range:Y2");
            chart1.Series["Range"].Enabled = checkBoxError.Checked || checkBoxForecastingError.Checked;

            chart1.Invalidate();
        }
        private void UpdateChartSettings()
        {
            // Bind chart data
            double[] yValues1 = new double[] { 216.1, 125.8, 2.6, 97.3, 45.7, 25.3 };
            double[] yValues2 = new double[] { 232.8, 195.4, 172.9, 100.3, 45.7, 25.3 };
            chart1.Series["Default"].Points.DataBindY((comboBoxFunnelStyle.SelectedIndex == 0) ? yValues1 : yValues2);

            // Set funnel style
            chart1.Series["Default"]["FunnelStyle"] = (string)comboBoxFunnelStyle.SelectedItem;

            // Set funnel data point labels style
            chart1.Series["Default"]["FunnelLabelStyle"] = (string)comboBoxLabelsStyle.SelectedItem;

            // Set labels placement
            if (comboBoxLabelsStyle.SelectedIndex == 0 ||
                comboBoxLabelsStyle.SelectedIndex == 1)
            {
                chart1.Series["Default"]["FunnelOutsideLabelPlacement"] = (string)comboBoxLabelsPlacement.SelectedItem;
            }
            else
            {
                chart1.Series["Default"]["FunnelInsideLabelAlignment"] = (string)comboBoxLabelsPlacement.SelectedItem;
            }

            // Set gap between points
            chart1.Series["Default"]["FunnelPointGap"] = numericUpDownGap.Value.ToString();

            // Set minimum point height
            chart1.Series["Default"]["FunnelMinPointHeight"] = numericUpDownMinHeight.Value.ToString();

            // Set 3D mode
            chart1.ChartAreas["Default"].Area3DStyle.Enable3D = checkBoxShow3D.Checked;

            // Set 3D angle
            chart1.Series["Default"]["Funnel3DRotationAngle"] = numericUpDownAngle.Value.ToString();

            // Set 3D drawing style
            chart1.Series["Default"]["Funnel3DDrawingStyle"] = (string)comboBox3DDrawingStyle.SelectedItem;

            // Disable/Enable controls
            numericUpDownAngle.Enabled          = checkBoxShow3D.Checked;
            labelAngle.Enabled                  = checkBoxShow3D.Checked;
            comboBox3DDrawingStyle.Enabled      = checkBoxShow3D.Checked;
            label3DDrawingStyle.Enabled         = checkBoxShow3D.Checked;
            comboBoxLabelsPlacement.Enabled     = comboBoxLabelsStyle.SelectedIndex != 3;
            labelOutsideLabelsPlacement.Enabled = comboBoxLabelsStyle.SelectedIndex != 3;

            chart1.Invalidate();
        }
예제 #19
0
        private void PopulateData()
        {
            // Prepare data base connection and query strings
            System.Windows.Forms.DataVisualization.Charting.Utilities.SampleMain.MainForm mainForm = (System.Windows.Forms.DataVisualization.Charting.Utilities.SampleMain.MainForm) this.ParentForm;
            string fileNameString = mainForm.applicationPath + "\\";

            fileNameString += "data\\chartdata.mdb";
            string myConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameString;
            string mySelectQuery      = "SELECT * FROM STOCKDATA WHERE SymbolName = '" + comboBoxStockSymbol.Text + "' ORDER BY Date";

            // Open data base connection
            OleDbConnection myConnection = new OleDbConnection(myConnectionString);
            OleDbCommand    myCommand    = new OleDbCommand(mySelectQuery, myConnection);

            myCommand.Connection.Open();

            // Create a database reader
            OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            // Data bind to the reader
            chart1.Series["StockPrice"].Points.Clear();
            chart1.Series["StockPrice"].Points.DataBindXY(myReader, "Date", myReader, "High,Low,Open,Close");

            // Group series data points by interval. Different formulas are used for each Y value:
            //   Y1 (High) - maximum of all Y1 points values in the group
            //   Y2 (Low) - minimum of all Y2 points values in the group
            //   Y3 (Open) - Y3 value of the first point in the group
            //   Y4 (Close) - Y4 value of the last point in the group
            chart1.Series["GroupedStockPrice"].Points.Clear();
            if (comboBoxGroupingInterval.Text == "Week")
            {
                chart1.DataManipulator.Group("Y1:MAX,Y2:MIN,Y3:FIRST,Y4:LAST", 1, IntervalType.Weeks, "StockPrice", "GroupedStockPrice");
            }
            else if (comboBoxGroupingInterval.Text == "Month")
            {
                chart1.DataManipulator.Group("Y1:MAX,Y2:MIN,Y3:FIRST,Y4:LAST", 1, IntervalType.Months, "StockPrice", "GroupedStockPrice");
            }
            else if (comboBoxGroupingInterval.Text == "Quarter")
            {
                chart1.DataManipulator.Group("Y1:MAX,Y2:MIN,Y3:FIRST,Y4:LAST", 3, IntervalType.Months, "StockPrice", "GroupedStockPrice");
            }

            // close the reader and the connection
            myReader.Close();
            myConnection.Close();

            chart1.ResetAutoValues();
            chart1.Invalidate();
        }
        private void Calculations()
        {
            // Set Formula Name
            string           formulaName = comboBoxFormulaName.Text;
            FinancialFormula formula     = (FinancialFormula)Enum.Parse(typeof(FinancialFormula), formulaName, true);

            // Easy of movement
            if (formulaName == "EaseOfMovement")
            {
                chart1.DataManipulator.FinancialFormula(formula, "Input:Y,Input:Y2,Volume", "Indicators");
            }
            // Money Flow
            else if (formulaName == "MoneyFlow")
            {
                chart1.DataManipulator.FinancialFormula(formula, "20", "Input:Y,Input:Y2,Input:Y4,Volume", "Indicators");
                chart1.ChartAreas["Indicator"].AxisX.Minimum = DateTime.Parse("1/1/2002").ToOADate();
            }
            // Chaikin Oscillator
            else if (formulaName == "ChaikinOscillator")
            {
                chart1.DataManipulator.FinancialFormula(formula, "5,12", "Input:Y,Input:Y2,Input:Y4,Volume", "Indicators");
                chart1.ChartAreas["Indicator"].AxisX.Minimum = DateTime.Parse("1/1/2002").ToOADate();
            }
            // Formulas which use one price and volume.
            else if (formulaName == "NegativeVolumeIndex" || formulaName == "OnBalanceVolume" || formulaName == "PositiveVolumeIndex" || formulaName == "PriceVolumeTrend")
            {
                chart1.DataManipulator.FinancialFormula(formula, "100", "Input:Y4,Volume", "Indicators");
            }
            // All other formulas.
            else
            {
                chart1.DataManipulator.FinancialFormula(formula, "Input:Y,Input:Y2,Input:Y4,Volume", "Indicators");
            }

            chart1.Invalidate();
        }
예제 #21
0
        private void StartTest()
        {
            chart1.Series["SecondGroup"].Points.Clear();
            chart1.Series["SecondGroup"].ChartArea = "";
            foreach (DataPoint point in chart1.Series["FirstGroup"].Points)
            {
                chart1.Series["SecondGroup"].Points.AddXY(point.XValue, point.XValue);
            }

            // Calculate Covariance
            double result = chart1.DataManipulator.Statistics.Covariance("FirstGroup", "SecondGroup");

            // Fill labels with results
            this.label1.Text = "Covariance";
            this.label2.Text = result.ToString("G4");

            // Calculate Correlation
            result = chart1.DataManipulator.Statistics.Correlation("FirstGroup", "SecondGroup");

            this.label3.Text = "Correlation";
            this.label4.Text = result.ToString("G4");

            chart1.Series["Result"].Points.Clear();

            Series rangeSeries = chart1.Series.Add("Range");

            rangeSeries.ChartType = SeriesChartType.Range;

            // Calculate Best Fit
            chart1.DataManipulator.FinancialFormula(FinancialFormula.Forecasting, "2,0", "FirstGroup", "Result:Y,Range:Y,Range:Y2");

            chart1.Series.Remove(rangeSeries);

            // Refresh Chart
            chart1.Invalidate();
        }
예제 #22
0
        private void checkBoxGrouped_CheckedChanged(object sender, System.EventArgs e)
        {
            if (checkBoxGrouped.Checked)
            {
                chart1.Series["Series1"]["StackedGroupName"] = "Group1";
                chart1.Series["Series2"]["StackedGroupName"] = "Group1";
                chart1.Series["Series3"]["StackedGroupName"] = "Group2";
                chart1.Series["Series4"]["StackedGroupName"] = "Group2";

                chart1.ResetAutoValues();
                chart1.Invalidate();
            }

            else
            {
                foreach (Series series in chart1.Series)
                {
                    series["StackedGroupName"] = "";
                }

                chart1.ResetAutoValues();
                chart1.Invalidate();
            }
        }
예제 #23
0
        private void tsmzoom_Click(object sender, EventArgs e)
        {
            //this.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
            //this.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            Control c = this.Parent;

            chartcopy = this;

            ZoomedChart frm = new ZoomedChart(this);

            frm.WindowState = FormWindowState.Maximized;
            frm.ShowDialog();

            c.Controls.Add(chartcopy);
            chartcopy.Invalidate();
            chartcopy.Show();
        }
예제 #24
0
        //Creating a fun little graph
        public static void CreateGraph(YearMap yearMap)
        {
            //Order the list of keys to get all of the years and find out how many years there were that someone lived in
            var orderedList = yearMap.YearVals.Keys.OrderBy(x => x).ToArray();
            var numberOfYears = orderedList.Count();

            var xvals = new int[numberOfYears];
            var yvals = new int[numberOfYears];
            for (int i = 0; i < yvals.Length; i++)
            {
                yvals[i] = yearMap.YearVals[orderedList[i]];
                xvals[i] = orderedList[i];
            }

            var chart = new Chart();
            chart.Size = new Size(1000, 1000);
            Title title = new Title("Number of people alive each year");
            title.Font = new Font("Calibri", 16, System.Drawing.FontStyle.Bold);
            chart.Titles.Add(title);

            var chartArea = new ChartArea();
            chartArea.AxisX.LabelStyle.Font = new Font("Calibri", 8);
            chartArea.AxisY.LabelStyle.Font = new Font("Calibri", 8);
            chartArea.AxisY.Minimum = 0;
            chartArea.AxisX.Minimum = 1900;
            chartArea.AxisX.Maximum = 2000;
            chartArea.AxisX.Title = "Years";
            chartArea.AxisX.TitleFont = new Font("Calibri", 14, System.Drawing.FontStyle.Bold);
            chartArea.AxisY.Title = "Number of People Alive";
            chartArea.AxisY.TitleFont = new Font("Calibri", 14, System.Drawing.FontStyle.Bold);
            chartArea.AxisY.Interval = 1;
            chartArea.AxisX.Interval = 5;

            chart.ChartAreas.Add(chartArea);

            var series = new Series();
            series.Name = "Series";
            series.ChartType = SeriesChartType.Bar;
            chart.Series.Add(series);

            chart.Series["Series"].Points.DataBindXY(xvals, yvals);

            chart.Invalidate();

            chart.SaveImage("../../Output/chart.png", ChartImageFormat.Png);
        }
예제 #25
0
        /// <summary>
        /// The AddNewPoint function is called for each series in the chart when
        /// new points need to be added.  The new point will be placed at specified
        /// X axis (Date/Time) position with a Y value in a range +/- 1 from the previous
        /// data point's Y value, and not smaller than zero.
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <param name="ptSeries"></param>
        public void AddNewPoint(DateTime timeStamp, System.Windows.Forms.DataVisualization.Charting.Series ptSeries)
        {
            // Add new data point to its series.
            ptSeries.Points.AddXY(timeStamp.ToOADate(), rand.Next(10, 20));

            // remove all points from the source series older than 20 seconds.
            double removeBefore = timeStamp.AddSeconds((double)(20) * (-1)).ToOADate();

            //remove oldest values to maintain a constant number of data points
            while (ptSeries.Points[0].XValue < removeBefore)
            {
                ptSeries.Points.RemoveAt(0);
            }

            chart1.ChartAreas[0].AxisX.Minimum = ptSeries.Points[0].XValue;
            chart1.ChartAreas[0].AxisX.Maximum = DateTime.FromOADate(ptSeries.Points[0].XValue).AddSeconds(30).ToOADate();

            chart1.Invalidate();
        }
예제 #26
0
        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Series.Clear();
            var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name              = "Series1",
                Color             = System.Drawing.Color.Green,
                IsVisibleInLegend = false,
                IsXValueIndexed   = true,
                ChartType         = SeriesChartType.Line
            };

            this.chart1.Series.Add(series1);

            for (int i = 0; i < results.Count; i++)
            {
                series1.Points.AddXY(i, results[i]);
            }
            chart1.Invalidate();
        }
예제 #27
0
        private void timerRealTimeData_Tick(object sender, System.EventArgs e)
        {
            // Define some variables
            int numberOfPointsInChart      = int.Parse(comboBoxVisiblePoints.Text);
            int numberOfPointsAfterRemoval = numberOfPointsInChart - int.Parse(comboBoxPointsRemoved.Text);

            // Simulate adding new data points
            int numberOfPointsAddedMin = 5;
            int numberOfPointsAddedMax = 10;

            for (int pointNumber = 0; pointNumber <
                 random.Next(numberOfPointsAddedMin, numberOfPointsAddedMax); pointNumber++)
            {
                chart1.Series[0].Points.AddXY(pointIndex + 1, random.Next(1000, 5000));
                ++pointIndex;
            }

            // Adjust Y & X axis scale
            chart1.ResetAutoValues();
            if (chart1.ChartAreas["Default"].AxisX.Maximum < pointIndex)
            {
                chart1.ChartAreas["Default"].AxisX.Maximum = pointIndex;
            }

            // Keep a constant number of points by removing them from the left
            while (chart1.Series[0].Points.Count > numberOfPointsInChart)
            {
                // Remove data points on the left side
                while (chart1.Series[0].Points.Count > numberOfPointsAfterRemoval)
                {
                    chart1.Series[0].Points.RemoveAt(0);
                }

                // Adjust X axis scale
                chart1.ChartAreas["Default"].AxisX.Minimum = pointIndex - numberOfPointsAfterRemoval;
                chart1.ChartAreas["Default"].AxisX.Maximum = chart1.ChartAreas["Default"].AxisX.Minimum + numberOfPointsInChart;
            }

            // Redraw chart
            chart1.Invalidate();
        }
예제 #28
0
        private void FillData()
        {
            // Populate chart with random sales data
            Random   random = new Random();
            DateTime xTime  = new DateTime(2000, 8, 1, 0, 0, 0);

            chart1.Series["Series Input"].Points.Clear();
            for (int pointIndex = 0; pointIndex < int.Parse(comboBoxNumberOfDays.Text); pointIndex++)
            {
                // Simulate lower sales on the weekends
                double yValue = random.Next(600, 950);
                if (xTime.DayOfWeek == DayOfWeek.Sunday || xTime.DayOfWeek == DayOfWeek.Saturday)
                {
                    yValue = random.Next(100, 400);
                }
                chart1.Series["Series Input"].Points.AddXY(xTime, yValue);
                xTime = xTime.AddDays(1);
            }

            chart1.Invalidate();
        }
        /// <summary>
        /// Pre: graph contains a series named "Series1"
        /// Adjusts "Series1" 
        /// </summary>
        /// <param name="chart">The chart that needs updating</param>
        /// <param name="newDataPoint">The new point that needs to be added to the chart</param>
        private void UpdateChartData(Chart chart, double newDataPoint, TimeSpan currentSessionTime)
        {
            // Update chart
            Series series = chart.Series["Series1"];
            int point = series.Points.AddXY(Math.Floor(currentSessionTime.TotalSeconds), newDataPoint);
            int pointsCounter = series.Points.Count;

            chart.ChartAreas[0].AxisX.Minimum = series.Points[0].XValue;
            chart.ChartAreas[0].AxisX.Maximum = series.Points[0].XValue + ((double)(60) * (TIME_WINDOW));
            chart.Invalidate(); //redraw

            // Remove old datapoints
            double removeBefore = Math.Floor(currentSessionTime.TotalSeconds - ((60) * (TIME_WINDOW)));
            while (series.Points[0].XValue < removeBefore)
            {
                series.Points.RemoveAt(0);
            }
        }
예제 #30
0
        private void ConfigurarAreaDeGrafico(Chart grafico, string labelEixoX, string labelEixoY)
        {
            Font fonteA = new Font(Font.FontFamily, 10);
            int nAreas = grafico.ChartAreas.Count;

            grafico.ChartAreas.Clear();

            for (int i = 0; i < nAreas; i++)
            {
                ChartArea areaDeGrafico = new ChartArea();

                areaDeGrafico.AxisX.MajorGrid.Enabled = false;
                areaDeGrafico.AxisX.Title = labelEixoX;
                areaDeGrafico.AxisX.TitleFont = fonteA;
                areaDeGrafico.AxisX.IsStartedFromZero = false;
                areaDeGrafico.AxisY.MajorGrid.Enabled = false;
                areaDeGrafico.AxisY.Title = labelEixoY;
                areaDeGrafico.AxisY.TitleFont = fonteA;
                areaDeGrafico.AxisY.IsStartedFromZero = false;
                areaDeGrafico.BorderDashStyle = ChartDashStyle.Solid;
                //areaDeGrafico.CursorX.Interval = 1E-10;
                //areaDeGrafico.CursorX.IsUserEnabled = true;
                //areaDeGrafico.CursorY.Interval = 1E-10;
                //areaDeGrafico.CursorY.IsUserEnabled = true;
                //areaDeGrafico.CursorX.LineColor = Color.Gainsboro;
                //areaDeGrafico.CursorY.LineColor = Color.Gainsboro;

                grafico.ChartAreas.Add(areaDeGrafico);
            }

            grafico.Invalidate(true);
        }
예제 #31
0
        private bool LoadPieChart(Chart pieChart, List<GeoSoft.Plugins.Interpolation.Classes.TempPIEChartData> pieChartData)
        {

            pieChart.Series.Clear();
            pieChart.Palette = ChartColorPalette.Fire;
            pieChart.ChartAreas[0].BackColor = Color.Transparent;

            Series series1 = new Series
            {
                Name = "series1",
                IsVisibleInLegend = true,
                Color = System.Drawing.Color.Green,
                ChartType = SeriesChartType.Pie
            };

            pieChart.Series.Add(series1);

            foreach (var item in pieChartData)
            {
                var p = series1.Points.Add(item.Count);
                p.Color = item.Color;
            }

            pieChart.Invalidate();

            panelChart.Controls.Add(pieChart);

            Bitmap bmp = new Bitmap(panelChart.Width, panelChart.Height);

            pieChart.DrawToBitmap(bmp, panelChart.ClientRectangle);

            return true;
        }
예제 #32
0
파일: Form1.cs 프로젝트: aemerman/Nevis14
        public void VoltageRangeTest(double ampStart, double ampStop, double ampStep)
        {
            try
            {
                functiongenerator.OutputOff();
            }
            catch (System.ArgumentException)
            {
                MessageBox.Show("This test is not available without a connection to the signal generator.");
                return;
            }

            double[] fourierHisto;
            AdcData data;
            Chart voltagechart = new Chart();
            Series enobdata;

            ResetGui();
            filePath += "Nevis14_" + chipNumBox.Text.PadLeft(5, '0') + "/";
            filePath += CreateNewDirectory("Volt");
            StreamWriter voltagedata = new StreamWriter(filePath + "voltage_data.txt");

            // --Chart Formatting--
            voltagechart.Size = new Size(690, 595);
            voltagechart.ChartAreas.Add(new ChartArea());
            voltagechart.ChartAreas[0].AxisX.Title = "Signal Amplitude [V]";
            voltagechart.ChartAreas[0].AxisX.Minimum = 0;
            voltagechart.ChartAreas[0].AxisX.Maximum = (ampStop - ampStart) / ampStep;
            voltagechart.ChartAreas[0].AxisY.Minimum = 9.5;
            voltagechart.ChartAreas[0].AxisY.Maximum = 10.5;
            voltagechart.ChartAreas[0].AxisY.Title = "ENOB";

            enobdata = new Series{
                Color = Color.Red,
                IsVisibleInLegend = false,
                IsXValueIndexed = true,
                MarkerStyle = MarkerStyle.Square,
                MarkerColor = Color.Red,
                MarkerBorderWidth = 0,
                ChartArea = chart1.ChartAreas[0].Name,
                ChartType = SeriesChartType.Point
            };
            voltagechart.Series.Add(enobdata);
            // End chart formatting
            double[] signalhisto;

            functiongenerator.SetShape("SIN");
            functiongenerator.SetFreq(signalFreq);
            for (double amp = ampStart; amp <= ampStop; amp += ampStep)
            {
                functiongenerator.OutputOn();
                TakeData(false);
                functiongenerator.OutputOff();
                signalhisto = ReadData()[0];
                functiongenerator.SetVolt(amp);
                fourierHisto = DoFFT(signalhisto);
                data = DoQACalculations(fourierHisto, 0);
                enobdata.Points.AddXY(amp, data.enob);
                voltagedata.WriteLine(string.Format("{0}, {1}", amp, data.enob));
            }
            voltagedata.Close();
            voltagechart.Invalidate();
            voltagechart.SaveImage(filePath + "ENOB_vs_amplitude.png", ChartImageFormat.Png);
        }
예제 #33
0
        public static void ParseStreamIntoChart( NetworkStream NetworkStream, Chart NetworkChart, string ActorFilter, string PropertyFilter, string RPCFilter )
        {
            var StartTime = DateTime.UtcNow;

            NetworkChart.BeginInit();

            // Reset existing data.
            foreach( var Series in NetworkChart.Series )
            {
                Series.Points.Clear();
            }
            NetworkChart.ResetAutoValues();
            NetworkChart.Invalidate();

            int FrameCounter = 0;
            foreach( PartialNetworkStream RawFrame in NetworkStream.Frames )
            {
                PartialNetworkStream Frame = RawFrame.Filter(ActorFilter,PropertyFilter,RPCFilter);

                if( Frame.EndTime == Frame.StartTime )
                {
                    throw new InvalidOperationException();
                }
                float OneOverDeltaTime = 1 / (Frame.EndTime - Frame.StartTime);

                NetworkChart.Series["ActorCount"].Points.AddXY( FrameCounter, Frame.ActorCount );
                NetworkChart.Series["ActorCountSec"].Points.AddXY(FrameCounter, Frame.ActorCount * OneOverDeltaTime);
                NetworkChart.Series["PropertyCount"].Points.AddXY( FrameCounter, Frame.PropertyCount );
                NetworkChart.Series["PropertyCountSec"].Points.AddXY( FrameCounter, Frame.PropertyCount * OneOverDeltaTime );
                NetworkChart.Series["PropertySize"].Points.AddXY( FrameCounter, Frame.ReplicatedSizeBits / 8 );
                NetworkChart.Series["PropertySizeSec"].Points.AddXY( FrameCounter, Frame.ReplicatedSizeBits / 8 * OneOverDeltaTime );
                NetworkChart.Series["RPCCount"].Points.AddXY( FrameCounter, Frame.RPCCount );
                NetworkChart.Series["RPCCountSec"].Points.AddXY( FrameCounter, Frame.RPCCount * OneOverDeltaTime );
                NetworkChart.Series["RPCSize"].Points.AddXY( FrameCounter, Frame.RPCSizeBits / 8 );
                NetworkChart.Series["RPCSizeSec"].Points.AddXY( FrameCounter, Frame.RPCSizeBits / 8 * OneOverDeltaTime );
                NetworkChart.Series["SendBunchCount"].Points.AddXY( FrameCounter, Frame.SendBunchCount );
                NetworkChart.Series["SendBunchCountSec"].Points.AddXY( FrameCounter, Frame.SendBunchCount * OneOverDeltaTime );
                NetworkChart.Series["SendBunchSize"].Points.AddXY( FrameCounter, Frame.SendBunchSizeBits / 8 );
                NetworkChart.Series["SendBunchSizeSec"].Points.AddXY( FrameCounter, Frame.SendBunchSizeBits / 8 * OneOverDeltaTime );
                NetworkChart.Series["GameSocketSendSize"].Points.AddXY( FrameCounter, Frame.UnrealSocketSize );
                NetworkChart.Series["GameSocketSendSizeSec"].Points.AddXY( FrameCounter, Frame.UnrealSocketSize * OneOverDeltaTime );
                NetworkChart.Series["GameSocketSendCount"].Points.AddXY( FrameCounter, Frame.UnrealSocketCount );
                NetworkChart.Series["GameSocketSendCountSec"].Points.AddXY( FrameCounter, Frame.UnrealSocketCount * OneOverDeltaTime );
                NetworkChart.Series["MiscSocketSendSize"].Points.AddXY( FrameCounter, Frame.OtherSocketSize );
                NetworkChart.Series["MiscSocketSendSizeSec"].Points.AddXY( FrameCounter, Frame.OtherSocketSize * OneOverDeltaTime );
                NetworkChart.Series["MiscSocketSendCount"].Points.AddXY( FrameCounter, Frame.OtherSocketCount );
                NetworkChart.Series["MiscSocketSendCountSec"].Points.AddXY( FrameCounter, Frame.OtherSocketCount * OneOverDeltaTime );
                int OutgoingBandwidth = Frame.UnrealSocketSize + Frame.OtherSocketSize + NetworkStream.PacketOverhead * (Frame.UnrealSocketCount + Frame.OtherSocketCount);
                NetworkChart.Series["OutgoingBandwidthSize"].Points.AddXY( FrameCounter, OutgoingBandwidth );
                NetworkChart.Series["OutgoingBandwidthSizeSec"].Points.AddXY( FrameCounter, OutgoingBandwidth * OneOverDeltaTime );
                NetworkChart.Series["ActorReplicateTimeInMS"].Points.AddXY(FrameCounter, Frame.ActorReplicateTimeInMS);

                if( Frame.NumEvents > 0 )
                {
                    NetworkChart.Series["Events"].Points.AddXY( FrameCounter, 0 );
                }

                FrameCounter++;
            }

            NetworkChart.DataManipulator.FinancialFormula(FinancialFormula.MovingAverage,"30","GameSocketSendSizeSec","GameSocketSendSizeAvgSec");
            NetworkChart.DataManipulator.FinancialFormula(FinancialFormula.MovingAverage,"30","OutgoingBandwidthSizeSec","OutgoingBandwidthSizeAvgSec");

            NetworkChart.ChartAreas["DefaultChartArea"].RecalculateAxesScale();

            NetworkChart.EndInit();

            Console.WriteLine("Adding data to chart took {0} seconds", (DateTime.UtcNow - StartTime).TotalSeconds);
        }
예제 #34
0
        private void DisplayChartFromSeries(QuantConnect.Chart chart)
        {
            string chartName = chart.Name;

            ControlInvoke(pnlCharts, new Action(() => pnlCharts.Controls.Clear()));

            foreach (var seri in chart.Series.Values)
            {
                System.Windows.Forms.DataVisualization.Charting.Chart
                         ctrlChart = new System.Windows.Forms.DataVisualization.Charting.Chart();
                ctrlChart.Name = chartName;
                ctrlChart.Titles.Add(chartName);

                string seriName = seri.Name;
                ctrlChart.Series.Add(seriName);
                System.Windows.Forms.DataVisualization.Charting.Series ctrlSeri = ctrlChart.Series[seriName];
                ctrlSeri.Color = seri.Color;

                ctrlSeri.IsValueShownAsLabel = true;
                //ctrlSeri.Label = "label "+seriName;
                //ctrlSeri.ToolTip = "tooltip " + seriName;
                ctrlSeri.ToolTip = "Name #SERIESNAME : X - #VALX{F2} , Y - #VALY{F2}";

                //ctrlSeri.Legend= "label " + seriName;
                //ctrlSeri.LegendToolTip = "Name #SERIESNAME : X - #VALX{F2} , Y - #VALY{F2}";

                Legend legend = new Legend("Legend " + seriName);
                ctrlChart.Legends.Add(legend);

                //// Set Docking of the Legend chart to the Default Chart Area.
                //legent. DockToChartArea = "Default";

                //// Assign the legend to Series1.l
                ctrlSeri.Legend            = "Legend " + seriName;
                ctrlSeri.IsVisibleInLegend = true;

                ctrlSeri.LegendText = seriName;
                //ctrlSeri.IsXValueIndexed = true;

                switch (seri.SeriesType)
                {
                case SeriesType.Line:
                    ctrlSeri.ChartType = SeriesChartType.Line;
                    break;

                case SeriesType.Scatter:
                    ctrlSeri.ChartType = SeriesChartType.Line;
                    break;

                case SeriesType.Candle:
                    ctrlSeri.ChartType = SeriesChartType.Candlestick;
                    break;

                case SeriesType.Bar:
                    ctrlSeri.ChartType = SeriesChartType.Bar;
                    break;

                case SeriesType.Flag:
                    ctrlSeri.ChartType = SeriesChartType.Line;
                    break;

                default:
                    break;
                }


                //ctrlSeri.Points.DataBindXY(seri.Values.Select(s => s.x), seri.Values.Select(s => s.y));

                foreach (var point in seri.Values.ToList().OrderByDescending(o => o.x))
                {
                    ctrlSeri.Points.AddXY(Time.UnixTimeStampToDateTime(point.x).ToString("o"), point.y);
                }

                ctrlChart.Height  = chartHeight;
                ctrlChart.Width   = chartWidth;
                ctrlChart.Visible = true;
                ChartArea chartArea = new ChartArea();
                chartArea.Area3DStyle.Enable3D = false;

                ctrlChart.ChartAreas.Add(chartArea);
                ctrlChart.Invalidate();

                ControlInvoke(pnlCharts, new Action(() => pnlCharts.Controls.Add(ctrlChart)));
            }
        }
예제 #35
0
		public static void ParseStreamIntoChart( MainWindow InMainWindow, NetworkStream NetworkStream, Chart NetworkChart, FilterValues InFilterValues )
		{
			var StartTime = DateTime.UtcNow;

			InMainWindow.ShowProgress( true );

			// Save old scroll position
			double OldPosition = NetworkChart.ChartAreas["DefaultChartArea"].AxisX.ScaleView.Position;

			NetworkChart.BeginInit();

			// Reset existing data.
			for ( int i = 0; i < NetworkChart.Series.Count; i++ )
			{
				float Percent = ( float )i / ( float )NetworkChart.Series.Count;
				InMainWindow.UpdateProgress( ( int )( Percent * 100 ) );

				NetworkChart.Series[i].Points.Clear();
			}

			InMainWindow.ShowProgress( true );

			NetworkChart.ResetAutoValues();
			NetworkChart.Invalidate();

			NetworkChart.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = false;
			NetworkChart.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.All;
			NetworkChart.ChartAreas[0].AxisX.ScrollBar.Size = 15;
			NetworkChart.ChartAreas[0].AxisX.ScrollBar.ButtonColor = Color.LightGray;

			NetworkChart.ChartAreas[0].AxisY.ScrollBar.IsPositionedInside = false;
			NetworkChart.ChartAreas[0].AxisY.ScrollBar.ButtonStyle = ScrollBarButtonStyles.All;
			NetworkChart.ChartAreas[0].AxisY.ScrollBar.Size = 15;
			NetworkChart.ChartAreas[0].AxisY.ScrollBar.ButtonColor = Color.LightGray;

			int FrameCounter = 0;

			foreach( PartialNetworkStream RawFrame in NetworkStream.Frames )
			{
				if ( FrameCounter % 1000 == 0 )
				{
					float Percent = ( float )FrameCounter / ( float )NetworkStream.Frames.Count;
					InMainWindow.UpdateProgress( ( int )( Percent * 100 ) );
				}

				PartialNetworkStream Frame = RawFrame.Filter( InFilterValues );

				if( Frame.EndTime == Frame.StartTime )
				{
					throw new InvalidOperationException();
				}

				float OneOverDeltaTime = 1 / (Frame.EndTime - Frame.StartTime);

				int OutgoingBandwidth = Frame.UnrealSocketSize + Frame.OtherSocketSize + NetworkStream.PacketOverhead * ( Frame.UnrealSocketCount + Frame.OtherSocketCount );

				InMainWindow.AddChartPoint( SeriesType.OutgoingBandwidthSize,		FrameCounter, OutgoingBandwidth );
				InMainWindow.AddChartPoint( SeriesType.OutgoingBandwidthSizeSec,	FrameCounter, OutgoingBandwidth * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.ActorCount,					FrameCounter, Frame.ActorCount );
				InMainWindow.AddChartPoint( SeriesType.PropertySize,				FrameCounter, Frame.ReplicatedSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.PropertySizeSec,				FrameCounter, Frame.ReplicatedSizeBits / 8 * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.RPCSize,						FrameCounter, Frame.RPCSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.RPCSizeSec,					FrameCounter, Frame.RPCSizeBits / 8 * OneOverDeltaTime );

#if true
				InMainWindow.AddChartPoint( SeriesType.ActorCountSec,				FrameCounter, Frame.ActorCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.PropertyCount,				FrameCounter, Frame.PropertyCount );
				InMainWindow.AddChartPoint( SeriesType.PropertyCountSec,			FrameCounter, Frame.PropertyCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.RPCCount,					FrameCounter, Frame.RPCCount );
				InMainWindow.AddChartPoint( SeriesType.RPCCountSec,					FrameCounter, Frame.RPCCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.ExportBunchCount,			FrameCounter, Frame.ExportBunchCount );
				InMainWindow.AddChartPoint( SeriesType.ExportBunchSize,				FrameCounter, Frame.ExportBunchSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.MustBeMappedGuidsCount,		FrameCounter, Frame.MustBeMappedGuidCount / 8 );
				InMainWindow.AddChartPoint( SeriesType.MustBeMappedGuidsSize,		FrameCounter, Frame.MustBeMappedGuidSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.SendAckCount,				FrameCounter, Frame.SendAckCount );
				InMainWindow.AddChartPoint( SeriesType.SendAckCountSec,				FrameCounter, Frame.SendAckCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.SendAckSize,					FrameCounter, Frame.SendAckSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.SendAckSizeSec,				FrameCounter, Frame.SendAckSizeBits / 8 * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.ContentBlockHeaderSize,		FrameCounter, Frame.ContentBlockHeaderSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.ContentBlockFooterSize,		FrameCounter, Frame.ContentBlockFooterSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.PropertyHandleSize,			FrameCounter, Frame.PropertyHandleSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.SendBunchCount,				FrameCounter, Frame.SendBunchCount );
				InMainWindow.AddChartPoint( SeriesType.SendBunchCountSec,			FrameCounter, Frame.SendBunchCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.SendBunchSize,				FrameCounter, Frame.SendBunchSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.SendBunchSizeSec,			FrameCounter, Frame.SendBunchSizeBits / 8 * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.SendBunchHeaderSize,			FrameCounter, Frame.SendBunchHeaderSizeBits / 8 );
				InMainWindow.AddChartPoint( SeriesType.GameSocketSendSize,			FrameCounter, Frame.UnrealSocketSize );
				InMainWindow.AddChartPoint( SeriesType.GameSocketSendSizeSec,		FrameCounter, Frame.UnrealSocketSize * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.GameSocketSendCount,			FrameCounter, Frame.UnrealSocketCount );
				InMainWindow.AddChartPoint( SeriesType.GameSocketSendCountSec,		FrameCounter, Frame.UnrealSocketCount * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.ActorReplicateTimeInMS,		FrameCounter, Frame.ActorReplicateTimeInMS);
#endif

#if false
				InMainWindow.AddChartPoint( SeriesType.MiscSocketSendSize,			FrameCounter, Frame.OtherSocketSize );
				InMainWindow.AddChartPoint( SeriesType.MiscSocketSendSizeSec,		FrameCounter, Frame.OtherSocketSize * OneOverDeltaTime );
				InMainWindow.AddChartPoint( SeriesType.MiscSocketSendCount,			FrameCounter, Frame.OtherSocketCount );
				InMainWindow.AddChartPoint( SeriesType.MiscSocketSendCountSec,		FrameCounter, Frame.OtherSocketCount * OneOverDeltaTime );								
#endif

				if ( Frame.NumEvents > 0 )
				{
					InMainWindow.AddChartPoint( SeriesType.Events, FrameCounter, 0 );
				}

				FrameCounter++;
			}

			//NetworkChart.DataManipulator.FinancialFormula( FinancialFormula.MovingAverage, "30", SeriesType.GameSocketSendSizeSec, SeriesType.GameSocketSendSizeAvgSec );
			NetworkChart.DataManipulator.FinancialFormula( FinancialFormula.MovingAverage, "30", SeriesType.OutgoingBandwidthSizeSec.ToString(), SeriesType.OutgoingBandwidthSizeAvgSec.ToString() );

			NetworkChart.ChartAreas["DefaultChartArea"].RecalculateAxesScale();

			NetworkChart.ChartAreas["DefaultChartArea"].AxisX.ScaleView.Position = OldPosition;

			NetworkChart.EndInit();

			InMainWindow.ShowProgress( false );

            Console.WriteLine("Adding data to chart took {0} seconds", (DateTime.UtcNow - StartTime).TotalSeconds);
		}
예제 #36
0
        /// <summary>
        /// charge le graphique, définit les parts du cammembert et le nom des catégories
        /// </summary>
        /// <param name="motif">Crédit ou Débit</param>
        /// <param name="zone">Panel dans lequel le graphique sera affiché</param>
        /// <param name="cammembert">Chart</param>
        void ChargeGraphique(string motif, Panel zone, Chart cammembert)
        {
            //supprime toutes les parts du cammembert
            cammembert.Series.Clear();

            switch (PaletteStyle)
            {
                case "Bright":
                    cammembert.Palette = ChartColorPalette.Bright;
                    break;
                case "Grayscale":
                    cammembert.Palette = ChartColorPalette.Grayscale;
                    break;
                case "Excel":
                    cammembert.Palette = ChartColorPalette.Excel;
                    break;
                case "Light":
                    cammembert.Palette = ChartColorPalette.Light;
                    break;
                case "Pastel":
                    cammembert.Palette = ChartColorPalette.Pastel;
                    break;
                case "EarthTones":
                    cammembert.Palette = ChartColorPalette.EarthTones;
                    break;
                case "SemiTransparent":
                    cammembert.Palette = ChartColorPalette.SemiTransparent;
                    break;
                case "Berry":
                    cammembert.Palette = ChartColorPalette.Berry;
                    break;
                case "Chocolate":
                    cammembert.Palette = ChartColorPalette.Chocolate;
                    break;
                case "Fire":
                    cammembert.Palette = ChartColorPalette.Fire;
                    break;
                case "SeaGreen":
                    cammembert.Palette = ChartColorPalette.SeaGreen;
                    break;
                case "BrightPastel":
                    cammembert.Palette = ChartColorPalette.BrightPastel;
                    break;
                default:
                    cammembert.Palette = ChartColorPalette.Excel;
                    break;
            }

            cammembert.BackColor = BackColor;
            //titre du graphique
            cammembert.Titles.Add("Etat des " + motif);
            cammembert.ChartAreas[0].BackColor = Color.Transparent;
            //crée la serie
            Series series1 = new Series
            {
                Name = motif,
                IsVisibleInLegend = true,
                Color = System.Drawing.Color.Blue,
                ChartType = SeriesChartType.Pie
            };

            cammembert.Series.Add(series1);
            string[,] maserie = RecupereInfo(motif);

            for (int i = 0; i < maserie.Length / 2; i++)
            {
                series1.Points.Add(System.Convert.ToDouble(maserie[i, 1]));

                var point = series1.Points[i];
                if (System.Convert.ToDouble(maserie[i, 1]) > 0)
                {
                    point.AxisLabel = maserie[i, 1];
                }
                point.LegendText = maserie[i, 0];

            }

            cammembert.Invalidate();
            zone.Controls.Add(cammembert);
        }
예제 #37
0
        /// <summary>
        /// This method calculates a different indicator if corresponding
        /// item in the combo box is selected.
        /// </summary>
        private void Calculations()
        {
            // Set defaults
            chart1.ChartAreas["Indicator"].AxisY.StripLines.Clear();
            chart1.ChartAreas["Indicator"].AxisY.Minimum = double.NaN;
            chart1.ChartAreas["Indicator"].AxisY.Maximum = double.NaN;
            try
            {
                chart1.Series["SMA"].ChartArea = "";
            }
            catch {}

            // Set Formula Name
            string           formulaName = comboBoxFormulaName.Text;
            FinancialFormula formula     = (FinancialFormula)Enum.Parse(typeof(FinancialFormula), formulaName, true);

            // Formulas with one input value
            if (formulaName == "DetrendedPriceOscillator" || formulaName == "MovingAverageConvergenceDivergence" || formulaName == "Performance" || formulaName == "RateOfChange" ||
                formulaName == "TripleExponentialMovingAverage")
            {
                chart1.DataManipulator.FinancialFormula(formula, "10", "Input:Y4", "Indicators");
            }

            // Relative Strength Index
            else if (formulaName == "RelativeStrengthIndex")
            {
                chart1.DataManipulator.FinancialFormula(formula, "10", "Input:Y4", "Indicators");

                // Set minimum and maximum for Y axis
                chart1.ChartAreas["Indicator"].AxisY.Minimum = 0;
                chart1.ChartAreas["Indicator"].AxisY.Maximum = 100;

                // Create strip lines used with Relative strength index.
                StripLine stripLine = new StripLine();
                chart1.ChartAreas["Indicator"].AxisY.StripLines.Add(stripLine);
                stripLine.Interval   = 70;
                stripLine.StripWidth = 30;
                stripLine.BackColor  = Color.FromArgb(64, 165, 191, 228);
            }
            // Williams %R
            else if (formulaName == "WilliamsR")
            {
                chart1.DataManipulator.FinancialFormula(formula, "Input:Y,Input:Y2,Input:Y4", "Indicators");

                // Set minimum and maximum for Y axis
                chart1.ChartAreas["Indicator"].AxisY.Minimum = -100;
                chart1.ChartAreas["Indicator"].AxisY.Maximum = 0;

                // Create strip lines used with Williams %R index.
                StripLine stripLine = new StripLine();
                chart1.ChartAreas["Indicator"].AxisY.StripLines.Add(stripLine);
                stripLine.Interval   = 80;
                stripLine.StripWidth = 20;
                stripLine.BackColor  = Color.FromArgb(64, 165, 191, 228);
            }
            // Formulas with two input value
            else if (formulaName == "MassIndex" || formulaName == "VolatilityChaikins" || formulaName == "Performance")
            {
                chart1.DataManipulator.FinancialFormula(formula, "20", "Input:Y,Input:Y2", "Indicators");
            }
            // Standard deviation
            else if (formulaName == "StandardDeviation")
            {
                chart1.DataManipulator.FinancialFormula(formula, "15", "Input:Y4", "Indicators");
            }
            // StochasticIndicator
            else if (formulaName == "StochasticIndicator")
            {
                chart1.DataManipulator.FinancialFormula(formula, "15", "Input:Y,Input:Y2,Input:Y4", "Indicators,SMA");

                // Set attributes for Simple moving average series.
                chart1.Series["SMA"].ChartType   = SeriesChartType.Line;
                chart1.Series["SMA"].Color       = Color.FromArgb(252, 180, 65);
                chart1.Series["SMA"].ChartArea   = "Indicator";
                chart1.Series["SMA"].BorderWidth = 2;
            }
            // All other formulas.
            else
            {
                chart1.DataManipulator.FinancialFormula(formula, "Input:Y,Input:Y2,Input:Y4", "Indicators");
            }

            // Set minimum for X axis
            chart1.ChartAreas["Indicator"].AxisX.Minimum = DateTime.Parse("1/1/2002").ToOADate();

            chart1.Invalidate();
        }
예제 #38
0
        /// <summary>
        /// Add graphics point overload method - Series Name instead of Series Num
        /// </summary>
        /// <param name="CurChart"></param>
        /// <param name="serName">Series name</param>
        /// <param name="XVal"></param>
        /// <param name="YVal"></param>
        private void addGraphicsPoint(Chart CurChart, string serName, DateTime XVal, double YVal)
        {
            //curX=DateTime.Now;
            CurChart.Series[serName].Points.AddXY(XVal, YVal);

            // Keep a constant number of points by removing them from the left
            if (CurChart.Series[serName].Points.Count > maxNumberOfPointsInChart)
            {
                // Remove data points on the left side
                while (CurChart.Series[serName].Points.Count > maxNumberOfPointsInChart)
                {
                    CurChart.Series[serName].Points.RemoveAt(0);
                }

                // Adjust X axis scale
                //CurChart.ChartAreas[0].AxisX.Minimum = curX - maxNumberOfPointsInChart;
                //CurChart.ChartAreas[0].AxisX.Maximum = CurChart.ChartAreas[0].AxisX.Minimum + maxNumberOfPointsInChart;
            }

            // Adjust Y & X axis scale
            CurChart.ResetAutoValues();

            // Invalidate chart
            CurChart.Invalidate();
        }
예제 #39
0
 public void SaveGraph(string fileName)
 {
     _chart.Invalidate();
     _chart.SaveImage($"{fileName.Replace(':', '-')}.png", ChartImageFormat.Png);
 }
예제 #40
0
 private void UpdateChart(Chart c, Series s, History hs)
 {
     s.Points.Clear();
     foreach (var h in hs)
     {
         s.Points.AddXY(h.Item1.Ticks, h.Item2);
     }
     c.Invalidate();
 }
예제 #41
0
        private void DesignChart(Chart chart1)
        {
            //
            // chart1
            //
            chart1.BackColor = System.Drawing.Color.WhiteSmoke;
            chart1.BackSecondaryColor = System.Drawing.Color.White;
            chart1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.DiagonalLeft;
            chart1.BorderlineColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart1.BorderSkin.BackColor = System.Drawing.Color.CornflowerBlue;
            chart1.BorderSkin.BackSecondaryColor = System.Drawing.Color.CornflowerBlue;
            chart1.BorderSkin.PageColor = System.Drawing.SystemColors.Control;
            chart1.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;
            chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisX.MinorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisX2.MajorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisX2.MinorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisY.MinorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisY2.MajorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].AxisY2.MinorGrid.LineColor = System.Drawing.Color.Silver;
            chart1.ChartAreas[0].BackColor = System.Drawing.Color.White;
            chart1.ChartAreas[0].BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            chart1.ChartAreas[0].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart1.ChartAreas[0].ShadowOffset = 2;

            chart1.Invalidate();
        }
예제 #42
0
 private void TableColor_SelectedIndexChanged(object sender, System.EventArgs e)
 {
     TableHelper.TableColor = Color.FromName(this.TableColor.SelectedItem.ToString());
     chart1.Invalidate();
 }
예제 #43
0
        public void Test(string testSetFile, string outputFile, Chart resultsChart)
        {
            List<double[]> originalTestValues = LoadTestData(testSetFile);

            string resultString = string.Empty;
            //klasyfikacja
            if (problemType == ProblemType.Classification)
            {
                resultsChart.Visible = true;
                List<Color> colors = new List<Color>() { Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Violet, Color.Orange, Color.Beige, Color.Brown };
                for (int i = 0; i < outputSize; i++)
                {
                    var serie = new System.Windows.Forms.DataVisualization.Charting.Series
                    {
                        Name = ("klasa " + (i + 1)),
                        Color = colors[i],
                        ChartType = SeriesChartType.FastPoint
                    };

                    resultsChart.Series.Add(serie);
                }

                for (int j = 0; j < testData.Count; j++)
                {
                    var d = network.Compute(testData[j]);
                    int cls = 1;
                    for (int i = 1; i < outputSize; i++)
                    {
                        if (d[i] > d[i - 1])
                            cls++;
                    }
                    resultsChart.Series["klasa " + cls].Points.AddXY(originalTestValues[j][0], originalTestValues[j][1]);
                    resultsChart.Invalidate();
                    foreach (double val in originalTestValues[j])
                        resultString += (val + ",");
                    resultString += (cls + Environment.NewLine);
                }
            }
            else //regresja
            {
                resultsChart.Visible = true;

                var serie = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name = ("regresja"),
                    Color = Color.Blue,
                    ChartType = SeriesChartType.FastPoint
                };

                resultsChart.Series.Add(serie);

                double minVal = (activationFunType == ActivationFunctionType.Bipolar) ? -1.0 : 0.0;
                double maxVal = 1.0;
                double normSize = (maxVal - minVal) * normParam;

                for (int j = 0; j < testData.Count; j++)
                {
                    var res = network.Compute(testData[j])[0];
                    //denormalizacja
                    double dSize = idealMax[0] - idealMin[0];
                    res = idealMin[0] + ((res - minVal) * dSize / normSize);
                    resultsChart.Series["regresja"].Points.AddXY(originalTestValues[j][0], res);
                    resultsChart.Invalidate();
                    foreach (double val in originalTestValues[j])
                        resultString += (val + ",");
                    resultString += (res + Environment.NewLine);
                }
            }

            using (StreamWriter outfile = new StreamWriter(outputFile))
            {
                outfile.Write(resultString);
            }
        }
예제 #44
0
        private void tsmzoom_Click(object sender, EventArgs e)
        {
            //this.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
            //this.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            Control c = this.Parent;
            chartcopy = this;

            ZoomedChart frm = new ZoomedChart(this);

            frm.WindowState = FormWindowState.Maximized;
            frm.ShowDialog();

            c.Controls.Add(chartcopy);
            chartcopy.Invalidate();
            chartcopy.Show();
        }
예제 #45
0
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt = readCSV("C:\\Users\\Vic\\Dropbox\\Data\\3day\\10in_1.csv");
            //dt = readCSV("C:\\Users\\Vic\\Desktop\\ewj.csv");

            //Console.WriteLine( dt.Columns.Count  );
            //Console.WriteLine(dt.Rows.Count);

            Stopwatch timer = new Stopwatch();  //碼表
            int Training_count = 20000;         //訓練資料的使用長度
            int MatchCount = 70;               //KNN裡的K值的大小
            //KDTree<double> _tree = new KDTree<double>(11);
            KDTree<double> _tree2 = new KDTree<double>(11);

            List<double> trade_list = new List<double>();
            List<double> EC1 = new List<double>();

            StreamWriter file = new System.IO.StreamWriter("C:\\001.csv");  //輸出觀察用的Log檔案
            double Long_Threshold = 0.1;
            double Short_Threshold = -0.2;
            int L_vote = 0;
            int S_vote = 0;
            double nodes_avg=0;
            double totalprofit;
            double mdd;

            timer.Reset();
            timer.Start();

            List<HistoricalStock>  data = HistoricalStockDownloader.DownloadData("SPY", 1962);
            Console.WriteLine("Get SPY from Yahoo : {0}ticks ,{1}msec", timer.ElapsedTicks, timer.ElapsedMilliseconds);
            timer.Reset();
            timer.Start();

            //把上面的資料想辦法用來計算 coodrs

            PatternFinder PF = new PatternFinder(data);

            for (int i = 10; i < 1000; i++)
            {
                PF.CalcHistorical();   //<<<<<<<-------------------------- 卡關 _tree.Add 傳入參數跟型態都沒問題,但是就是沒法加入節點
                PF.CurrentBar++;

                Console.WriteLine("CurrentBar={0} ,DateT={1},E={2} ",PF.CurrentBar,PF.Date_Time[i],PF.Expectancy  );

                //Console.Write(PF.Date_Time[i].ToShortDateString()  +","  );
                //Console.WriteLine("data.Count:" + data.Count() );
            }

            Console.WriteLine("Tree Nodes Count:"+PF._tree.Count    );
            Console.WriteLine("共使用記憶體: {0}MB", Environment.WorkingSet / 1000000);

            Console.ReadLine();
            return;  // 使用返回  中斷程式,直到上面的做好

            // 舊的流程
            for (int CurrentBar = 1; CurrentBar < dt.Rows.Count; CurrentBar++)
            {

                DataRow row = dt.Rows[CurrentBar];
                Double[] coords = new double[11];

                    //Get 11 dimentions into Array
                    for (int i2 = 4; i2 < row.ItemArray.Count() ; i2++)
                    {   coords[i2-4] = Convert.ToDouble(row.ItemArray[4])  ;   }

                    if (CurrentBar <= Training_count)
                    {   //將陣列做為index值,報酬率作為value存入KD二元樹
                        //_tree.Add(coords, Convert.ToDouble(row.ItemArray[3]));
                        //_tree2.Add(coords, Convert.ToDouble(row.ItemArray[3]));

                    }
                    else   //CurrentBar大於Training_count以後,開始Testing運算,模擬交易開始
                    {
                        L_vote = 0;
                        S_vote = 0;
                        Long_Threshold = 0.3;
                        Short_Threshold = -0.3;

                        //string s = SiteHelper.Serialize(_tree2);

                        for (int i3 = 1; i3 <= 7; i3++ )
                        {
                            //nodes_avg = _tree.Nearest(coords, MatchCount*i3  ).Average(x => x.Node.Value);
                            if (nodes_avg >= Long_Threshold) { L_vote += 1; }
                            if (nodes_avg <= Short_Threshold) { S_vote += 1; }
                        }

                        //型態比對找出群組的平均值以後 如果大於 Long_Threshold 的投票數就模擬買進
                        if (L_vote>=6 )
                        {

                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) /100 * 1000000);
                            EC1.Add(trade_list.Sum());

                            string s_out = string.Format("{0},{1},{2},{3},{4}", Convert.ToDouble(row.ItemArray[1]), row.ItemArray[2], trade_list.Last(), EC1.Last(), Math.Round( nodes_avg,2) );

                            /*
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last() );
                            Console.WriteLine(" "+ EC1.Last() );
                            */
                            Console.WriteLine(s_out);

                            /*
                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(trade_list.Last()+"," );
                            file.WriteLine(EC1.Last()  );
                            */

                            file.WriteLine(s_out);

                        }

                        /*  Take Short trades
                        if (S_vote >= 6)
                        {
                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) / 100 * -1000000  );
                            EC1.Add(trade_list.Sum());
                            //trade_list.Add(Convert.ToDouble(row.ItemArray[1]) );
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last());
                            Console.WriteLine(" " + EC1.Last());

                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(" " + trade_list.Last());
                            file.WriteLine(" " + EC1.Last());

                        }
                        */

                        /*
                        //Console.Write(CurrentBar );
                        Console.Write(row.ItemArray[1]);
                        Console.Write(" Forecast is:" + _tree.Nearest(coords, MatchCount).Average(x => x.Node.Value));
                        Console.WriteLine(" True Return is:" + Convert.ToDouble(row.ItemArray[3]) + "  ");
                        */

                        //Console.WriteLine(row.ItemArray.Count());
                    }
            }

            file.Close();

            totalprofit = trade_list.Sum();
            mdd = MaxDrawdown(EC1.ToArray());

            Console.WriteLine();
            Console.WriteLine("trade_list Profit: " + totalprofit );
            Console.WriteLine("MDD: " + mdd);
            Console.WriteLine("Profit/MDD: " +  Math.Round( totalprofit/mdd ,2)  );
            Console.WriteLine("Trades: " + trade_list.Count );
            Console.WriteLine("EC1 Count: " + EC1.Count);
            Console.WriteLine( "Total Rows: "+ dt.Rows.Count );
            //Console.WriteLine( "Tree Count(Training Count): " + _tree.Count() );

            /*
            //KDTree<double> _tree2 =
            KDTreeNodeCollection<double>  kd_nodes;
            Dictionary<KDTreeNodeCollection<double>  , int>   Dict= new Dictionary<KDTreeNodeCollection<double>,int>()  ;

            foreach (var nodes in _tree2 ){

            kd_nodes=  _tree.Nearest(nodes.Position , MatchCount) ;

            //Console.WriteLine(nodes.Position +"  "  );
            //Console.WriteLine(nodes.GetType() );

                if (Dict.ContainsKey( kd_nodes )  )
                {

                }
                else
                {
                    Dict.Add(kd_nodes, 1);

                }

            }

            Console.WriteLine("Dict count:" + Dict.Count );
             */

            // EC1 畫圖輸出來觀察 create the chart
            var chart = new Chart();
            chart.Size = new Size(600, 600);

            var chartArea = new ChartArea();
            //chartArea.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
            chartArea.AxisX.Interval = 1;
            chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisX.LabelStyle.Font = new Font("Consolas", 8);
            chartArea.AxisY.LabelStyle.Font = new Font("Consolas", 8);
            chart.ChartAreas.Add(chartArea);

            var series = new Series();
            series.Name = "Series1";
            series.ChartType = SeriesChartType.FastLine;
            series.XValueType = ChartValueType.DateTime;
            chart.Series.Add(series);

            /*
            foreach (int i4 in EC1) {
            series.Points.AddY(i4  );
            } */

            foreach (HistoricalStock stock in data)
            {
                //Console.WriteLine(string.Format("Date={0} High={1} Low={2} Open={3} Close={4}", stock.Date.ToShortDateString() , stock.High, stock.Low, stock.Open, stock.Close)  );
                //Console.WriteLine(stock.Date.ToShortDateString()+",");

                series.Points.AddXY( stock.Date ,stock.Close );
            }

            // draw!
            chart.Invalidate();

            // write out a file
            chart.SaveImage("c:\\chart.png", ChartImageFormat.Png);

            Process.Start(@"c:\\chart.png");

            Console.ReadLine();
        }
예제 #46
0
        private void DisplayChart()
        {
            if (_algoEnv == null || _algoEnv.ResultsHandler == null)
            {
                return;
            }


            foreach (Chart chart in _algoEnv.ResultsHandler.Charts.Values)
            {
                System.Windows.Forms.DataVisualization.Charting.Chart ctrlChart = new System.Windows.Forms.DataVisualization.Charting.Chart();

                ctrlChart.Name = chart.Name;

                foreach (var seri in chart.Series.Values)
                {
                    string seriName = seri.Name;
                    ctrlChart.Series.Add(seriName);
                    System.Windows.Forms.DataVisualization.Charting.Series ctrlSeri = ctrlChart.Series[seriName];
                    ctrlSeri.Color = seri.Color;

                    //ctrlSeri.IsVisibleInLegend = false;
                    //ctrlSeri.IsXValueIndexed = true;

                    switch (seri.SeriesType)
                    {
                    case SeriesType.Line:
                        ctrlSeri.ChartType = SeriesChartType.Line;
                        break;

                    case SeriesType.Scatter:
                        ctrlSeri.ChartType = SeriesChartType.Line;
                        break;

                    case SeriesType.Candle:
                        ctrlSeri.ChartType = SeriesChartType.Candlestick;
                        break;

                    case SeriesType.Bar:
                        ctrlSeri.ChartType = SeriesChartType.Bar;
                        break;

                    case SeriesType.Flag:
                        ctrlSeri.ChartType = SeriesChartType.Line;
                        break;

                    default:
                        break;
                    }



                    foreach (var point in seri.Values)
                    {
                        ctrlSeri.Points.AddXY(point.x, point.y);
                    }
                }

                ctrlChart.Height  = 400;
                ctrlChart.Width   = 600;
                ctrlChart.Visible = true;
                ctrlChart.ChartAreas.Add(new ChartArea());
                ctrlChart.ChartAreas[0].Area3DStyle.Enable3D = false;
                ctrlChart.Invalidate();

                pnlCharts.Controls.Add(ctrlChart);
            }
        }