ASE Home Page Products Download Purchase Support About ASE
ChartDirector Support
Forum HomeForum Home   SearchSearch

Message ListMessage List     Post MessagePost Message

  zoom function according to no of candle
Posted by Nidhi on Oct-28-2015 23:41
Hi,

Zoom functionality work according to viewportleft, but if I want to work no of candle then
how to manage it.

I wrote formula for calculating viewportleft according to no of candle but its not bringing
that no of candle in viewing window.

  double per = (Convert.ToDouble(txtmaxDsplay.Text) * 100) / timeStamps.Length;
           // viewer.ViewPortWidth = 0.2;
            viewer.ViewPortWidth = per / 100;
            viewer.ViewPortLeft = 1 - viewer.ViewPortWidth;

  Re: zoom function according to no of candle
Posted by Peter Kwan on Oct-30-2015 01:51
Hi Nidhi,

It seems the formula you are using is correct.

In your charting code, it should get the number of candles based on the ViewPortLeft and
ViewPortWidth. For example, if the requested number of candlesticks is 150, your code
should get (150 + extraPoints) number of data points. If this is not the case, you would
need to investigate why the charting code is not getting the required number of
candlesticks. For example, is it possible the "full range" is set not according to the number
of candlesticks?

Regards
Peter Kwan

  Re: zoom function according to no of candle
Posted by Nidhi on Oct-30-2015 18:00
Attachments:
Please find file attached here for my working:


Here candles are not coming according to given no of candle in text box.
frmfinancedemo.cs
using System;
using System.Collections;
using System.Windows.Forms;
using ChartDirector;

namespace CSharpChartExplorer
{
    public partial class FrmFinanceDemo : Form
    {
        public FrmFinanceDemo()
        {
            InitializeComponent();
        }

        /// <summary>
        /// A utility class for adding items to ComboBox
        /// </summary>
        private class ListItem
        {
            string m_key;
            string m_value;

            public ListItem(string key, string val)
            {
                m_key = key;
                m_value = val;
            }

            public string Key
            {
                get { return m_key; }
            }

            public override string ToString()
            {
                return m_value;
            }
        }

        // The ticker symbol, timeStamps, volume, high, low, open and close data    
        string tickerKey = "";
        private DateTime[] timeStamps;
        private double[] volData;
        private double[] highData;
        private double[] lowData;
        private double[] openData;
        private double[] closeData;
        bool ISline;
        ArrayList xdata = new ArrayList();
        ArrayList ydata = new ArrayList();
        ArrayList xdatapoint = new ArrayList();
        ArrayList ydatapoint = new ArrayList();
        private DateTime startDate;
        private int extraPoints = 0;
        // An extra data series to compare with the close data
        private string compareKey = "";
        private double[] compareData = null;

        // The resolution of the data in seconds. 1 day = 86400 seconds.
        private int resolution = 86400;

        // Will set to true at the end of initialization - prevents events from firing before the
        // controls are properly initialized.
        private bool hasFinishedInitialization = false;
        private void initChartViewer(WinChartViewer viewer)
        {
            
            
            // Set the full x range to be the duration of the data
            viewer.setFullRange("x", timeStamps[0], timeStamps[timeStamps.Length - 1]);

           

            // Initialize the view port to show the latest 20% of the time range
            double per = ((Convert.ToDouble(txtmaxDsplay.Text)+2) * 100) / timeStamps.Length;
           // viewer.ViewPortWidth = 0.2;
            viewer.ViewPortWidth = per / 100;
            viewer.ViewPortLeft = 1 - viewer.ViewPortWidth;
            
            // Set the maximum zoom to 10 points
            viewer.ZoomInWidthLimit = 10.0 / timeStamps.Length;

            // Enable mouse wheel zooming by setting the zoom ratio to 1.1 per wheel event
            viewer.MouseWheelZoomRatio = 1.1;

            // Initially set the mouse usage to "Pointer" mode (Drag to Scroll mode)
            pointerPB.Checked = true;
        }
        private void loadData()
        {
            // In this demo, we just assume we plot up to the latest time. So endDate is now.
            DateTime endDate = DateTime.Now;

            // If the trading day has not yet started (before 9:30am), or if the end date is
            // on on Sat or Sun, we set the end date to 4:00pm of the last trading day
            while ((endDate.TimeOfDay.CompareTo(new TimeSpan(9, 30, 0)) < 0) || (
                endDate.DayOfWeek == DayOfWeek.Sunday) || (endDate.DayOfWeek ==
                DayOfWeek.Saturday))
            {
                endDate = endDate.Date.AddDays(-1).Add(new TimeSpan(16, 0, 0));
            }

            // The duration selected by the user
            int durationInDays = int.Parse(((ListItem)timeRange.SelectedItem).Key);

            // Compute the start date by subtracting the duration from the end date.
           
            if (durationInDays >= 30)
            {
                // More or equal to 30 days - so we use months as the unit
                startDate = new DateTime(endDate.Year, endDate.Month, 1).AddMonths(
                    -durationInDays / 30);
            }
            else
            {
                // Less than 30 days - use day as the unit. Note that we use trading days 
                // below. For less than 30 days, the starting point of the axis is always at
                // the start of the day.
                startDate = endDate.Date;
                for (int i = 1; i < durationInDays; ++i)
                    startDate = startDate.AddDays(
                        (startDate.DayOfWeek == DayOfWeek.Monday) ? -3 : -1);
            }
            compareKey = compareWith.Text.Trim();
            compareData = null;
            if (getData(compareKey, startDate, endDate, durationInDays, extraPoints))
                compareData = closeData;

            // The data series we want to get.
            tickerKey = tickerSymbol.Text.Trim();
            if (!getData(tickerKey, startDate, endDate, durationInDays, extraPoints))
            {
                errMsg(winChartViewer1, "Please enter a valid ticker symbol");
                return;
            }
        }
        /// <summary>
        /// Form Load event handler - initialize the form
        /// </summary>
        private void FrmFinanceDemo_Load(object sender, System.EventArgs e)
        {
            hasFinishedInitialization = false;

            timeRange.Items.Add(new ListItem("1", "1 day"));
            timeRange.Items.Add(new ListItem("2", "2 days"));
            timeRange.Items.Add(new ListItem("5", "5 days"));
            timeRange.Items.Add(new ListItem("10", "10 days"));
            timeRange.Items.Add(new ListItem("30", "1 month"));
            timeRange.Items.Add(new ListItem("60", "2 months"));
            timeRange.Items.Add(new ListItem("90", "3 months"));
            timeRange.SelectedIndex = timeRange.Items.Add(new ListItem("180", "6 months"));
            timeRange.Items.Add(new ListItem("360", "1 year"));
            timeRange.Items.Add(new ListItem("720", "2 years"));
            timeRange.Items.Add(new ListItem("1080", "3 years"));
            timeRange.Items.Add(new ListItem("1440", "4 years"));
            timeRange.Items.Add(new ListItem("1800", "5 years"));
            timeRange.Items.Add(new ListItem("3600", "10 years"));

            chartSize.Items.Add(new ListItem("S", "Small"));
            chartSize.Items.Add(new ListItem("M", "Medium"));
            chartSize.SelectedIndex = chartSize.Items.Add(new ListItem("L", "Large"));
            chartSize.Items.Add(new ListItem("H", "Huge"));

            chartType.Items.Add(new ListItem("None", "None"));
            chartType.SelectedIndex = chartType.Items.Add(new ListItem("CandleStick", "CandleStick"));
            chartType.Items.Add(new ListItem("Close", "Closing Price"));
            chartType.Items.Add(new ListItem("Median", "Median Price"));
            chartType.Items.Add(new ListItem("OHLC", "OHLC"));
            chartType.Items.Add(new ListItem("TP", "Typical Price"));
            chartType.Items.Add(new ListItem("WC", "Weighted Close"));

            priceBand.SelectedIndex = priceBand.Items.Add(new ListItem("None", "None"));
           priceBand.Items.Add(new ListItem("BB", "Bollinger Band"));
            priceBand.Items.Add(new ListItem("DC", "Donchain Channel"));
            priceBand.Items.Add(new ListItem("Envelop", "Envelop (SMA 20 +/- 10%)"));

            avgType1.Items.Add(new ListItem("None", "None"));
            avgType1.SelectedIndex = avgType1.Items.Add(new ListItem("SMA", "Simple"));
            avgType1.Items.Add(new ListItem("EMA", "Exponential"));
            avgType1.Items.Add(new ListItem("TMA", "Triangular"));
            avgType1.Items.Add(new ListItem("WMA", "Weighted"));

            avgType2.Items.Add(new ListItem("None", "None"));
            avgType2.SelectedIndex = avgType2.Items.Add(new ListItem("SMA", "Simple"));
            avgType2.Items.Add(new ListItem("EMA", "Exponential"));
            avgType2.Items.Add(new ListItem("TMA", "Triangular"));
            avgType2.Items.Add(new ListItem("WMA", "Weighted"));

            ListItem[] indicators = 
			{
				new ListItem("None", "None"),
				new ListItem("AccDist", "Accumulation/Distribution"),
				new ListItem("AroonOsc", "Aroon Oscillator"),
				new ListItem("Aroon", "Aroon Up/Down"),
				new ListItem("ADX", "Avg Directional Index"),
				new ListItem("ATR", "Avg True Range"),
				new ListItem("BBW", "Bollinger Band Width"),
				new ListItem("CMF", "Chaikin Money Flow"),
				new ListItem("COscillator", "Chaikin Oscillator"),
				new ListItem("CVolatility", "Chaikin Volatility"),
				new ListItem("CLV", "Close Location Value"),
				new ListItem("CCI", "Commodity Channel Index"),
				new ListItem("DPO", "Detrended Price Osc"),
				new ListItem("DCW", "Donchian Channel Width"),
				new ListItem("EMV", "Ease of Movement"),
				new ListItem("FStoch", "Fast Stochastic"),
				new ListItem("MACD", "MACD"),
				new ListItem("MDX", "Mass Index"),
				new ListItem("Momentum", "Momentum"),
				new ListItem("MFI", "Money Flow Index"),
				new ListItem("NVI", "Neg Volume Index"),
				new ListItem("OBV", "On Balance Volume"),
				new ListItem("Performance", "Performance"),
				new ListItem("PPO", "% Price Oscillator"),
				new ListItem("PVO", "% Volume Oscillator"),
				new ListItem("PVI", "Pos Volume Index"),
				new ListItem("PVT", "Price Volume Trend"),
				new ListItem("ROC", "Rate of Change"),
				new ListItem("RSI", "RSI"),
				new ListItem("SStoch", "Slow Stochastic"),
				new ListItem("StochRSI", "StochRSI"),
				new ListItem("TRIX", "TRIX"),
				new ListItem("UO", "Ultimate Oscillator"),
				new ListItem("Vol", "Volume"),
				new ListItem("WilliamR", "William's %R")
			};

            indicator1.Items.AddRange(indicators);
            indicator2.Items.AddRange(indicators);
            indicator3.Items.AddRange(indicators);
            indicator4.Items.AddRange(indicators);

            //for (int i = 0; i < indicators.Length; ++i)
            //{
            //    if (indicators[i].Key == "RSI")
            //        indicator1.SelectedIndex = i;
            //    else if (indicators[i].Key == "MACD")
            //        indicator2.SelectedIndex = i;
            //}
            indicator1.SelectedIndex = 0;
            indicator2.SelectedIndex = 0;
            indicator3.SelectedIndex = 0;
            indicator4.SelectedIndex = 0;

            // Load the data
            loadData();

            // Initialize the WinChartViewer
            initChartViewer(winChartViewer1);

            // Can handle events now
            hasFinishedInitialization = true;

            // Trigger the ViewPortChanged event to draw the chart
            winChartViewer1.updateViewPort(true, true);
        }

