using C1.Chart;
using C1.Chart.Annotation;
using C1.Win.Chart.Annotation;
using C1.Win.Chart.Finance;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StockChart
{
    public partial class frmMain : Form
    {
        private const string _comparisonBinding = "percentage";
        private readonly Color _baseSeriesColor = Color.FromArgb(255, 165, 0);

        private string _symbol = "MSFT";
        private string _binding = "close";
        private QuoteData _quoteData = null;
        ComparisonSymbols _comparisonSymbols;


        private QuoteData _IXICData = null;

        C1.Win.Chart.Interaction.RangeSelector rs;
        C1.Win.Chart.Interaction.LineMarker marker;
        AnnotationLayer annotationLayer;

        SolidBrush axisRectSB = new SolidBrush(Color.FromArgb(255, 42, 42, 42));
        SolidBrush axisFontSB = new SolidBrush(Color.FromArgb(255, 170, 170, 170));
        Font axisFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 9, FontStyle.Regular);

        public string Binding
        {
            get { return _binding; }
            set { _binding = value; }
        }

        private string Symbol
        {
            get { return _symbol; }
            set { this._symbol = value; if (this.Created) this.BeginInvoke(new Action(() => { ucTitlebar.StockName = DataService.Instance.GetSymbolName(this._symbol); })); }
        }

        MovingAverage ma;
        C1.Win.Chart.Series fs;
        C1.Win.Chart.Series vs;
        C1.Win.Chart.Series cs;
        public frmMain()
        {
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            InitializeComponent();

            this.Disposed += (o, e) =>
            {
                if (marker != null)
                {
                    marker.Remove();
                }
            };
            _quoteData = DataService.Instance.GetSymbolData(Symbol, new Action<string>((s) =>
            {
                System.Windows.Forms.MessageBox.Show(this, s);
            }));

            _IXICData = DataService.Instance.GetSymbolData("^IXIC", new Action<string>((s) =>
            {
                System.Windows.Forms.MessageBox.Show(this, s);
            }));

            if (_quoteData.Any())
            {
                ucTitlebar.StockName = DataService.Instance.GetSymbolName(this._symbol);
                ucTitlebar.Price = _quoteData.Last().close;
                ucTitlebar.Difference = _quoteData[Math.Max(_quoteData.Count - 1, 0)].close - _quoteData[Math.Max(_quoteData.Count - 2, 0)].close;
            }

            InitializeChart();
            InitializeControls();
            //SetupAnnotations();
        }

        private void InitializeChart()
        {
            if (_quoteData == null || !_quoteData.Any())
            {
                return;
            }
            var maxVolume = _quoteData.Max(p => p.volume);

            HsbColor hsb = ColorEx.RgbToHsb(_baseSeriesColor);

            financialChart1.BeginUpdate();
            financialChart1.BindingX = "date";
            financialChart1.ToolTip.Active = false;
            financialChart1.AxisY.Position = Position.Right;
            financialChart1.AxisY.MajorGrid = false;
            financialChart1.AxisY.MinorGrid = false;
            financialChart1.AxisY.Format = null;
            financialChart1.Legend.Position = Position.None;

            ma = new MovingAverage()
            {
                Binding = Binding,
                Type = MovingAverageType.Simple,
                Period = 10,
            };
            ma.Style.StrokeWidth = 1;
            ma.Style.FillColor = ma.Style.StrokeColor
                = ColorEx.HsbToRgb(new HsbColor() { A = hsb.A, H = hsb.H, S = Math.Max(hsb.B / 2, 0), B = Math.Min(hsb.B * 2, 1) });
            financialChart1.Series.Add(ma);

            fs = new C1.Win.Chart.Series() { Binding = Binding, Name = _symbol.ToUpper() };
            fs.ChartType = ChartType.Line;
            fs.Style.StrokeWidth = 2;
            fs.Style.FillColor = Color.FromArgb(64, _baseSeriesColor);
            fs.Style.StrokeColor = _baseSeriesColor;
            financialChart1.Series.Add(fs);

            vs = new C1.Win.Chart.Series() { Binding = "volume", AxisY = new C1.Win.Chart.Axis() { Max = maxVolume * 8 }, ChartType = C1.Chart.ChartType.Column };
            vs.Style.FillColor = Color.FromArgb(255, 165, 0);
            vs.Style.StrokeColor = Color.FromArgb(255, 165, 0);
            financialChart1.Series.Add(vs);

            financialChart1.ChartType = C1.Chart.Finance.FinancialChartType.Line;
            financialChart1.DataSource = _quoteData;
            financialChart1.Stacking = Stacking.None;
            financialChart1.EndUpdate();

            financialChart2.BeginUpdate();
            financialChart2.BindingX = "date";
            financialChart2.Binding = "close";
            financialChart2.AxisY.Position = Position.None;
            cs = new FinancialSeries();
            cs.Style.StrokeWidth = 2;
            cs.Style.FillColor = Color.FromArgb(255, 165, 0);
            cs.Style.StrokeColor = Color.FromArgb(255, 165, 0);
            financialChart2.Series.Add(cs);
            financialChart2.ChartType = C1.Chart.Finance.FinancialChartType.Line;
            financialChart2.DataSource = _IXICData;
            financialChart2.ToolTip.Content = null;
            financialChart2.AxisX.Min = new DateTime(2007, 12, 31, 0, 0, 0).ToOADate();
            financialChart2.EndUpdate();

            financialChart1.Rendered += financialChart1_Rendered;
            financialChart1.MouseMove += FinancialChart1_MouseMove;
            financialChart2.Rendered += financialChart2_Rendered;
        }

        private void FinancialChart1_MouseMove(object sender, MouseEventArgs e)
        {
            var ht = financialChart1.HitTest(e.Location);
            if (ht != null)
            {
                var result = new StringBuilder();
                if (ht.PointIndex >= 0)
                {
                    DateTime currDate = DateTime.MaxValue;
                    if (ht.Series != null && ht.Item != null)
                    {
                        currDate = Convert.ToDateTime(ht.Item.GetRefValue("date"));
                    }
                    if (ht.Series is MovingAverage)
                    {
                        currDate = currDate.AddDays(0-(ht.Series as MovingAverage).Period);
                    }

                    if (currDate == DateTime.MaxValue)
                    {
                        return;
                    }

                    Stack<QuoteInfo> quotes = new Stack<QuoteInfo>();

                    if(_quoteData != null)
                    {
                        result.Append(string.Format("{0}: ", _symbol));
                        var quote = (from p in _quoteData where (p.date >= currDate) select p).FirstOrDefault();
                         
                        if (quote != null)
                        {
                            double dd = quote.GetValue(this.Binding);

                            quotes.Push(new QuoteInfo()
                            {
                                Symbol = _symbol,
                                Color = _baseSeriesColor,
                                Value = dd,
                                Volume = Convert.ToInt32(quote.GetRefValue("volume")),
                                Date = Convert.ToDateTime(quote.GetRefValue("date"))
                        });
                        }
                    }

                    if (_comparisonSymbols != null)
                    {
                        foreach (var series in financialChart1.Series)
                        {
                            if (series.Visibility == SeriesVisibility.Visible && !(series is MovingAverage) && !string.IsNullOrEmpty(series.Name))
                            {
                                var currSeries = (from p in (from kv in _comparisonSymbols.Values select kv) where p.Series == series select p).FirstOrDefault();

                                if (currSeries != null)
                                {

                                    var quote = (from p in currSeries.DataSource where (p.date >= currDate) select p).FirstOrDefault();
                                    
                                    if (quote != null)
                                    {
                                        System.Diagnostics.Debug.WriteLine(currDate.ToShortDateString());
                                        double dd = quote.GetValue(this.Binding);

                                        quotes.Push(new QuoteInfo()
                                        {
                                            Symbol = currSeries.Code,
                                            Color = currSeries.Color,
                                            Value = dd,
                                            Volume = Convert.ToInt32(quote.GetRefValue("volume")),
                                            Date = Convert.ToDateTime(quote.GetRefValue("date"))
                                        });
                                    }
                                }
                            }
                                
                        }
                    }
                    ucToolbar.QuotesInfoDisplayMode = this.Binding == _comparisonBinding ? DisplayMode.Comparison : DisplayMode.Independent;
                    
                    ucToolbar.QuotesInfo = quotes;
                }

            }
        }

        private void UpdateChart()
        {
            financialChart1.BeginUpdate();
            fs.Name = _symbol;
            financialChart1.DataSource = _quoteData;
            UpdateDataRange();
            financialChart1.EndUpdate();
        }

        private void InitializeControls()
        {
            ucTitlebar.OnSymbolChanged += (o, e) =>
            {
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((oo) =>
                {
                    var symbolData = DataService.Instance.GetSymbolData(e.Value, (s) =>
                        {
                            this.BeginInvoke(new Action(() =>
                            {
                                System.Windows.Forms.MessageBox.Show(this, s);
                            }));
                            return;
                        });
                        if (symbolData.Any())
                        {
                            _quoteData = symbolData;
                            Symbol = e.Value.ToUpper();
                            ucTitlebar.Price = _quoteData.Last().close;
                            ucTitlebar.Difference = _quoteData[Math.Max(_quoteData.Count - 1, 0)].close - _quoteData[Math.Max(_quoteData.Count - 2, 0)].close;
                            this.BeginInvoke(new Action(() =>
                            {
                                UpdateChart();
                                SetupAnnotations(ucToolbar.IsShowNews);
                            }));
                        }
                }));
            };

            ucToolbar.OnComparisonChanged += (o, e) =>
            {
                if (_comparisonSymbols == null)
                {
                    _comparisonSymbols = new ComparisonSymbols(financialChart1);
                }

                if (e.Value.ToUpper() == _symbol.ToUpper())
                {
                    return;
                }

                _comparisonSymbols.CreateSysmbol(e.Value, (s) => {
                    if (_comparisonSymbols.Add(s, _comparisonBinding, ucToolbar.IsShowMovingAverage))
                    {
                        ChangeMode(true);

                        ucToolbar.AddSeriesController(s, () =>
                        {
                            if(s.Visibility == SeriesVisibility.Visible)
                                s.MovingAverage.Visibility = ucToolbar.IsShowMovingAverage ? SeriesVisibility.Visible : SeriesVisibility.Hidden;
                            var checkedSymbol = from p in _comparisonSymbols where p.Value.Visibility == SeriesVisibility.Visible select p;
                            if (checkedSymbol == null || !checkedSymbol.Any())
                            {
                                ChangeMode(false);
                            }
                            else
                            {
                                ChangeMode(true);
                            }
                            UpdateYRange();
                        });

                        if (_comparisonSymbols.Keys.Count > 4)
                        {
                            var key = ucToolbar.GetFirstSeriesCOntroller();
                            var value = _comparisonSymbols[key];
                            ucToolbar.RemoveSeriesController(value);
                            _comparisonSymbols.Remove(value);
                        }
                        UpdateDataRange();
                    }

                });
            };

            ucToolbar.OnSelectedIndexChanged += (o, e) =>
            {
                if (rs == null)
                {
                    return;
                }
                DateTime lowValue = DateTime.Now;
                switch (e.Value)
                {
                    case 0:
                        lowValue = DateTime.Now.AddMonths(-1);
                        break;
                    case 1:
                        lowValue = DateTime.Now.AddMonths(-3);
                        break;
                    case 2:
                        lowValue = DateTime.Now.AddMonths(-6);
                        break;
                    case 3:
                        lowValue = DateTime.Parse(string.Format("01-01-{0}", DateTime.Now.Year));
                        break;
                    case 4:
                        lowValue = DateTime.Now.AddYears(-1);
                        break;
                    case 5:
                        lowValue = DateTime.Now.AddYears(-3);
                        break;
                    case 6:
                        lowValue = DateTime.Now.AddYears(-6);
                        break;
                    case 7:
                        lowValue = _quoteData.Min(p => p.date);
                        break;
                    default:
                        break;
                }
                rs.UpperValue = DateTime.Now.ToOADate();
                rs.LowerValue = lowValue.ToOADate();

                ucToolbar.RangeText = lowValue.ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture) + 
                " - " + DateTime.Now.ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture);
            };

            ucToolbar.OnReseted += (o, e) =>
            {
                if (_comparisonSymbols != null && _comparisonSymbols.Any())
                {
                    _comparisonSymbols.Clear();


                    ChangeMode(false);

                    UpdateYRange();
                    ucToolbar.RemoveAllSeriesController();
                    var  removeItems = (from p in financialChart1.Series where p != fs && p != ma && p != vs select p).ToList();

                    for (int i = 0; i < removeItems.Count(); i++)
                    {
                        financialChart1.Series.Remove(removeItems[i]);
                    }

                }
            };

            ucToolbar.OnShowVolumeChanged += (o, e) =>
            {
                if (vs != null)
                {
                    vs.Visibility = e.Value ? SeriesVisibility.Visible : SeriesVisibility.Hidden;
                }
            };

            ucToolbar.OnChartTypeChanged += (o, e) =>
            {
                if (fs == null)
                {
                    return;
                }

                financialChart1.BeginUpdate();
                switch (e.Type)
                {
                    case ChartType.Line:
                    case ChartType.Area:
                        fs.Style.FillColor = Color.FromArgb(64, _baseSeriesColor);
                        fs.Binding = Binding;
                        break;
                    case ChartType.Candlestick:
                        fs.Style.FillColor = Color.FromArgb(255, _baseSeriesColor);
                        fs.Binding = "high,low,open,close";
                        break;
                    case ChartType.HighLowOpenClose:
                    default:
                        fs.Style.FillColor = Color.FromArgb(64, _baseSeriesColor);
                        fs.Binding = "high,low,open,close";
                        break;
                }
                fs.ChartType = e.Type;
                financialChart1.EndUpdate();
            };

            ucToolbar.OnSaveImage += (o, e) =>
            {
                string filter = string.Empty;
                C1.Win.Chart.ImageFormat format = C1.Win.Chart.ImageFormat.Png;
                switch (e.Value)
                {
                    case "PNG":
                        filter = "PNG|*.png";
                        format = C1.Win.Chart.ImageFormat.Png;
                        break;
                    case "JPG":
                        filter = "JPG|*.jpg";
                        format = C1.Win.Chart.ImageFormat.Jpg;
                        break;
                    case "SVG":
                        filter = "SVG|*.svg";
                        format = C1.Win.Chart.ImageFormat.Svg;
                        break;
                    default:
                        filter = "PNG|*.png";
                        format = C1.Win.Chart.ImageFormat.Png;
                        break;
                }

                using (SaveFileDialog dialog = new SaveFileDialog())
                {
                    dialog.Filter = filter;
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                       string path = dialog.FileName;
                        using (System.IO.FileStream fs = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
                        {
                            financialChart1.SaveImage(fs, format, financialChart1.Width, financialChart1.Height);
                        }
                    }
                }
            };

            ucToolbar.OnMovingAverageVisibilityChanged += (o, e) =>
            {
                if (ma != null)
                {
                    ma.Visibility = e.Value ? SeriesVisibility.Visible : SeriesVisibility.Hidden;
                    if (_comparisonSymbols != null)
                        foreach (var kv in _comparisonSymbols)
                        {
                            kv.Value.MovingAverage.Visibility = ma.Visibility;
                        }
                }
            };

            ucToolbar.OnMovingAverageTypeChanged += (o, e) =>
            {
                if (ma != null)
                {
                    ma.Type = e.Type;
                    if (_comparisonSymbols != null)
                    {
                        _comparisonSymbols.Type = e.Type;
                    }
                }
            };

            ucToolbar.OnMovingAveragePeriodChanged += (o, e) =>
            {
                if (ma != null)
                {
                    ma.Period = e.Value;
                    if (_comparisonSymbols != null)
                    {
                        _comparisonSymbols.Period = e.Value;
                    }
                }
            };

            ucToolbar.OnLineMarkerVisibilityChanged += (o, e) =>
            {
                if (marker != null)
                {
                    marker.Visible = e.Value;
                }
            };

            ucToolbar.OnNewsVisibilityChanged += (o, e) =>
            {
                SetupAnnotations(e.Value);
            };
        }

        private bool _isConfrontation = false;
        private void ChangeMode(bool isConfrontation)
        {

            if (_isConfrontation == isConfrontation)
            {
                return;
            }

            ucToolbar.ShowChartType = !isConfrontation;
            ucToolbar.EnableReset = isConfrontation;
            ucToolbar.IsShowNews = !isConfrontation;

            if (isConfrontation)
            {
                Binding = fs.Binding = ma.Binding = "percentage";
                financialChart1.AxisY.Format = "P0";
            }
            else
            {

                Binding = fs.Binding = ma.Binding = "close";
                financialChart1.AxisY.Format = null;
            }
            _isConfrontation = isConfrontation;
            fs.Rebind();
            ma.Rebind();
            this.BeginInvoke(new Action(() =>
            {
                SetupAnnotations(!isConfrontation && ucToolbar.IsNewsChecked);
            }));
        }

        private void SetupAnnotations(bool isShown = true)
        {
            if (annotationLayer == null)
            {
                annotationLayer = new AnnotationLayer(financialChart1);
            }
            else
            {
                annotationLayer.Annotations.Clear();
            }

            if (!isShown)
            {
                return;
            }
            SetupAnnotation(_quoteData);
        }
        
        void SetupAnnotation(IEnumerable<Quote> dataSource)
        {
            var cache = new Queue<Square>();


            foreach (var d in dataSource)
            {
                if (!string.IsNullOrEmpty(d.events))
                {
                    var dSquare = new Square("N", 20)
                    {
                        SeriesIndex = 0,
                        Location = new PointF((float)d.date.ToOADate(), (float)d.GetValue(Binding)),
                        Attachment = AnnotationAttachment.DataCoordinate,
                        TooltipText = d.events,
                    };
                    dSquare.ContentStyle.StrokeColor = Color.Black;
                    dSquare.ContentStyle.Font = new System.Drawing.Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
                    dSquare.Style.FillColor = Color.FromArgb(136, 136, 136);
                    dSquare.Style.StrokeColor = Color.Black;
                    dSquare.Style.StrokeWidth = 1;
                    annotationLayer.Annotations.Add(dSquare);

                    cache.Enqueue(dSquare);
                }
            }
        }

        void financialChart1_Rendered(object sender, C1.Win.Chart.RenderEventArgs e)
        {
            if (marker == null)
            {
                marker = new C1.Win.Chart.Interaction.LineMarker(financialChart1);
                marker.Lines = C1.Win.Chart.Interaction.LineMarkerLines.Both;
                marker.Visible = ucToolbar.IsLineMarkerChecked;
                marker.LineWidth = 1;
                marker.DragThreshold = 10;
                marker.Paint += lineMarker_Paint;
            }
        }

        void lineMarker_Paint(object sender, PaintEventArgs e)
        {
            var chartPoint = new Point(marker.X, marker.Y);
            var _hitTestInfo = financialChart1.HitTest(chartPoint, C1.Chart.MeasureOption.X);
            
            var hitTestInfo = financialChart1.HitTest(chartPoint);

            var isLeft = marker.X > financialChart1.PlotRect.Width / 2;

            //draw X rectangle
            var xRect = new System.Drawing.Rectangle(marker.X - 60, (int)(financialChart1.PlotRect.Top + financialChart1.PlotRect.Height), 120, 25);

            e.Graphics.FillRectangle(axisRectSB, xRect);
            var text = hitTestInfo.Format("{x:dd-MM-yyyy}");
            SizeF fontSize = e.Graphics.MeasureString(text, axisFont);
            e.Graphics.DrawString(text, axisFont, axisFontSB, xRect.X + (120 - fontSize.Width) / 2, xRect.Y + (25 - fontSize.Height) / 2);


            var value = financialChart1.AxisY.ActualMin + (financialChart1.AxisY.ActualMax - financialChart1.AxisY.ActualMin) * (financialChart1.PlotRect.Top + financialChart1.PlotRect.Height - marker.Y) / financialChart1.PlotRect.Height;

            //draw Y rectangle

            var format = string.Format((value >= 0 ? "+{0:P2}" : "{0:P2}"), value);
            if (value == 0)
            {
                format = "{0:P2}";
            }
            text = string.Format(_isConfrontation ? format : "{0:.##}", value);

            if (isLeft)
            {
                var yRect = new System.Drawing.Rectangle((int)(financialChart1.PlotRect.Left), marker.Y - 25 / 2, 60, 25);
                e.Graphics.FillRectangle(axisRectSB, yRect);
                fontSize = e.Graphics.MeasureString(text, axisFont);
                e.Graphics.DrawString(text, axisFont, axisFontSB, yRect.X + (60 - fontSize.Width) / 2, yRect.Y + (25 - fontSize.Height) / 2);
            }
            else
            {
                var yRect = new System.Drawing.Rectangle((int)(financialChart1.PlotRect.Right - 60), marker.Y - 25 / 2, 60, 25);
                e.Graphics.FillRectangle(axisRectSB, yRect);
                fontSize = e.Graphics.MeasureString(text, axisFont);
                e.Graphics.DrawString(text, axisFont, axisFontSB, yRect.X + (60 - fontSize.Width) / 2, yRect.Y + (25 - fontSize.Height) / 2);
            }
        }
        void financialChart2_Rendered(object sender, C1.Win.Chart.RenderEventArgs e)
        {
            RefrushRangeSelector();
        }

        void RefrushRangeSelector()
        {

            if (rs == null && financialChart2.AxisX.ActualMin != financialChart2.AxisX.ActualMax)
            {
                rs = new C1.Win.Chart.Interaction.RangeSelector(financialChart2);
                rs.Styles.BarStyle.SelectedAreaColor = Color.FromArgb(80, 189, 189, 189);
                rs.ValueChanged += rs_ValueChanged;

                var lowValue = DateTime.Parse(string.Format("01-01-{0}", DateTime.Now.Year));
                rs.LowerValue = lowValue.ToOADate();
                rs.UpperValue = DateTime.Now.ToOADate();
                ucToolbar.RangeText = lowValue.ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture)
                    + " - " + DateTime.Now.ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture);
            }
        }

        void rs_ValueChanged(object sender, EventArgs e)
        {
            UpdateDataRange();
            ucToolbar.RangeText =DateTime.FromOADate(rs.LowerValue).ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture)
                   + " - " + DateTime.FromOADate(rs.UpperValue).ToString("MMM dd, yyyy", System.Threading.Thread.CurrentThread.CurrentCulture);
        }

        void UpdateDataRange()
        {

            DateTime ds = DateTime.FromOADate(rs.LowerValue);
            Quote quote = _quoteData.FirstOrDefault(p => p.date >= ds);
            if (quote == null)
            {
                return;
            }

            financialChart1.BeginUpdate();
            _quoteData.ReferenceValue.Value = quote.close;


            if (_comparisonSymbols != null)
            {
                foreach (var kv in _comparisonSymbols)
                {
                    quote = kv.Value.DataSource.FirstOrDefault(p => p.date >= ds);
                    if (quote != null)
                    {
                        kv.Value.DataSource.ReferenceValue.Value = quote.close;
                        kv.Value.Series.Rebind();
                        kv.Value.MovingAverage.Rebind();
                    }
                }
            }

            fs.Rebind();
            ma.Rebind();
            UpdateYRange();
            financialChart1.EndUpdate();
        }

        
        void UpdateYRange()
        {
            IEnumerable<QuoteRange> ranges = (new QuoteRange[] { DataService.Instance.GetSymbolYRange(_quoteData, rs.LowerValue, rs.UpperValue, Binding) });

            if (_comparisonSymbols != null)
            {
                var cssRange = from cs in _comparisonSymbols where cs.Value.Visibility == SeriesVisibility.Visible select DataService.Instance.GetSymbolYRange(cs.Value.DataSource, rs.LowerValue, rs.UpperValue, Binding);
                ranges = ranges.Union(cssRange);
            }
            if (ranges.Any())
            {
                financialChart1.AxisX.Min = rs.LowerValue;
                financialChart1.AxisX.Max = rs.UpperValue;
                financialChart1.AxisY.Min = ranges.Min(p => { return p == null ? int.MaxValue : p.PriceMin; });
                financialChart1.AxisY.Max = ranges.Max(p => { return p == null ? int.MinValue : p.PriceMax; });
                if (ranges.First() != null)
                {
                    vs.AxisY.Min = ranges.First().VolumeMin;
                    vs.AxisY.Max = ranges.First().VolumeMax * 12;
                }
            }
        }
    }
}