        /// <summary>
        /// Get the timeStamps, highData, lowData, openData, closeData and volData.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        /// <param name="durationInDays">The number of trading days to get.</param>
        /// <param name="extraPoints">The extra leading data points needed in order to 
        /// compute moving averages.</param>
        /// <returns>True if successfully obtain the data, otherwise false.</returns>
        protected bool getData(string ticker, DateTime startDate, DateTime endDate,
            int durationInDays, int extraPoints)
        {
            // This method should return false if the ticker symbol is invalid. In this
            // sample code, as we are using a random number generator for the data, all
            // ticker symbol is allowed, but we still assumed an empty symbol is invalid.
            if (ticker == "")
                return false;

            // In this demo, we can get 15 min, daily, weekly or monthly data depending on
            // the time range.
            resolution = 86400;
            if (durationInDays <= 10)
            {
                // 10 days or less, we assume 15 minute data points are available
                resolution = 900;

                // We need to adjust the startDate backwards for the extraPoints. We assume
                // 6.5 hours trading time per day, and 5 trading days per week.
                double dataPointsPerDay = 6.5 * 3600 / resolution;
                DateTime adjustedStartDate = startDate.AddDays(-Math.Ceiling(extraPoints /
                    dataPointsPerDay * 7 / 5) - 2);

                // Get the required 15 min data
                get15MinData(ticker, adjustedStartDate, endDate);

            }
            else if (durationInDays >= 4.5 * 360)
            {
                // 4 years or more - use monthly data points.
                resolution = 30 * 86400;

                // Adjust startDate backwards to cater for extraPoints
                DateTime adjustedStartDate = startDate.Date.AddMonths(-extraPoints);

                // Get the required monthly data
                getMonthlyData(ticker, adjustedStartDate, endDate);

            }
            else if (durationInDays >= 1.5 * 360)
            {
                // 1 year or more - use weekly points.
                resolution = 7 * 86400;

                // Adjust startDate backwards to cater for extraPoints
                DateTime adjustedStartDate = startDate.Date.AddDays(-extraPoints * 7 - 6);

                // Get the required weekly data
                getWeeklyData(ticker, adjustedStartDate, endDate);

            }
            else
            {
                // Default - use daily points
                resolution = 86400;

                // Adjust startDate backwards to cater for extraPoints. We multiply the days
                // by 7/5 as we assume 1 week has 5 trading days.
                DateTime adjustedStartDate = startDate.Date.AddDays(-Math.Ceiling(extraPoints
                    * 7.0 / 5) - 2);

                // Get the required daily data
                getDailyData(ticker, adjustedStartDate, endDate);
            }

            return true;
        }

        /// <summary>
        /// Get 15 minutes data series for timeStamps, highData, lowData, openData, closeData
        /// and volData.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        private void get15MinData(string ticker, DateTime startDate, DateTime endDate)
        {
            //
            //In this demo, we use a random number generator to generate the data. In practice,
            //you may get the data from a database or by other means. If you do not have 15 
            //minute data, you may modify the "drawChart" method below to not using 15 minute
            //data.
            //
            generateRandomData(ticker, startDate, endDate, 900);
        }

        /// <summary>
        /// Get daily data series for timeStamps, highData, lowData, openData, closeData
        /// and volData.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        private void getDailyData(string ticker, DateTime startDate, DateTime endDate)
        {
            //
            //In this demo, we use a random number generator to generate the data. In practice,
            //you may get the data from a database or by other means. A typical database code
            //example is like below. (This only shows a general idea. The exact details may differ
            //depending on your database brand and schema. The SQL, in particular the date format,
            //may be different depending on which brand of database you use.)
            //
            //	 //Open the database connection to MS SQL
            //	 System.Data.IDbConnection dbconn = new System.Data.SqlClient.SqlConnection(
            //	      "..... put your database connection string here .......");
            //   dbconn.Open();
            //
            //   //SQL statement to get the data
            //   System.Data.IDbCommand sqlCmd = dbconn.CreateCommand();
            //   sqlCmd.CommandText = "Select recordDate, highData, lowData, openData, " + 
            //         "closeData, volData From dailyFinanceTable Where ticker = '" + ticker + 
            //         "' And recordDate >= '" + startDate.ToString("yyyyMMdd") + "' And " + 
            //         "recordDate <= '" + endDate.ToString("yyyyMMdd") + "' Order By recordDate";
            //
            //   //The most convenient way to read the SQL result into arrays is to use the 
            //   //ChartDirector DBTable utility.
            //   DBTable table = new DBTable(sqlCmd.ExecuteReader());
            //   dbconn.Close();
            //
            //   //Now get the data into arrays
            //   timeStamps = table.getColAsDateTime(0);
            //   highData = table.getCol(1);
            //   lowData = table.getCol(2);
            //   openData = table.getCol(3);
            //   closeData = table.getCol(4);
            //   volData = table.getCol(5);
            //
            generateRandomData(ticker, startDate, endDate, 86400);
        }

        /// <summary>
        /// Get weekly data series for timeStamps, highData, lowData, openData, closeData
        /// and volData.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        private void getWeeklyData(string ticker, DateTime startDate, DateTime endDate)
        {
            //
            //In this demo, we use a random number generator to generate the data. In practice,
            //you may get the data from a database or by other means. If you do not have weekly
            //data, you may call "getDailyData" to get daily data first, and then call 
            //"convertDailyToWeeklyData" to convert it to weekly data, like:
            //
            //      getDailyData(startDate, endDate);
            //      convertDailyToWeeklyData();
            //
            generateRandomData(ticker, startDate, endDate, 86400 * 7);
        }

        /// <summary>
        /// Get monthly data series for timeStamps, highData, lowData, openData, closeData
        /// and volData.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        private void getMonthlyData(string ticker, DateTime startDate, DateTime endDate)
        {
            //
            //In this demo, we use a random number generator to generate the data. In practice,
            //you may get the data from a database or by other means. If you do not have monthly
            //data, you may call "getDailyData" to get daily data first, and then call 
            //"convertDailyToMonthlyData" to convert it to monthly data, like:
            //
            //      getDailyData(startDate, endDate);
            //      convertDailyToMonthlyData();
            //
            generateRandomData(ticker, startDate, endDate, 86400 * 30);
        }

        /// <summary>
        /// A random number generator designed to generate realistic financial data.
        /// </summary>
        /// <param name="ticker">The ticker symbol for the data series.</param>
        /// <param name="startDate">The starting date/time for the data series.</param>
        /// <param name="endDate">The ending date/time for the data series.</param>
        /// <param name="resolution">The period of the data series.</param>
        private void generateRandomData(string ticker, DateTime startDate, DateTime endDate,
            int resolution)
        {
            FinanceSimulator db = new FinanceSimulator(ticker, startDate, endDate, resolution);
            timeStamps = db.getTimeStamps();
            highData = db.getHighData();
            lowData = db.getLowData();
            openData = db.getOpenData();
            closeData = db.getCloseData();
            volData = db.getVolData();
        }

        /// <summary>
        /// A utility to convert daily to weekly data.
        /// </summary>
        private void convertDailyToWeeklyData()
        {
            aggregateData(new ArrayMath(timeStamps).selectStartOfWeek());
        }

        /// <summary>
        /// A utility to convert daily to monthly data.
        /// </summary>
        private void convertDailyToMonthlyData()
        {
            aggregateData(new ArrayMath(timeStamps).selectStartOfMonth());
        }

        /// <summary>
        /// An internal method used to aggregate daily data.
        /// </summary>
        private void aggregateData(ArrayMath aggregator)
        {
            timeStamps = Chart.NTime(aggregator.aggregate(Chart.CTime(timeStamps),
                Chart.AggregateFirst));
            highData = aggregator.aggregate(highData, Chart.AggregateMax);
            lowData = aggregator.aggregate(lowData, Chart.AggregateMin);
            openData = aggregator.aggregate(openData, Chart.AggregateFirst);
            closeData = aggregator.aggregate(closeData, Chart.AggregateLast);
            volData = aggregator.aggregate(volData, Chart.AggregateSum);
        }

        /// <summary>
        /// In this sample code, the chart updates when the user selection changes. You may 
        /// modify the code to update the data and chart periodically for real time charts.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectionChanged(object sender, System.EventArgs e)
        {
            if (hasFinishedInitialization)
                drawChart(winChartViewer1);
        }

        ///
        /// For the ticker symbols, the chart will update when the user enters a new symbol,
        /// and then press the enter button or leave the text box.
        ///

        private void tickerSymbol_Leave(object sender, System.EventArgs e)
        {
            // User leave ticker symbol text box - redraw chart if symbol has changed
            if (tickerSymbol.Text != tickerKey)
                drawChart(winChartViewer1);
        }

        private void tickerSymbol_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // User press enter key - same action as leaving the text box.
            if (e.KeyChar == '\\r')
                tickerSymbol_Leave(sender, e);
        }

        private void compareWith_Leave(object sender, System.EventArgs e)
        {
            // User leave compare symbol text box - redraw chart if symbol has changed
            if (compareWith.Text != compareKey)
                drawChart(winChartViewer1);
        }

        private void compareWith_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // User press enter key - same action as leaving the text box.
            if (e.KeyChar == '\\r')
                compareWith_Leave(sender, e);
        }

        /// <summary>
        /// Draw the chart according to user selection and display it in the WinChartViewer.
        /// </summary>
        /// <param name="viewer">The WinChartViewer object to display the chart.</param>
        private void drawChart(WinChartViewer viewer)
        {
            // Use InvariantCulture to draw the chart. This ensures the chart will look the
            // same on any computer.
            System.Threading.Thread.CurrentThread.CurrentCulture =
                      System.Globalization.CultureInfo.InvariantCulture;

          

            // The first moving average period selected by the user.
            int avgPeriod1;
            try { avgPeriod1 = int.Parse(movAvg1.Text); }
            catch { avgPeriod1 = 0; }
            avgPeriod1 = Math.Max(0, Math.Min(300, avgPeriod1));

            // The second moving average period selected by the user.
            int avgPeriod2;
            try { avgPeriod2 = int.Parse(movAvg2.Text); }
            catch { avgPeriod2 = 0; }
            avgPeriod2 = Math.Max(0, Math.Min(300, avgPeriod2));

            // We need extra leading data points in order to compute moving averages.
            extraPoints = Math.Max(20, Math.Max(avgPeriod1, avgPeriod2));

            // Get the data series to compare with, if any.
            DateTime viewPortStartDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.ViewPortLeft));
            DateTime viewPortEndDate = Chart.NTime(viewer.getValueAtViewPort("x", viewer.ViewPortLeft +
                viewer.ViewPortWidth));

            // Get the array indexes that corresponds to the visible start and end dates
            int startIndex = (int)Math.Floor(Chart.bSearch(timeStamps, viewPortStartDate));
            int endIndex = (int)Math.Ceiling(Chart.bSearch(timeStamps, viewPortEndDate));
            int noOfPoints = endIndex - startIndex + 1;

            // Extract the part of the data array that are visible.
            DateTime[] viewPortTimeStamps = (DateTime[])Chart.arraySlice(timeStamps, startIndex, noOfPoints);
            double[] viewPortDatahighData = (double[])Chart.arraySlice(highData, startIndex, noOfPoints);
            double[] viewPortDatalowData = (double[])Chart.arraySlice(lowData, startIndex, noOfPoints);
            double[] viewPortDataopenData = (double[])Chart.arraySlice(openData, startIndex, noOfPoints);
            double[] viewPortDatacloseData = (double[])Chart.arraySlice(closeData, startIndex, noOfPoints);
            double[] viewPortDatavolData = (double[])Chart.arraySlice(volData, startIndex, noOfPoints);
            // We now confirm the actual number of extra points (data points that are before
            // the start date) as inferred using actual data from the database.
            extraPoints = timeStamps.Length;
            for (int i = 0; i < timeStamps.Length; ++i)
            {
                if (timeStamps[i] >= startDate)
                {
                    extraPoints = i;
                    break;
                }
            }

            // Check if there is any valid data
            if (extraPoints >= viewPortTimeStamps.Length)
            {
                // No data - just display the no data message.
                errMsg(viewer, "No data available for the specified time period");
                return;
            }

            // In some finance chart presentation style, even if the data for the latest day 
            // is not fully available, the axis for the entire day will still be drawn, where
            // no data will appear near the end of the axis.
            if (resolution < 86400)
            {
                // Add extra points to the axis until it reaches the end of the day. The end
                // of day is assumed to be 4:00pm (it depends on the stock exchange).
                DateTime lastTime = timeStamps[timeStamps.Length - 1];
                int extraTrailingPoints = (int)(new TimeSpan(16, 0, 0).Subtract(
                    lastTime.TimeOfDay).TotalSeconds / resolution);

                if (extraTrailingPoints > 0)
                {
                    DateTime[] extendedTimeStamps = new DateTime[timeStamps.Length +
                        extraTrailingPoints];
                    Array.Copy(timeStamps, 0, extendedTimeStamps, 0, timeStamps.Length);
                    for (int i = 0; i < extraTrailingPoints; ++i)
                        extendedTimeStamps[i + timeStamps.Length] = lastTime.AddSeconds(
                            resolution * i);
                    timeStamps = extendedTimeStamps;
                }
            }

            //
            // At this stage, all data is available. We can draw the chart as according to 
            // user input.
            //

            //
            // Determine the chart size. In this demo, user can select 4 different chart
            // sizes. Default is the large chart size.
            //
            int width = 780;
            int mainHeight = 255;
            int indicatorHeight = 80;

            string selectedSize = ((ListItem)chartSize.SelectedItem).Key;
            if (selectedSize == "S")
            {
                // Small chart size
                width = 450;
                mainHeight = 160;
                indicatorHeight = 60;
            }
            else if (selectedSize == "M")
            {
                // Medium chart size
                width = 620;
                mainHeight = 215;
                indicatorHeight = 70;
            }
            else if (selectedSize == "H")
            {
                // Huge chart size
                width = 1000;
                mainHeight = 320;
                indicatorHeight = 90;
            }

            // Create the chart object using the selected size
            FinanceChart m = new FinanceChart(width);

            // Set the data into the chart object
            m.setData(viewPortTimeStamps, viewPortDatahighData, viewPortDatalowData, viewPortDataopenData, viewPortDatacloseData, viewPortDatavolData, extraPoints);

            //
            // We configure the title of the chart. In this demo chart design, we put the 
            // company name as the top line of the title with left alignment.
            //
            m.addPlotAreaTitle(Chart.TopLeft, tickerKey);

            // We displays the current date as well as the data resolution on the next line.
            string resolutionText = "";
            if (resolution == 30 * 86400)
                resolutionText = "Monthly";
            else if (resolution == 7 * 86400)
                resolutionText = "Weekly";
            else if (resolution == 86400)
                resolutionText = "Daily";
            else if (resolution == 900)
                resolutionText = "15-min";

            m.addPlotAreaTitle(Chart.BottomLeft, "<*font=Arial,size=8*>" + m.formatValue(
                DateTime.Now, "mmm dd, yyyy") + " - " + resolutionText + " chart");

            // A copyright message at the bottom left corner the title area
            m.addPlotAreaTitle(Chart.BottomRight,
                "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering");

            //
            // Add the first techical indicator according. In this demo, we draw the first
            // indicator on top of the main chart.
            //
            addIndicator(m, ((ListItem)indicator1.SelectedItem).Key, indicatorHeight);

            //
            // Add the main chart
            //
            m.addMainChart(mainHeight);

            //
            // Set log or linear scale according to user preference
            //
            m.setLogScale(logScale.Checked);

            //
            // Set axis labels to show data values or percentage change to user preference
            //
            if (percentageScale.Checked)
                m.setPercentageAxis();
           
            //
            // Draw any price line the user has selected
            //
            string mainType = ((ListItem)chartType.SelectedItem).Key;
            if (mainType == "Close")
                m.addCloseLine(0x000040);
            else if (mainType == "TP")
                m.addTypicalPrice(0x000040);
            else if (mainType == "WC")
                m.addWeightedClose(0x000040);
            else if (mainType == "Median")
                m.addMedianPrice(0x000040);

            //
            // Add comparison line if there is data for comparison
            //
            if ((compareData != null) && (compareData.Length > extraPoints))
                m.addComparison(compareData, 0x0000ff, compareKey);

            //
            // Add moving average lines.
            //
            addMovingAvg(m, ((ListItem)avgType1.SelectedItem).Key, avgPeriod1, 0x663300);
            addMovingAvg(m, ((ListItem)avgType2.SelectedItem).Key, avgPeriod2, 0x9900ff);

            //
            // Draw candlesticks or OHLC symbols if the user has selected them.
            //
            if (mainType == "CandleStick")
                m.addCandleStick(0x33ff33, 0xff3333);
            else if (mainType == "OHLC")
                m.addHLOC(0x008800, 0xcc0000);

            //
            // Add parabolic SAR if necessary
            //
            if (parabolicSAR.Checked)
                m.addParabolicSAR(0.02, 0.02, 0.2, Chart.DiamondShape, 5, 0x008800, 0x000000);

            //
            // Add price band/channel/envelop to the chart according to user selection
            //
            string selectedBand = ((ListItem)priceBand.SelectedItem).Key;
            if (selectedBand == "BB")
                m.addBollingerBand(20, 2, 0x9999ff, unchecked((int)(0xc06666ff)));
            else if (selectedBand == "DC")
                m.addDonchianChannel(20, 0x9999ff, unchecked((int)(0xc06666ff)));
            else if (selectedBand == "Envelop")
                m.addEnvelop(20, 0.1, 0x9999ff, unchecked((int)(0xc06666ff)));

            //
            // Add volume bars to the main chart if necessary
            //
            if (volumeBars.Checked)
                m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);

            //
            // Add additional indicators as according to user selection.
            //
            addIndicator(m, ((ListItem)indicator2.SelectedItem).Key, indicatorHeight);
            addIndicator(m, ((ListItem)indicator3.SelectedItem).Key, indicatorHeight);
            addIndicator(m, ((ListItem)indicator4.SelectedItem).Key, indicatorHeight);

            //
            // output the chart
            //
            if (xdata.Count > 0)
            {
                XYChart c = (XYChart)m.getChart(0);
               
                LineLayer layer = c.addLineLayer();
                Double[] Yval = new Double[viewPortTimeStamps.Length];
                DateTime[] Xval = new DateTime[viewPortTimeStamps.Length];

                viewPortTimeStamps.CopyTo(Xval, 0);

                for (int i = 0; i < xdatapoint.Count; i++)
                {
                    int Index = (int)Math.Floor(Chart.bSearch(viewPortTimeStamps, xdatapoint[i]));
                    Yval[Index] = viewPortDatacloseData[Index];
                }
               // layer.addDataSet(Yval, 0x000040);
                //layer.setXData(Xval);
               // layer.setFastLineMode();
              //  layer.setLineWidth(2);
                DrawLinesOld(m);
                //DrawLines(m, (double[])xdata.ToArray(typeof(double)), (double[])ydata.ToArray(typeof(double)), System.Drawing.Color.Blue); ;
               
            }
            viewer.Chart = m;

            //
            // tooltips for the chart
            //
            
            viewer.ImageMap = m.getHTMLImageMap("", "", "title='" + m.getToolTipDateFormat()
                + " {value|P}'");
        }

        /// <summary>
        /// Add a moving average line to the FinanceChart object.
        /// </summary>
        /// <param name="m">The FinanceChart object to add the line to.</param>
        /// <param name="avgType">The moving average type (SMA/EMA/TMA/WMA).</param>
        /// <param name="avgPeriod">The moving average period.</param>
        /// <param name="color">The color of the line.</param>
        /// <returns>The LineLayer object representing line layer created.</returns>
        /// 
        private void DrawLines(MultiChart m, double[] XData, double[] YData, System.Drawing.Color ThisLineColor)
        {
            XYChart c = (XYChart)m.getChart(0);
            DrawArea d = m.initDynamicLayer();
            d.initDynamicLayer();

            PlotArea plotArea = c.getPlotArea();
            int plotAreaLeftX = plotArea.getLeftX() + c.getAbsOffsetX();
            int plotAreaTopY = plotArea.getTopY() + c.getAbsOffsetY();
            if (XData.Length > 0)
            {
                double xValue = (c.getNearestXValue(XData[0]));
                double yValue = c.getYValue((int)YData[0]);
                int xCoor = c.getXCoor(xValue);
                int yCoor = c.getYCoor(yValue);
                double x1Value = (c.getNearestXValue(XData[XData.Length - 1]));
                double y1Value = c.getYValue((int)YData[XData.Length - 1]);
                int x1Coor = c.getXCoor(x1Value);
                int y1Coor = c.getYCoor(y1Value);
                d.line(xCoor, yCoor, x1Coor, y1Coor, ToArgb(System.Drawing.Color.White));

            }



            //((XYChart)c.getChart(0)).addLine(Convert.ToInt32(data[0]), Convert.ToInt32(data[0]), Convert.ToInt32(data[data.Length - 1]), Convert.ToInt32(data[data.Length - 1]), ToArgb(LineColor), 2);
            //((XYChart)c.getChart(0)).addLine(0, 0, Convert.ToInt32(data[data.Length - 1]), Convert.ToInt32(data[data.Length - 1]), ToArgb(LineColor), 2);
            //LineLayer l=c.addLine(data[0],data[0],data[data.Length-1],,data[data.Length-1],toarg
            //   int xCoor = c.getXCoor(xValue);
            //int yCoor = c.getYCoor(yValue);
            //for (int j = 0; j < c.getLayerCount(); ++j)
            //    {
            //        Layer layer = c.getLayerByZ(j);
            //    int xIndex = layer.getXIndexOf(xValue);
            //    ChartDirector.DataSet dataSet1 = layer.getDataSet(layer.getDataSetCount() - 1);
            //     Axis yAxis = dataSet1.getUseYAxis();
            //     int xPos = yAxis.getX() + ((yAxis.getAlignment() == Chart.Left) ? -4 : 4);

            //     d.line(0, yCoor, xPos, 0, ToArgb(Color.White));
            // }

        }
        private void DrawLinesOld(MultiChart m)
        {
            if (xdata.Count > 0)
            {
                XYChart c = (XYChart)m.getChart(0);

                //int xcoor = c.getXCoor(Convert.ToDouble(xdata[0]));
                //int ycoor = c.getYCoor(Convert.ToDouble(ydata[0]));
                //int ycoor1 = c.getYCoor(Convert.ToDouble(ydata[ydata.Count - 1]));
                //int xcoor1 = c.getXCoor(Convert.ToDouble(xdata[xdata.Count - 1]));
                //Line line = m.addLine(Convert.ToInt32(xdata[0]), Convert.ToInt32(ydata[0]), Convert.ToInt32(xdata[xdata.Count - 1]), Convert.ToInt32(ydata[ydata.Count - 1]), 0x000040, 2);
              

                //StepLineLayer sl = c.addStepLineLayer(Yval, 0x000040);
                //layer.addDataSet(Yval, 0x000040);
                ////layer.setXData(Xval);
                //layer.setFastLineMode();
                //layer.setLineWidth(2);

                //int xcoor = c.getXCoor(Convert.ToDouble(xdata[0]));
                //int xcoor1 = c.getXCoor(Convert.ToDouble(xdata[xdata.Count - 1]));
                //for (int i = 0; i < c.getLayerCount(); ++i)
                //{
                //    Layer layer = c.getLayerByZ(i);

                //    // The data array index of the x-value
                //    int xIndex = layer.getXIndexOf(Convert.ToDouble(xdata[0]));
                //    int xIndex1 = layer.getXIndexOf(Convert.ToDouble(xdata[xdata.Count - 1]));
                //    // Iterate through all the data sets in the layer

                //        ChartDirector.DataSet dataSet = layer.getDataSetByZ(layer.getDataSetCount()-1);
                //        int yCoor = c.getYCoor(dataSet.getPosition(xIndex), dataSet.getUseYAxis());
                //        int yCoor1 = c.getYCoor(dataSet.getPosition(xIndex1), dataSet.getUseYAxis());
                //        Line line = c.addLine(xcoor, xcoor, xcoor1, xcoor1 + 200, 0x000040, 2);

                //    }
                //}
                //int ycoor = c.getYCoor(Convert.ToDouble(ydata[0]),c.yAxis2());
                //int ycoor1 = c.getYCoor(Convert.ToDouble(ydata[ydata.Count - 1]));

                Line line = m.addLine(Convert.ToInt32(xdata[0]), Convert.ToInt32(ydata[0]), Convert.ToInt32(xdata[xdata.Count - 1]), Convert.ToInt32(ydata[ydata.Count - 1]), 0x000040, 2);
            }
            
        }

        private void hScrollBar1_ValueChanged(object sender, EventArgs e)
        {
            // When the view port is changed (user drags on the chart to scroll), the scroll bar will get
            // updated. When the scroll bar changes (eg. user drags on the scroll bar), the view port will
            // get updated. This creates an infinite loop. To avoid this, the scroll bar can update the 
            // view port only if the view port is not updating the scroll bar.
            if (hasFinishedInitialization && !winChartViewer1.IsInViewPortChangedEvent)
            {
                // Set the view port based on the scroll bar
                winChartViewer1.ViewPortLeft = ((double)(hScrollBar1.Value - hScrollBar1.Minimum))
                    / (hScrollBar1.Maximum - hScrollBar1.Minimum);

                // Trigger a view port changed event to update the chart
                winChartViewer1.updateViewPort(true, false);
            }
        }
        protected LineLayer addMovingAvg(FinanceChart m, string avgType, int avgPeriod, int color)
        {
            if (avgPeriod > 1)
            {
                if (avgType == "SMA")
                    return m.addSimpleMovingAvg(avgPeriod, color);
                else if (avgType == "EMA")
                    return m.addExpMovingAvg(avgPeriod, color);
                else if (avgType == "TMA")
                    return m.addTriMovingAvg(avgPeriod, color);
                else if (avgType == "WMA")
                    return m.addWeightedMovingAvg(avgPeriod, color);
            }
            return null;
        }

        /// <summary>
        /// Add an indicator chart to the FinanceChart object. In this demo example, the indicator
        /// parameters (such as the period used to compute RSI, colors of the lines, etc.) are hard
        /// coded to commonly used values. You are welcome to design a more complex user interface 
        /// to allow users to set the parameters.
        /// </summary>
        /// <param name="m">The FinanceChart object to add the line to.</param>
        /// <param name="indicator">The selected indicator.</param>
        /// <param name="height">Height of the chart in pixels</param>
        /// <returns>The XYChart object representing indicator chart.</returns>
        protected XYChart addIndicator(FinanceChart m, string indicator, int height)
        {
            if (indicator == "RSI")
                return m.addRSI(height, 14, 0x800080, 20, 0xff6666, 0x6666ff);
            else if (indicator == "StochRSI")
                return m.addStochRSI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
            else if (indicator == "MACD")
                return m.addMACD(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
            else if (indicator == "FStoch")
                return m.addFastStochastic(height, 14, 3, 0x6060, 0x606000);
            else if (indicator == "SStoch")
                return m.addSlowStochastic(height, 14, 3, 0x6060, 0x606000);
            else if (indicator == "ATR")
                return m.addATR(height, 14, 0x808080, 0xff);
            else if (indicator == "ADX")
                return m.addADX(height, 14, 0x8000, 0x800000, 0x80);
            else if (indicator == "DCW")
                return m.addDonchianWidth(height, 20, 0xff);
            else if (indicator == "BBW")
                return m.addBollingerWidth(height, 20, 2, 0xff);
            else if (indicator == "DPO")
                return m.addDPO(height, 20, 0xff);
            else if (indicator == "PVT")
                return m.addPVT(height, 0xff);
            else if (indicator == "Momentum")
                return m.addMomentum(height, 12, 0xff);
            else if (indicator == "Performance")
                return m.addPerformance(height, 0xff);
            else if (indicator == "ROC")
                return m.addROC(height, 12, 0xff);
            else if (indicator == "OBV")
                return m.addOBV(height, 0xff);
            else if (indicator == "AccDist")
                return m.addAccDist(height, 0xff);
            else if (indicator == "CLV")
                return m.addCLV(height, 0xff);
            else if (indicator == "WilliamR")
                return m.addWilliamR(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
            else if (indicator == "Aroon")
                return m.addAroon(height, 14, 0x339933, 0x333399);
            else if (indicator == "AroonOsc")
                return m.addAroonOsc(height, 14, 0xff);
            else if (indicator == "CCI")
                return m.addCCI(height, 20, 0x800080, 100, 0xff6666, 0x6666ff);
            else if (indicator == "EMV")
                return m.addEaseOfMovement(height, 9, 0x6060, 0x606000);
            else if (indicator == "MDX")
                return m.addMassIndex(height, 0x800080, 0xff6666, 0x6666ff);
            else if (indicator == "CVolatility")
                return m.addChaikinVolatility(height, 10, 10, 0xff);
            else if (indicator == "COscillator")
                return m.addChaikinOscillator(height, 0xff);
            else if (indicator == "CMF")
                return m.addChaikinMoneyFlow(height, 21, 0x8000);
            else if (indicator == "NVI")
                return m.addNVI(height, 255, 0xff, 0x883333);
            else if (indicator == "PVI")
                return m.addPVI(height, 255, 0xff, 0x883333);
            else if (indicator == "MFI")
                return m.addMFI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
            else if (indicator == "PVO")
                return m.addPVO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
            else if (indicator == "PPO")
                return m.addPPO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000);
            else if (indicator == "UO")
                return m.addUltimateOscillator(height, 7, 14, 28, 0x800080, 20, 0xff6666, 0x6666ff);
            else if (indicator == "Vol")
                return m.addVolIndicator(height, 0x99ff99, 0xff9999, 0xc0c0c0);
            else if (indicator == "TRIX")
                return m.addTRIX(height, 12, 0xff);
            return null;
        }

        /// <summary>
        /// Creates a dummy chart to show an error message.
        /// </summary>
        /// <param name="viewer">The WinChartViewer to display the error message.</param>
        /// <param name="msg">The error message</param>
        protected void errMsg(WinChartViewer viewer, string msg)
        {
            MultiChart m = new MultiChart(400, 200);
            m.addTitle2(Chart.Center, msg, "Arial", 10).setMaxWidth(m.getWidth());
            viewer.Image = m.makeImage();
        }
        //
        // Pointer (Drag to Scroll) button event handler
        //
        private void pointerPB_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
                winChartViewer1.MouseUsage = WinChartMouseUsage.ScrollOnDrag;
        }
        private void updateControls(WinChartViewer viewer)
        {
            // In this demo, we need to update the scroll bar to reflect the view port position and
            // width of the view port.
            hScrollBar1.Enabled = winChartViewer1.ViewPortWidth < 1;
            hScrollBar1.LargeChange = (int)Math.Ceiling(winChartViewer1.ViewPortWidth *
                (hScrollBar1.Maximum - hScrollBar1.Minimum));
            hScrollBar1.SmallChange = (int)Math.Ceiling(hScrollBar1.LargeChange * 0.1);
            hScrollBar1.Value = (int)Math.Round(winChartViewer1.ViewPortLeft *
                (hScrollBar1.Maximum - hScrollBar1.Minimum)) + hScrollBar1.Minimum;
        }
        //
        // Zoom In button event handler
        //
        private void zoomInPB_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
                winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomIn;
        }

        //
        // Zoom Out button event handler
        //
        private void zoomOutPB_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
                winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomOut;
        }

        private void winChartViewer1_ViewPortChanged(object sender, WinViewPortEventArgs e)
        {
            // In addition to updating the chart, we may also need to update other controls that
            // changes based on the view port.
            updateControls(winChartViewer1);

            // Update the chart if necessary
            if (e.NeedUpdateChart)
                drawChart(winChartViewer1);
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {

        }

        private void txtmaxDsplay_TextChanged(object sender, EventArgs e)
        {
            hasFinishedInitialization = false;
            // Load the data
            loadData();

            // Initialize the WinChartViewer
            initChartViewer(winChartViewer1);

            // Can handle events now
            hasFinishedInitialization = true;

            // Trigger the ViewPortChanged event to draw the chart
            winChartViewer1.updateViewPort(true, true);
        }
        private void trackFinance(MultiChart m, int mouseX)
        {
            // Clear the current dynamic layer and get the DrawArea object to draw on it.
            DrawArea d = m.initDynamicLayer();

            // It is possible for a FinanceChart to be empty, so we need to check for it.
            if (m.getChartCount() == 0)
            {
                return;
            }

            // Get the data x-value that is nearest to the mouse
            int xValue = (int)(((XYChart)m.getChart(0)).getNearestXValue(mouseX));

            // Iterate the XY charts (main price chart and indicator charts) in the FinanceChart
            XYChart c = null;
            for (int i = 0; i < m.getChartCount(); ++i)
            {
                c = (XYChart)m.getChart(i);

                // Variables to hold the legend entries
                string ohlcLegend = "";
                ArrayList legendEntries = new ArrayList();

                // Iterate through all layers to find the highest data point
                for (int j = 0; j < c.getLayerCount(); ++j)
                {
                    Layer layer = c.getLayerByZ(j);
                    int xIndex = layer.getXIndexOf(xValue);
                    int dataSetCount = layer.getDataSetCount();

                    // In a FinanceChart, only layers showing OHLC data can have 4 data sets
                    if (dataSetCount == 4)
                    {
                        double highValue = layer.getDataSet(0).getValue(xIndex);
                        double lowValue = layer.getDataSet(1).getValue(xIndex);
                        double openValue = layer.getDataSet(2).getValue(xIndex);
                        double closeValue = layer.getDataSet(3).getValue(xIndex);

                        if (closeValue != Chart.NoValue)
                        {
                            // Build the OHLC legend
                            ohlcLegend = "Open: " + c.formatValue(openValue, "{value|P4}") + ", High: " +
                                c.formatValue(highValue, "{value|P4}") + ", Low: " + c.formatValue(lowValue,
                                "{value|P4}") + ", Close: " + c.formatValue(closeValue, "{value|P4}");

                            // We also draw an upward or downward triangle for up and down days and the %
                            // change
                            double lastCloseValue = layer.getDataSet(3).getValue(xIndex - 1);
                            if (lastCloseValue != Chart.NoValue)
                            {
                                double change = closeValue - lastCloseValue;
                                double percent = change * 100 / closeValue;
                                string symbol = ((change >= 0) ?
                                    "<*font,color=008800*><*img=@triangle,width=8,color=008800*>" :
                                    "<*font,color=CC0000*><*img=@invertedtriangle,width=8,color=CC0000*>");

                                ohlcLegend = ohlcLegend + "  " + symbol + " " + c.formatValue(change,
                                    "{value|P4}") + " (" + c.formatValue(percent, "{value|2}") + "%)<*/font*>"
                                    ;
                            }

                            // Use a <*block*> to make sure the line does not wrap within the legend entry
                            ohlcLegend = "<*block*>" + ohlcLegend + "      <*/*>";
                        }
                    }
                    else
                    {
                        // Iterate through all the data sets in the layer
                        for (int k = 0; k < layer.getDataSetCount(); ++k)
                        {
                            ChartDirector.DataSet dataSet = layer.getDataSetByZ(k);

                            string name = dataSet.getDataName();
                            double value = dataSet.getValue(xIndex);
                            if ((!string.IsNullOrEmpty(name)) && (value != Chart.NoValue))
                            {

                                // In a FinanceChart, the data set name consists of the indicator name and its
                                // latest value. It is like "Vol: 123M" or "RSI (14): 55.34". As we are
                                // generating the values dynamically, we need to extract the indictor name
                                // out, and also the volume unit (if any).

                                // The unit character, if any, is the last character and must not be a digit.
                                string unitChar = name.Substring(name.Length - 1);
                                if (unitChar.CompareTo("0") >= 0 && unitChar.CompareTo("9") <= 0)
                                {
                                    unitChar = "";
                                }

                                // The indicator name is the part of the name up to the colon character.
                                int delimiterPosition = name.IndexOf(":");
                                if (delimiterPosition != -1)
                                {
                                    name = name.Substring(0, delimiterPosition);
                                }

                                // In a FinanceChart, if there are two data sets, it must be representing a
                                // range.
                                if (dataSetCount == 2)
                                {
                                    // We show both values in the range in a single legend entry
                                    value = layer.getDataSet(0).getValue(xIndex);
                                    double value2 = layer.getDataSet(1).getValue(xIndex);
                                    name = name + ": " + c.formatValue(Math.Min(value, value2), "{value|P3}")
                                         + " - " + c.formatValue(Math.Max(value, value2), "{value|P3}");
                                }
                                else
                                {
                                    // In a FinanceChart, only the layer for volume bars has 3 data sets for
                                    // up/down/flat days
                                    if (dataSetCount == 3)
                                    {
                                        // The actual volume is the sum of the 3 data sets.
                                        value = layer.getDataSet(0).getValue(xIndex) + layer.getDataSet(1
                                            ).getValue(xIndex) + layer.getDataSet(2).getValue(xIndex);
                                    }

                                    // Create the legend entry
                                    name = name + ": " + c.formatValue(value, "{value|P3}") + unitChar;
                                }

                                // Build the legend entry, consist of a colored square box and the name (with
                                // the data value in it).
                                legendEntries.Add("<*block*><*img=@square,width=8,edgeColor=000000,color=" +
                                    dataSet.getDataColor().ToString("x") + "*> " + name + "<*/*>");
                            }
                        }
                    }
                }

                // Get the plot area position relative to the entire FinanceChart
                PlotArea plotArea = c.getPlotArea();
                int plotAreaLeftX = plotArea.getLeftX() + c.getAbsOffsetX();
                int plotAreaTopY = plotArea.getTopY() + c.getAbsOffsetY();

                // The legend is formed by concatenating the legend entries.
                legendEntries.Reverse();
                string legendText = String.Join("      ", (string[])legendEntries.ToArray(typeof(string)));

                // Add the date and the ohlcLegend (if any) at the beginning of the legend
                legendText = "<*block,valign=top,maxWidth=" + (plotArea.getWidth() - 5) +
                    "*><*font=Arial Bold*>[" + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") +
                    "]<*/font*>      " + ohlcLegend + legendText;

                // Draw a vertical track line at the x-position
                d.vline(plotAreaTopY, plotAreaTopY + plotArea.getHeight(), c.getXCoor(xValue) +
                    c.getAbsOffsetX(), d.dashLineColor(0x000000, 0x0101));

                // Display the legend on the top of the plot area
                TTFText t = d.text(legendText, "Arial", 8);
                t.draw(plotAreaLeftX + 5, plotAreaTopY + 3, 0x000000, Chart.TopLeft);
            }
        }


        

        private void winChartViewer1_MouseMovePlotArea(object sender, MouseEventArgs e)
        {
            //if (ISline)
            //{
            //    MultiChart m = (MultiChart)winChartViewer1.Chart;
            //    XYChart c = (XYChart)m.getChart(0);
            //    DateTime xVal = Convert.ToDateTime(c.xAxis().getFormattedLabel(c.getNearestXValue(winChartViewer1.PlotAreaMouseX), "mmm dd, yyyy hh:nn:ss"));
            //    //double xValue = c.getNearestXValue(winChartViewer1.PlotAreaMouseX);
            //    double yValue = c.getYValue(winChartViewer1.PlotAreaMouseY);
            //    xdata.Add(xVal);
            //    ydata.Add(yValue);
            //}
            //WinChartViewer viewer = (WinChartViewer)sender;
            //trackFinance((MultiChart)viewer.Chart, viewer.PlotAreaMouseX);
            //viewer.updateDisplay();
        }
        public int ToArgb(System.Drawing.Color color)
        {
            byte[] bytes = new byte[] { color.B, color.G, color.R, 0 };
            return BitConverter.ToInt32(bytes, 0);
        }
        private void winChartViewer1_Click(object sender, EventArgs e)
        {
            
            MultiChart m = (MultiChart)winChartViewer1.Chart;
            XYChart c = (XYChart)m.getChart(0);
            if (!ISline)
            {
                ydata.Clear();
                xdata.Clear();
               
                DateTime xVal = Convert.ToDateTime(c.xAxis().getFormattedLabel(c.getNearestXValue(winChartViewer1.PlotAreaMouseX), "mmm dd, yyyy hh:nn:ss"));
                //double xValue = c.getNearestXValue(winChartViewer1.PlotAreaMouseX);
                double yVal= c.getYValue(winChartViewer1.PlotAreaMouseY);
                double xValue = winChartViewer1.PlotAreaMouseX;
                double yValue = winChartViewer1.PlotAreaMouseY;
                xdata.Add(xValue);
                ydata.Add(yValue);
                xdatapoint.Add(xVal);
                ydatapoint.Add(yVal);
                ISline = true;
            }
            else
            {
                DateTime xVal = Convert.ToDateTime(c.xAxis().getFormattedLabel(c.getNearestXValue(winChartViewer1.PlotAreaMouseX), "mmm dd, yyyy hh:nn:ss"));
                //double xValue = c.getNearestXValue(winChartViewer1.PlotAreaMouseX);
                double yVal = c.getYValue(winChartViewer1.PlotAreaMouseY);
                double xValue = winChartViewer1.PlotAreaMouseX;
                double yValue = winChartViewer1.PlotAreaMouseY;
                xdata.Add(xValue);
                ydata.Add(yValue);
                xdatapoint.Add(xVal);
                ydatapoint.Add(yVal);

                ISline = false;
                DrawLinesOld(m);
               // DrawLines(m, (double[])xdata.ToArray(typeof(double)), (double[])ydata.ToArray(typeof(double)), System.Drawing.Color.Blue);
               // winChartViewer1.updateDisplay();
                winChartViewer1.updateViewPort(true, true);
                

            }
        }

       
    }
}
financedemo.cs
using System;
using ChartDirector;

namespace CSharpChartExplorer
{
    class financedemo : DemoModule
    {
        //Name of demo module
        public string getName() { return "Interactive Financial Chart"; }

        //Number of charts produced in this demo module
        public int getNoOfCharts()
        {
            return 1;
        }

        //Main code for creating chart.
        public void createChart(WinChartViewer viewer, int chartIndex)
        {
            //This demo uses its own form. The viewer on the right pane is not used.
            viewer.Image = null;
            System.Windows.Forms.Form f = new FrmFinanceDemo();
            f.ShowDialog();
            f.Dispose();
           
        }
    }
}
frmfinancedemo.Designer.cs
namespace CSharpChartExplorer
{
    partial class FrmFinanceDemo
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmFinanceDemo));
            this.rightPanel = new System.Windows.Forms.Panel();
            this.txtmaxDsplay = new System.Windows.Forms.TextBox();
            this.pointerPB = new System.Windows.Forms.RadioButton();
            this.zoomInPB = new System.Windows.Forms.RadioButton();
            this.zoomOutPB = new System.Windows.Forms.RadioButton();
            this.hScrollBar1 = new System.Windows.Forms.HScrollBar();
            this.winChartViewer1 = new ChartDirector.WinChartViewer();
            this.leftPanel = new System.Windows.Forms.Panel();
            this.compareWith = new System.Windows.Forms.TextBox();
            this.compareWithLabel = new System.Windows.Forms.Label();
            this.tickerSymbol = new System.Windows.Forms.TextBox();
            this.percentageScale = new System.Windows.Forms.CheckBox();
            this.parabolicSAR = new System.Windows.Forms.CheckBox();
            this.separator = new System.Windows.Forms.Label();
            this.tickerSymbolLabel = new System.Windows.Forms.Label();
            this.movAvg2 = new System.Windows.Forms.TextBox();
            this.avgType2 = new System.Windows.Forms.ComboBox();
            this.movAvg1 = new System.Windows.Forms.TextBox();
            this.avgType1 = new System.Windows.Forms.ComboBox();
            this.indicator4 = new System.Windows.Forms.ComboBox();
            this.indicator3 = new System.Windows.Forms.ComboBox();
            this.indicator2 = new System.Windows.Forms.ComboBox();
            this.indicator1 = new System.Windows.Forms.ComboBox();
            this.priceBand = new System.Windows.Forms.ComboBox();
            this.chartType = new System.Windows.Forms.ComboBox();
            this.indicatorLabel = new System.Windows.Forms.Label();
            this.movAvgLabel = new System.Windows.Forms.Label();
            this.priceBandLabel = new System.Windows.Forms.Label();
            this.chartTypeLabel = new System.Windows.Forms.Label();
            this.logScale = new System.Windows.Forms.CheckBox();
            this.volumeBars = new System.Windows.Forms.CheckBox();
            this.chartSize = new System.Windows.Forms.ComboBox();
            this.chartSizeLabel = new System.Windows.Forms.Label();
            this.timeRange = new System.Windows.Forms.ComboBox();
            this.timePeriodLabel = new System.Windows.Forms.Label();
            this.topLabel = new System.Windows.Forms.Label();
            this.rightPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).BeginInit();
            this.leftPanel.SuspendLayout();
            this.SuspendLayout();
            // 
            // rightPanel
            // 
            this.rightPanel.AutoScroll = true;
            this.rightPanel.BackColor = System.Drawing.Color.White;
            this.rightPanel.Controls.Add(this.txtmaxDsplay);
            this.rightPanel.Controls.Add(this.pointerPB);
            this.rightPanel.Controls.Add(this.zoomInPB);
            this.rightPanel.Controls.Add(this.zoomOutPB);
            this.rightPanel.Controls.Add(this.hScrollBar1);
            this.rightPanel.Controls.Add(this.winChartViewer1);
            this.rightPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.rightPanel.Location = new System.Drawing.Point(160, 24);
            this.rightPanel.Name = "rightPanel";
            this.rightPanel.Size = new System.Drawing.Size(792, 538);
            this.rightPanel.TabIndex = 6;
            // 
            // txtmaxDsplay
            // 
            this.txtmaxDsplay.Location = new System.Drawing.Point(384, 4);
            this.txtmaxDsplay.Name = "txtmaxDsplay";
            this.txtmaxDsplay.Size = new System.Drawing.Size(137, 20);
            this.txtmaxDsplay.TabIndex = 8;
            this.txtmaxDsplay.Text = "60";
            this.txtmaxDsplay.TextChanged += new System.EventHandler(this.txtmaxDsplay_TextChanged);
            // 
            // pointerPB
            // 
            this.pointerPB.Appearance = System.Windows.Forms.Appearance.Button;
            this.pointerPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.pointerPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.pointerPB.Image = ((System.Drawing.Image)(resources.GetObject("pointerPB.Image")));
            this.pointerPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.pointerPB.Location = new System.Drawing.Point(6, 0);
            this.pointerPB.Name = "pointerPB";
            this.pointerPB.Size = new System.Drawing.Size(120, 28);
            this.pointerPB.TabIndex = 5;
            this.pointerPB.Text = "      Pointer";
            // 
            // zoomInPB
            // 
            this.zoomInPB.Appearance = System.Windows.Forms.Appearance.Button;
            this.zoomInPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.zoomInPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.zoomInPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomInPB.Image")));
            this.zoomInPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.zoomInPB.Location = new System.Drawing.Point(132, 0);
            this.zoomInPB.Name = "zoomInPB";
            this.zoomInPB.Size = new System.Drawing.Size(120, 28);
            this.zoomInPB.TabIndex = 6;
            this.zoomInPB.Text = "      Zoom In";
            this.zoomInPB.CheckedChanged += new System.EventHandler(this.zoomInPB_CheckedChanged);
            // 
            // zoomOutPB
            // 
            this.zoomOutPB.Appearance = System.Windows.Forms.Appearance.Button;
            this.zoomOutPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.zoomOutPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.zoomOutPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomOutPB.Image")));
            this.zoomOutPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.zoomOutPB.Location = new System.Drawing.Point(258, 0);
            this.zoomOutPB.Name = "zoomOutPB";
            this.zoomOutPB.Size = new System.Drawing.Size(120, 28);
            this.zoomOutPB.TabIndex = 7;
            this.zoomOutPB.Text = "      Zoom Out";
            this.zoomOutPB.CheckedChanged += new System.EventHandler(this.zoomOutPB_CheckedChanged);
            // 
            // hScrollBar1
            // 
            this.hScrollBar1.BackColor = System.Drawing.Color.White;
            this.hScrollBar1.Cursor = System.Windows.Forms.Cursors.Default;
            this.hScrollBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.hScrollBar1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.hScrollBar1.Location = new System.Drawing.Point(0, 522);
            this.hScrollBar1.Maximum = 1000000000;
            this.hScrollBar1.Name = "hScrollBar1";
            this.hScrollBar1.Size = new System.Drawing.Size(792, 16);
            this.hScrollBar1.TabIndex = 4;
            this.hScrollBar1.Scroll += new System.Windows.Forms.ScrollEventHandler(this.hScrollBar1_Scroll);
            this.hScrollBar1.ValueChanged += new System.EventHandler(this.hScrollBar1_ValueChanged);
            // 
            // winChartViewer1
            // 
            this.winChartViewer1.Location = new System.Drawing.Point(6, 27);
            this.winChartViewer1.Name = "winChartViewer1";
            this.winChartViewer1.Size = new System.Drawing.Size(780, 470);
            this.winChartViewer1.TabIndex = 0;
            this.winChartViewer1.TabStop = false;
            this.winChartViewer1.MouseMovePlotArea += new System.Windows.Forms.MouseEventHandler(this.winChartViewer1_MouseMovePlotArea);
            this.winChartViewer1.ViewPortChanged += new ChartDirector.WinViewPortEventHandler(this.winChartViewer1_ViewPortChanged);
            this.winChartViewer1.Click += new System.EventHandler(this.winChartViewer1_Click);
            // 
            // leftPanel
            // 
            this.leftPanel.AutoScroll = true;
            this.leftPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(186)))), ((int)(((byte)(221)))), ((int)(((byte)(255)))));
            this.leftPanel.Controls.Add(this.compareWith);
            this.leftPanel.Controls.Add(this.compareWithLabel);
            this.leftPanel.Controls.Add(this.tickerSymbol);
            this.leftPanel.Controls.Add(this.percentageScale);
            this.leftPanel.Controls.Add(this.parabolicSAR);
            this.leftPanel.Controls.Add(this.separator);
            this.leftPanel.Controls.Add(this.tickerSymbolLabel);
            this.leftPanel.Controls.Add(this.movAvg2);
            this.leftPanel.Controls.Add(this.avgType2);
            this.leftPanel.Controls.Add(this.movAvg1);
            this.leftPanel.Controls.Add(this.avgType1);
            this.leftPanel.Controls.Add(this.indicator4);
            this.leftPanel.Controls.Add(this.indicator3);
            this.leftPanel.Controls.Add(this.indicator2);
            this.leftPanel.Controls.Add(this.indicator1);
            this.leftPanel.Controls.Add(this.priceBand);
            this.leftPanel.Controls.Add(this.chartType);
            this.leftPanel.Controls.Add(this.indicatorLabel);
            this.leftPanel.Controls.Add(this.movAvgLabel);
            this.leftPanel.Controls.Add(this.priceBandLabel);
            this.leftPanel.Controls.Add(this.chartTypeLabel);
            this.leftPanel.Controls.Add(this.logScale);
            this.leftPanel.Controls.Add(this.volumeBars);
            this.leftPanel.Controls.Add(this.chartSize);
            this.leftPanel.Controls.Add(this.chartSizeLabel);
            this.leftPanel.Controls.Add(this.timeRange);
            this.leftPanel.Controls.Add(this.timePeriodLabel);
            this.leftPanel.Dock = System.Windows.Forms.DockStyle.Left;
            this.leftPanel.Location = new System.Drawing.Point(0, 24);
            this.leftPanel.Name = "leftPanel";
            this.leftPanel.Size = new System.Drawing.Size(160, 538);
            this.leftPanel.TabIndex = 4;
            // 
            // compareWith
            // 
            this.compareWith.Location = new System.Drawing.Point(8, 64);
            this.compareWith.Name = "compareWith";
            this.compareWith.Size = new System.Drawing.Size(128, 20);
            this.compareWith.TabIndex = 1;
            this.compareWith.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.compareWith_KeyPress);
            this.compareWith.Leave += new System.EventHandler(this.compareWith_Leave);
            // 
            // compareWithLabel
            // 
            this.compareWithLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.compareWithLabel.Location = new System.Drawing.Point(8, 48);
            this.compareWithLabel.Name = "compareWithLabel";
            this.compareWithLabel.Size = new System.Drawing.Size(100, 16);
            this.compareWithLabel.TabIndex = 21;
            this.compareWithLabel.Text = "Compare With";
            // 
            // tickerSymbol
            // 
            this.tickerSymbol.Location = new System.Drawing.Point(8, 24);
            this.tickerSymbol.Name = "tickerSymbol";
            this.tickerSymbol.Size = new System.Drawing.Size(128, 20);
            this.tickerSymbol.TabIndex = 0;
            this.tickerSymbol.Text = "ASE.SYMBOL";
            this.tickerSymbol.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tickerSymbol_KeyPress);
            this.tickerSymbol.Leave += new System.EventHandler(this.tickerSymbol_Leave);
            // 
            // percentageScale
            // 
            this.percentageScale.Location = new System.Drawing.Point(8, 236);
            this.percentageScale.Name = "percentageScale";
            this.percentageScale.Size = new System.Drawing.Size(128, 20);
            this.percentageScale.TabIndex = 7;
            this.percentageScale.Text = "Percentage Scale";
            this.percentageScale.CheckedChanged += new System.EventHandler(this.selectionChanged);
            // 
            // parabolicSAR
            // 
            this.parabolicSAR.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(186)))), ((int)(((byte)(221)))), ((int)(((byte)(255)))));
            this.parabolicSAR.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.parabolicSAR.Location = new System.Drawing.Point(8, 196);
            this.parabolicSAR.Name = "parabolicSAR";
            this.parabolicSAR.Size = new System.Drawing.Size(128, 20);
            this.parabolicSAR.TabIndex = 5;
            this.parabolicSAR.Text = "Parabolic SAR";
            this.parabolicSAR.UseVisualStyleBackColor = false;
            this.parabolicSAR.CheckedChanged += new System.EventHandler(this.selectionChanged);
            // 
            // separator
            // 
            this.separator.BackColor = System.Drawing.Color.Black;
            this.separator.Dock = System.Windows.Forms.DockStyle.Right;
            this.separator.Location = new System.Drawing.Point(159, 0);
            this.separator.Name = "separator";
            this.separator.Size = new System.Drawing.Size(1, 538);
            this.separator.TabIndex = 19;
            // 
            // tickerSymbolLabel
            // 
            this.tickerSymbolLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tickerSymbolLabel.Location = new System.Drawing.Point(8, 8);
            this.tickerSymbolLabel.Name = "tickerSymbolLabel";
            this.tickerSymbolLabel.Size = new System.Drawing.Size(100, 16);
            this.tickerSymbolLabel.TabIndex = 18;
            this.tickerSymbolLabel.Text = "Ticker Symbol";
            // 
            // movAvg2
            // 
            this.movAvg2.Location = new System.Drawing.Point(96, 388);
            this.movAvg2.Name = "movAvg2";
            this.movAvg2.Size = new System.Drawing.Size(40, 20);
            this.movAvg2.TabIndex = 13;
            this.movAvg2.Text = "25";
            this.movAvg2.TextChanged += new System.EventHandler(this.selectionChanged);
            // 
            // avgType2
            // 
            this.avgType2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.avgType2.Location = new System.Drawing.Point(8, 388);
            this.avgType2.Name = "avgType2";
            this.avgType2.Size = new System.Drawing.Size(88, 22);
            this.avgType2.TabIndex = 12;
            this.avgType2.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // movAvg1
            // 
            this.movAvg1.Location = new System.Drawing.Point(96, 364);
            this.movAvg1.Name = "movAvg1";
            this.movAvg1.Size = new System.Drawing.Size(40, 20);
            this.movAvg1.TabIndex = 11;
            this.movAvg1.Text = "10";
            this.movAvg1.TextChanged += new System.EventHandler(this.selectionChanged);
            // 
            // avgType1
            // 
            this.avgType1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.avgType1.Location = new System.Drawing.Point(8, 364);
            this.avgType1.Name = "avgType1";
            this.avgType1.Size = new System.Drawing.Size(88, 22);
            this.avgType1.TabIndex = 10;
            this.avgType1.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // indicator4
            // 
            this.indicator4.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.indicator4.Location = new System.Drawing.Point(8, 504);
            this.indicator4.Name = "indicator4";
            this.indicator4.Size = new System.Drawing.Size(130, 22);
            this.indicator4.TabIndex = 17;
            this.indicator4.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // indicator3
            // 
            this.indicator3.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.indicator3.Location = new System.Drawing.Point(8, 480);
            this.indicator3.Name = "indicator3";
            this.indicator3.Size = new System.Drawing.Size(130, 22);
            this.indicator3.TabIndex = 16;
            this.indicator3.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // indicator2
            // 
            this.indicator2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.indicator2.Location = new System.Drawing.Point(8, 456);
            this.indicator2.Name = "indicator2";
            this.indicator2.Size = new System.Drawing.Size(130, 22);
            this.indicator2.TabIndex = 15;
            this.indicator2.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // indicator1
            // 
            this.indicator1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.indicator1.Location = new System.Drawing.Point(8, 432);
            this.indicator1.Name = "indicator1";
            this.indicator1.Size = new System.Drawing.Size(130, 22);
            this.indicator1.TabIndex = 14;
            this.indicator1.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // priceBand
            // 
            this.priceBand.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.priceBand.Location = new System.Drawing.Point(8, 320);
            this.priceBand.Name = "priceBand";
            this.priceBand.Size = new System.Drawing.Size(130, 22);
            this.priceBand.TabIndex = 9;
            this.priceBand.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // chartType
            // 
            this.chartType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.chartType.Location = new System.Drawing.Point(8, 276);
            this.chartType.Name = "chartType";
            this.chartType.Size = new System.Drawing.Size(130, 22);
            this.chartType.TabIndex = 8;
            this.chartType.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // indicatorLabel
            // 
            this.indicatorLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.indicatorLabel.Location = new System.Drawing.Point(8, 416);
            this.indicatorLabel.Name = "indicatorLabel";
            this.indicatorLabel.Size = new System.Drawing.Size(128, 16);
            this.indicatorLabel.TabIndex = 13;
            this.indicatorLabel.Text = "Technical Indicators";
            // 
            // movAvgLabel
            // 
            this.movAvgLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.movAvgLabel.Location = new System.Drawing.Point(8, 348);
            this.movAvgLabel.Name = "movAvgLabel";
            this.movAvgLabel.Size = new System.Drawing.Size(100, 16);
            this.movAvgLabel.TabIndex = 12;
            this.movAvgLabel.Text = "Moving Averages";
            // 
            // priceBandLabel
            // 
            this.priceBandLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.priceBandLabel.Location = new System.Drawing.Point(8, 304);
            this.priceBandLabel.Name = "priceBandLabel";
            this.priceBandLabel.Size = new System.Drawing.Size(100, 16);
            this.priceBandLabel.TabIndex = 11;
            this.priceBandLabel.Text = "Price Band";
            // 
            // chartTypeLabel
            // 
            this.chartTypeLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chartTypeLabel.Location = new System.Drawing.Point(8, 260);
            this.chartTypeLabel.Name = "chartTypeLabel";
            this.chartTypeLabel.Size = new System.Drawing.Size(100, 16);
            this.chartTypeLabel.TabIndex = 10;
            this.chartTypeLabel.Text = "Chart Type";
            // 
            // logScale
            // 
            this.logScale.Location = new System.Drawing.Point(8, 216);
            this.logScale.Name = "logScale";
            this.logScale.Size = new System.Drawing.Size(128, 20);
            this.logScale.TabIndex = 6;
            this.logScale.Text = "Log Scale";
            this.logScale.CheckedChanged += new System.EventHandler(this.selectionChanged);
            // 
            // volumeBars
            // 
            this.volumeBars.Checked = true;
            this.volumeBars.CheckState = System.Windows.Forms.CheckState.Checked;
            this.volumeBars.Location = new System.Drawing.Point(8, 176);
            this.volumeBars.Name = "volumeBars";
            this.volumeBars.Size = new System.Drawing.Size(128, 20);
            this.volumeBars.TabIndex = 4;
            this.volumeBars.Text = "Show Volume Bars";
            this.volumeBars.CheckedChanged += new System.EventHandler(this.selectionChanged);
            // 
            // chartSize
            // 
            this.chartSize.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.chartSize.Location = new System.Drawing.Point(8, 148);
            this.chartSize.Name = "chartSize";
            this.chartSize.Size = new System.Drawing.Size(130, 22);
            this.chartSize.TabIndex = 3;
            this.chartSize.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // chartSizeLabel
            // 
            this.chartSizeLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chartSizeLabel.Location = new System.Drawing.Point(8, 132);
            this.chartSizeLabel.Name = "chartSizeLabel";
            this.chartSizeLabel.Size = new System.Drawing.Size(100, 16);
            this.chartSizeLabel.TabIndex = 2;
            this.chartSizeLabel.Text = "Chart Size";
            // 
            // timeRange
            // 
            this.timeRange.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.timeRange.Location = new System.Drawing.Point(8, 104);
            this.timeRange.MaxDropDownItems = 20;
            this.timeRange.Name = "timeRange";
            this.timeRange.Size = new System.Drawing.Size(130, 22);
            this.timeRange.TabIndex = 2;
            this.timeRange.SelectedIndexChanged += new System.EventHandler(this.selectionChanged);
            // 
            // timePeriodLabel
            // 
            this.timePeriodLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.timePeriodLabel.Location = new System.Drawing.Point(8, 88);
            this.timePeriodLabel.Name = "timePeriodLabel";
            this.timePeriodLabel.Size = new System.Drawing.Size(100, 16);
            this.timePeriodLabel.TabIndex = 0;
            this.timePeriodLabel.Text = "Time Period";
            // 
            // topLabel
            // 
            this.topLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(136)))));
            this.topLabel.Dock = System.Windows.Forms.DockStyle.Top;
            this.topLabel.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.topLabel.ForeColor = System.Drawing.Color.Yellow;
            this.topLabel.Location = new System.Drawing.Point(0, 0);
            this.topLabel.Name = "topLabel";
            this.topLabel.Size = new System.Drawing.Size(952, 24);
            this.topLabel.TabIndex = 5;
            this.topLabel.Text = "Advanced Software Engineering";
            this.topLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // FrmFinanceDemo
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.ClientSize = new System.Drawing.Size(952, 562);
            this.Controls.Add(this.rightPanel);
            this.Controls.Add(this.leftPanel);
            this.Controls.Add(this.topLabel);
            this.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "FrmFinanceDemo";
            this.Text = "ChartDirector Financial Chart Demonstration";
            this.Load += new System.EventHandler(this.FrmFinanceDemo_Load);
            this.rightPanel.ResumeLayout(false);
            this.rightPanel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).EndInit();
            this.leftPanel.ResumeLayout(false);
            this.leftPanel.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel rightPanel;
        private ChartDirector.WinChartViewer winChartViewer1;
        private System.Windows.Forms.Panel leftPanel;
        private System.Windows.Forms.TextBox compareWith;
        private System.Windows.Forms.Label compareWithLabel;
        private System.Windows.Forms.TextBox tickerSymbol;
        private System.Windows.Forms.CheckBox percentageScale;
        private System.Windows.Forms.CheckBox parabolicSAR;
        private System.Windows.Forms.Label separator;
        private System.Windows.Forms.Label tickerSymbolLabel;
        private System.Windows.Forms.TextBox movAvg2;
        private System.Windows.Forms.ComboBox avgType2;
        private System.Windows.Forms.TextBox movAvg1;
        private System.Windows.Forms.ComboBox avgType1;
        private System.Windows.Forms.ComboBox indicator4;
        private System.Windows.Forms.ComboBox indicator3;
        private System.Windows.Forms.ComboBox indicator2;
        private System.Windows.Forms.ComboBox indicator1;
        private System.Windows.Forms.ComboBox priceBand;
        private System.Windows.Forms.ComboBox chartType;
        private System.Windows.Forms.Label indicatorLabel;
        private System.Windows.Forms.Label movAvgLabel;
        private System.Windows.Forms.Label priceBandLabel;
        private System.Windows.Forms.Label chartTypeLabel;
        private System.Windows.Forms.CheckBox logScale;
        private System.Windows.Forms.CheckBox volumeBars;
        private System.Windows.Forms.ComboBox chartSize;
        private System.Windows.Forms.Label chartSizeLabel;
        private System.Windows.Forms.ComboBox timeRange;
        private System.Windows.Forms.Label timePeriodLabel;
        private System.Windows.Forms.Label topLabel;
        private System.Windows.Forms.HScrollBar hScrollBar1;
        private System.Windows.Forms.RadioButton pointerPB;
        private System.Windows.Forms.RadioButton zoomInPB;
        private System.Windows.Forms.RadioButton zoomOutPB;
        private System.Windows.Forms.TextBox txtmaxDsplay;

    }
}
frmfinancedemo.resx
frmfinancedemo.resx

10.42 Kb

  Re: zoom function according to no of candle
Posted by Peter Kwan on Oct-31-2015 05:19
Attachments:
Hi Nidhi,

There are several issues with the code. I have quickly done some modification so fix the
issues. As I have only worked on your code for a short time, there may still be issues, and
you may need to debug it.

First, the data are not loaded correctly. The loadData is designed to be executed once
during initiation. However, your code calls loadData many times, causing the data structure
to become inconsistent.

Another issue is that the scale is inconsistent. Your code sets the viewport ratios based on
the number of candlesticks. But the full range of the viewport is defined based on
date/time, and in your charting code, the viewport is interpreted as date/time. In a
FinanceChart, the candlestick ratio is not the same as the date/time ratio, so the ratio is
not accurate.

Regards
Peter Kwan
frmfinancedemo.cs
frmfinancedemo.cs

61.66 Kb

  Re: zoom function according to no of candle
Posted by Nidhi on Nov-02-2015 19:56
Thanks a lot.

Initially code works perfect according to no of candles.

But now I want zoom in and zoom out only for 10 candles per click.

Please help me for the same.

  Re: zoom function according to no of candle
Posted by Peter Kwan on Nov-03-2015 01:14
Hi Nidhi,

May be your code can just increase or decrease txtmaxDsplay by 10, then redraw the chart
with the updated txtmaxDsplay.

Regards
Peter Kwan