예제 #1
0
        public static void TestGraph(this AbstractIndicator ind, string filename, int length)
        {
            Quantum q = Quantum.ExcelToQuantum(filename, "symbol", 0);

            var           dz    = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, q.Data.Count);
            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add(ind.ToString());
            foreach (var indicator in ind.SubIndicators)
            {
                names.Add(indicator.Key);
            }

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 400, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 200, YPosition = 1
            };
            for (int i = 2; i < chartOptions.Length; i++)
            {
                chartOptions[i] = new ChartOption()
                {
                    Height = 0, YPosition = 1, Layover = true
                }
            }
            ;

            int counter = 0;

            foreach (Tick tick in q)
            {
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;

                dz[4, counter] = ind.HandleNextTick(tick);

                int icounter = 5;
                foreach (var subind in ind.SubIndicators.Values)
                {
                    dz[icounter, counter] = subind[0];
                    icounter++;
                }

                counter++;
            }


            Visualize.GenerateMultiPaneGraph(names.ToArray(), q.Data.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html",
                                             chartOptions);

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
예제 #2
0
        public ChartOption CreateChartOptions()
        {
            var option = new ChartOption
            {
                ShowScale                = true,
                ScaleLabel               = "<%=value%>",
                ScaleShowGridLines       = true,
                ScaleGridLineColor       = "rgba(0,0,0,0,0.05)",
                ScaleGridLineWidth       = 1,
                ScaleShowHorizontalLines = true,
                ScaleShowVerticalLines   = true,
                BezierCurve              = true,
                BezierCurveTension       = 0.4F,
                PointDot                = true,
                PointDotRadius          = 4,
                PointDotStrokeWidth     = 1,
                PointHitDetectionRadius = 20,
                DatasetStroke           = true,
                DatasetStrokeWidth      = 2,
                DatasetFill             = false,
                LegendTemplate          = "<ul class=\"chartLegend\"><% for (var i=0; i<datasets.length; i++){%><li><span><div class=\"legendColor\" style=\"background-color:<%=datasets[i].fillColor%>\"></div><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>",
                TooltipTemplate         = "<%if (label){%><%=label%>: <%}%><%= value %>",
                MultiTooltipTemplate    = "<%=datasetLabel%> : <%= value %>"
            };

            return(option);
        }
예제 #3
0
        public ChartOption GetCHART(WIPProfileInput input)
        {
            var summaryData  = _HoldLotInfoRepository.QueryCWIP(input);
            var percentData1 = _HoldLotInfoRepository.QueryMOVE(input);
            var percentData2 = _HoldLotInfoRepository.QueryHoldWIP(input);
            var percentData3 = _HoldLotInfoRepository.QueryRunWIP(input);
            var percentData4 = _HoldLotInfoRepository.QueryQueueWIP(input);

            string chartTitle = "WIPProfile Chart";

            string firstAxisName  = "MOVE QTY";
            string secondAxisName = "WIP";

            ChartOption optionSummary  = percentData1.ToChartOption(ChartType.Line, chartTitle, "", "name", "Series", "value", "", ChartDirection.Vertical, "", firstAxisName);
            ChartOption addtionOption  = summaryData.AddToChartOption(optionSummary, ChartType.Line, "name", "Series", "value", "", "", firstAxisName);
            ChartOption addtionOption1 = percentData2.AddToChartOption(optionSummary, ChartType.Bar, "name", "Series", "value", "", "", secondAxisName);
            ChartOption addtionOption2 = percentData3.AddToChartOption(optionSummary, ChartType.Bar, "name", "Series", "value", "", "", secondAxisName);
            ChartOption addtionOption3 = percentData4.AddToChartOption(optionSummary, ChartType.Bar, "name", "Series", "value", "", "", secondAxisName);

            addtionOption1.xAxis[0].axisLabel = new AxisLabel()
            {
                interval = 0
            };
            addtionOption1.title.x = "left";

            return(addtionOption1);
        }
        // GET: ReceiptsChart
        public ActionResult ReceiptsChart()
        {
            // Fill Chart Data ------------------------------------------
            #region Chart Data

            var api  = new ReportsApiController();
            var data = api.GetInvoiceRemainChart().ToList();

            var opt = new ChartOption()
            {
                Name      = "receiptsChart",
                ChartType = ChartTypes.Column,
                //XAxisData = chartCategories,
                YAxisData = new Data(data.Select(x => new Point()
                {
                    Id = x.id.ToString(), Name = x.name, Y = x.y
                }).ToArray()),
                Tilte          = "گزارش جمعی رسیدی ها به تفکیک متصدی ها",
                YAxisTitle     = "جمع ریالی",
                SeriesName     = "پرسنل",
                ShowLegend     = false,
                ShowDataLabels = true,
                SubTitle       = $"مبلغ کل رسیدی دفتر: {data.Sum(x => (long)x.y).ToString("N0", CultureInfo.GetCultureInfo("fa-IR"))}"
            };

            #endregion
            //----------------------------------------------------------

            return(PartialView("Receipt/ReceiptsChart", HtmlHelperExtensions.GetHighChart(opt)));
        }
예제 #5
0
        //根据文章数,按文章发布时间产生折线图
        public string CreateLine(string key, DataTable dt)
        {
            ChartTitle title = new ChartTitle()
            {
                text = key, subtext = "最近30天"
            };
            ChartOption option = null;

            option = new BarChartOption(title, "", "line");
            string[] days     = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31".Split(',');
            int[]    data_int = new int[days.Length];
            for (int i = 0; i < days.Length; i++)
            {
                data_int[i] = dt.Select("Day=" + (i + 1)).Length;
            }
            List <ChartSeries> seriesList = new List <ChartSeries>()//这里的统计算法不对,需要统计出文章数
            {
                new ChartSeries()
                {
                    name     = "文章数",
                    type     = "line",
                    data_int = data_int
                }
            };

            ((BarChartOption)option).AddData(days, seriesList, "");
            option.tooltip.formatter = null;//使用默认格式
            return(option.ToString());
        }
예제 #6
0
        private ChartOption GetSummaryOption(HoldLotHistoryInput input)
        {
            var summaryData = iHoldLotHistoryRepository.GetHoldLotHistorySummarySync(input);
            var percentData = iHoldLotHistoryRepository.GetHoldLotHistoryPercentSync(input);

            string chartTitle = input.moduleCode;

            if (string.IsNullOrWhiteSpace(input.moduleCode))
            {
                chartTitle = "Fab";
            }

            string firstAxisName  = "lots";
            string secondAxisName = "lots/time";

            if (0 == string.Compare(input.analysisUnit, "wafer"))
            {
                firstAxisName  = "wafers";
                secondAxisName = "wafers/time";
            }
            ChartOption optionSummary = summaryData.ToChartOption(ChartType.Bar, chartTitle, "", "name", "Series", "value", "HoldLotHist", ChartDirection.Vertical, "", firstAxisName);
            ChartOption addtionOption = percentData.AddToChartOption(optionSummary, ChartType.Line, "name", "Series", "value", " ", "", secondAxisName);

            //ChartOption optionSummary = summaryData.ToChartOption(ChartType.Bar, chartTitle, "", "name", "Series", "value", "HoldLotHist", ChartDirection.Horizontal, firstAxisName);
            //ChartOption addtionOption = percentData.AddToChartOption(optionSummary, ChartType.Line, "name", "Series", "value", " ", secondAxisName);
            addtionOption.title.x = "left";
            return(addtionOption);
        }
예제 #7
0
        public ChartOption GetEQPGroupWipMoveChart(EQPGroupPerformanceSubPageInput input)
        {
            input.StartTime = input.StartTime.Replace("-", "").Replace(":", "") + "000";
            input.EndTime   = input.EndTime.Replace("-", "").Replace(":", "") + "000";
            var    WipData     = _Repository.QueryEQPGroupWipInfo(input);
            var    MoveData    = _Repository.QueryEQPGroupMoveInfo(input);
            var    percentData = _Repository.QueryEQPGroupAvailInfo(input);
            string chartTitle  = "EQPGroup WIP & MOVE Chart";

            string firstAxisName  = "Wafer Qty";
            string secondAxisName = "EQP Avail";

            ChartOption optionSummary  = WipData.ToChartOption(ChartType.Bar, chartTitle, "", "name", "Series", "value", "", ChartDirection.Vertical, "", firstAxisName);
            ChartOption addtionOption  = MoveData.AddToChartOption(optionSummary, ChartType.Bar, "name", "Series", "value", "", "", firstAxisName);
            ChartOption addtionOption1 = percentData.AddToChartOption(addtionOption, ChartType.Line, "name", "Series", "value", "", "", secondAxisName);

            addtionOption1.xAxis[0].axisLabel = new AxisLabel()
            {
                interval = 0
            };
            addtionOption1.yAxis[1].axisLabel = new AxisLabel()
            {
                interval = 0
            };
            addtionOption1.title.x = "left";

            return(addtionOption1);
        }
예제 #8
0
        //生成图片数据
        public string BindImgCode(string sitename, JArray jarray)
        {
            ChartOption option = new ChartOption();

            option.title.text    = "站点关系:用户整合";
            option.title.subtext = "数据来自" + sitename;
            option.legend.data   = new string[] { "主站", "子站", "二级子站" };
            option.series.Add(new ChartSeries()
            {
                name       = "站点关系",
                categories = new Categories[] { new Categories("主站"), new Categories("子站"), new Categories("二级子站") },
                nodes      = GetPicData(sitename, jarray),
                links      = GetPicLinks(GetPicData(sitename, jarray), sitename),
                itemStyle  = new SeriesItemStyle()
                {
                    normal = new ChartNormal()
                    {
                        label = new ChartLabel()
                        {
                            textStyle = new TextStyle()
                            {
                                color = "#333"
                            }
                        }
                    }
                }
            });
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            return("option=" + JsonConvert.SerializeObject(option, Formatting.None, setting) + ";");
        }
예제 #9
0
        public PagedResults QueryEmployListSync(Models.QueryEmployInfoInput input)
        {
            var pageResults     = iEmployInfoRepository.GetEmployListSync(input);
            var summaryData     = iEmployInfoRepository.GetEmploySummarySync(input);
            var summaryDataList = iEmployInfoRepository.GetEmploySummaryListSync(input);

            ChartOption optionPie = summaryData.ToChartOption(ChartType.Pie, "", "", "name", "Series", "value", "EmployEE", ChartDirection.Vertical);

            pageResults.ExtraDatas.Add("SummaryPie", optionPie);

            ChartOption optionBar = summaryDataList[0].ToChartOption(ChartType.Bar, "", "", "name", "Series", "value", "EmployEE", ChartDirection.Vertical);

            ChartOption addtionOption;

            for (int i = 1; i < summaryDataList.Length; ++i)
            {
                addtionOption = summaryDataList[i].AddToChartOption(optionBar, ChartType.Line, "name", "Series", "value", " ");
                pageResults.ExtraDatas.Add("SummaryBar", addtionOption);
            }

            ChartOption optionLine = summaryData.ToChartOption(ChartType.Line, "", "", "name", "Series", "value", "EmployEE", ChartDirection.Vertical);

            pageResults.ExtraDatas.Add("SummaryLine", optionLine);

            return(pageResults);
        }
예제 #10
0
 public ChartOptionForm(ChartOption option, int idx = 0)
 {
     OwnedOption = option;
     InitializeComponent();
     OptionTab.SelectedTabIndex = idx;
     ChunkEndBtn.SelectedColor  = Color.Gold;
     ColorBar.ChunkColor        = Color.Gold;
 }
예제 #11
0
 public ChartOptionForm(ChartOption option,int idx=0)
 {
     OwnedOption = option;
     InitializeComponent();
     OptionTab.SelectedTabIndex = idx;
     ChunkEndBtn.SelectedColor = Color.Gold;
     ColorBar.ChunkColor = Color.Gold;
 }
예제 #12
0
        public List <Chart> GetHistoricData(string symbol, ChartOption chartOption)
        {
            string optionStr  = chartOption.ToString().StartsWith("_") ? chartOption.ToString().Remove(0, 1) : chartOption.ToString();
            string requestUrl = string.Format(this.GetIEXBaseRequestUri(IEXRequestType.Chart), symbol, optionStr);
            string jsonstring = base.GetString(requestUrl).Result;

            List <Chart> result = SerializerHandler.DeserializeObj <List <Chart> >(jsonstring);

            return(result);
        }
예제 #13
0
        public PagedResults QueryLotInfo(Models.XuTaoInput input)
        {
            if (input.ProductName.IsNullOrEmpty())
            {
                throw new ParameterRequiredException("ProductName");
            }
            var         pageResults = _XuTaoRepository.GetLotInfoList(input);
            var         summaryData = _XuTaoRepository.GetLotStatusSummary(input);
            ChartOption option      = summaryData.ToChartOption(ChartType.Bar, "", "", "Status", "Series", "CNT", "asd", ChartDirection.Vertical);

            pageResults.ExtraDatas.Add("Summary", option);
            option = summaryData.ToChartOption(ChartType.Line, "", "", "Status", "Series", "CNT", "asd", ChartDirection.Vertical);
            pageResults.ExtraDatas.Add("Summary1", option);
            return(pageResults);
        }
예제 #14
0
        public override void ProcessCommand(Control control, Command command)
        {
            if (command == Command.Default)
            {
                selectedOption = ChartOption.DefaultCharts;
            }
            else if (command == Command.Custom)
            {
                selectedOption = ChartOption.CustomCharts;
            }
            else
            {
                selectedOption = ChartOption.NoCharts;
            }

            View.Close();
        }
예제 #15
0
        public ChartOption GetMTDInOutInfo(WIPWaferInOutInput input)
        {
            var    summaryData = _WIPWaferInOutRptRepository.QueryMTDInWaferInfo(input);
            var    percentData = _WIPWaferInOutRptRepository.QueryMTDOutWaferInfo(input);
            string chartTitle  = "Fab In & Fab Out Chart( " + input.sMTD + " )";

            string firstAxisName  = "Fab In";
            string secondAxisName = "Fab Out";

            ChartOption optionSummary = summaryData.ToChartOption(ChartType.Bar, chartTitle, "", "name", "Series", "value", "", ChartDirection.Vertical, "", firstAxisName);
            ChartOption addtionOption = percentData.AddToChartOption(optionSummary, ChartType.Bar, "name", "Series", "value", "", "", firstAxisName);

            addtionOption.xAxis[0].axisLabel = new AxisLabel()
            {
                interval = 0, rotate = 40
            };
            addtionOption.title.x = "left";

            return(addtionOption);
        }
예제 #16
0
        // GET: CustomersOrdersChart/fromDate/toDate
        public ActionResult CustomersOrdersChart(string fromDate, string toDate)
        {
            ViewBag.FromDate = fromDate ?? DateTime.Now.GetPersianDateByDashSpliter();
            ViewBag.ToDate   = toDate ?? DateTime.Now.GetPersianDateByDashSpliter();

            try
            {
                lock (CurrentUser)
                {
                    // Fill Chart Data ------------------------------------------
                    #region Chart Data

                    var opt = new ChartOption()
                    {
                        Name           = "customersOrdersChart",
                        ChartType      = ChartTypes.Column,
                        Tilte          = "درخواست مشتریان هر متصدی",
                        SubTitle       = "جمع درخواست ها: ",
                        YAxisTitle     = "جمع ریالی",
                        SeriesName     = "پرسنل",
                        ShowLegend     = false,
                        ShowDataLabels = true,
                        AjaxLoading    = true,
                        LoadDataUrl    = $"GetOfficerOrderStatisticsChart/{fromDate}/{toDate}",
                        SubTitleFunc   = "sum"
                    };

                    #endregion
                    //----------------------------------------------------------


                    return(PartialView("CustomersOrders/CustomersOrdersChart", HtmlHelperExtensions.GetHighChart(opt)));
                }
            }
            catch (Exception exp)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(exp);
            }

            return(PartialView("CustomersOrders/CustomersOrdersChart"));
        }
예제 #17
0
        //生成图片数据
        public string BindImgCode(string sitename, JArray jarray)
        {
            ChartOption option = new ChartOption();

            option.title.text    = "站点关系:用户整合";
            option.title.subtext = "数据来自" + sitename;
            option.legend.data   = new string[] { "主站", "子站", "二级子站" };
            option.series.Add(new ChartSeries()
            {
                name       = "站点关系",
                categories = new Categories[] { new Categories("主站"), new Categories("子站"), new Categories("二级子站") },
                nodes      = GetPicData(sitename, jarray),
                links      = GetPicLinks(GetPicData(sitename, jarray), sitename),
                itemStyle  = new SeriesItemStyle()
            });
            option.series[0].itemStyle.normal.label.textStyle.color = "#333";
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            return("option=" + JsonConvert.SerializeObject(option, Newtonsoft.Json.Formatting.None, setting) + ";myChart.on(\"click\", function (param) {window.open(param.data.url); });");
        }
예제 #18
0
        /// <summary>
        /// refer: https://www.cnblogs.com/kulong995/p/5237796.html
        /// </summary>
        /// <returns></returns>
        public static string TemperatureBar()
        {
            ChartOption option = new ChartOption();

            option.Title().Text("温度计式图表").Subtext("Form ExcelHome").
            Sublink("http://e.weibo.com/1341556070/AizJXrAEa");

            option.ToolTip().Trigger(TriggerType.axis)
            // 原作者嘅 code,好似有 bug,暫時取消
            //.Formatter(new JRaw(@"function (params){
            //    return params[0].name + '<br/>'
            //            + params[0].seriesName + ' : ' + params[0].value + '<br/>'
            //            + params[1].seriesName + ' : ' + (params[1].value + params[0].value);
            //    }"))
            .AxisPointer().Type(AxisPointType.shadow);

            option.Legend().Data("Acutal", "Forecast");

            Feature feature = new Feature();

            feature.Mark().Show(true);
            feature.DataView().Show(true).ReadOnly(false);
            feature.Restore().Show(true);
            feature.SaveAsImage().Show(true);
            option.ToolBox().Show(true).SetFeature(feature);

            option.Grid().Y(80).Y2(30);

            CategoryAxis x = new CategoryAxis();

            x.Data("Cosco", "CMA", "APL", "OOCL", "Wanhai", "Zim");
            option.XAxis(x);

            ValueAxis y = new ValueAxis();

            y.BoundaryGap(new List <double>()
            {
                0, 0.1
            });
            option.YAxis(y);

            var tomatoStyle = new ItemStyle();

            tomatoStyle.Normal().Color("tomato").BarBorderRadius(0)
            .BarBorderColor("tomato").BarBorderWidth(6)
            .Label().Show(true).Position(StyleLabelType.insideTop);
            Bar b1 = new Bar("Acutal");

            b1.Stack("sum");
            b1.SetItemStyle(tomatoStyle);
            b1.Data(260, 200, 220, 120, 100, 80);

            var forecastStyle = new ItemStyle();
            var pattern       = @"(""(?:[^""\\]|\\.)*"")|\s+"; // remove space and CRLF
            var raw           = @"function (params) {for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) {if (option.xAxis[0].data[i] == params.name) {return option.series[0].data[i] + params.value;}}}";
            var formatter     = string.Format(@"eval(""{0}"")", raw);
            var tmp           = new JRaw(raw);

            //! HACK: Formatter 去到 EChartsBox.html script 會出 JSON.parse error
            forecastStyle.Normal().Color("#fff").BarBorderRadius(0)
            .BarBorderColor("tomato").BarBorderWidth(6)
            .Label().Show(true).Position(StyleLabelType.top)
            .Formatter(new JRaw(@"function (params) {
                        for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) {
                            if (option.xAxis[0].data[i] == params.name) {
                                return option.series[0].data[i] + params.value;
                            }
                        }
                    }"))
            //.Formatter(new JRaw(formatter))
            .TextStyle().Color("tomato");

            Bar b2 = new Bar("Forecast");

            b2.Stack("sum");
            b2.SetItemStyle(forecastStyle);
            b2.Data(40, 80, 50, 80, 80, 70);

            option.Series(b1, b2);

            var result = JsonHelper.ObjectToJson2(option);

            return(result);
        }
예제 #19
0
 private void RemoveSeries(ChartOption option)
 {
     while (SeriesOptions.Count(option1 => option1 == option) > 0)
     {
         int i = SeriesOptions.IndexOf(option);
         SeriesOptions.Remove(option);
         Series.RemoveAt(i);
         DwarfChart.Series.RemoveAt(i);
     }
 }
예제 #20
0
        private List<Series> GenerateSeries(ChartOption option, string command = "")
        {
            List<Series> series = new List<Series>();
            switch (option) //Series Setup
            {
                case ChartOption.TimelineEvents: series.Add(new Series("Events"));
                    series.First().Color = Color.FromArgb(65, 140, 240); break;
                case ChartOption.TimelineEventsFiltered: series.Add(new Series("Events (Filtered)"));
                    series.First().Color = Color.FromArgb(252, 180, 64); break;
                case ChartOption.TimelineActiveSites: series.Add(new Series("Sites"));
                    series.First().Color = Color.FromArgb(145, 70, 170); break;
                case ChartOption.TimelineActiveSitesByRace:
                    List<string> races = World.Entities.Where(entity => entity.IsCiv).GroupBy(entity => entity.Race).Select(entity => entity.Key).ToList();
                    foreach (string race in races)
                    {
                        Series raceSeries = new Series(race);
                        raceSeries.Color = World.Entities.First(entity => entity.IsCiv && entity.Race == race).LineColor;
                        raceSeries.BorderWidth = 3;
                        raceSeries.IsVisibleInLegend = false;
                        series.Add(raceSeries);
                    }
                    break;
                case ChartOption.TimelineActiveWars: series.Add(new Series("Wars"));
                    series.First().Color = Color.FromArgb(202, 107, 75); break;
                case ChartOption.TimelineAliveHFs:
                    series.Add(new Series("Historical Figures"));
                    series.First().Color = Color.FromArgb(224, 64, 10); break;
                case ChartOption.TimeLineAliveHFSpecific:
                    series.Add(new Series(AliveHFRace));
                    series.First().Color = Color.FromArgb(224, 64, 10); break;
                case ChartOption.TimelineBattles: series.Add(new Series("Battles"));
                    series.First().Color = Color.FromArgb(26, 59, 105); break;
                case ChartOption.TimelineBeastAttacks: series.Add(new Series("Beast Attacks"));
                    series.First().Color = Color.FromArgb(105, 170, 60); break;
                case ChartOption.TimelineBattleDeaths: series.Add(new Series("Battle Deaths"));
                    series.First().Color = Color.FromArgb(130, 160, 210); break;
                case ChartOption.WorldHFAlive: series.Add(new Series("Historical Figures - Alive")); break;
                case ChartOption.WorldHFRemaining:
                    series.Add(new Series("Historical Figures - Totals"));
                    series.Add(new Series("Historical Figures - Remaining"));
                    break;
                //case ChartOption.WorldHFDead: series.Insert(new Series("Historical Figures - Dead");break;
                case ChartOption.WorldHFRaces: series.Add(new Series("Historical Figures")); break;
                case ChartOption.WorldOutdoorPopulations: series.Add(new Series("Outdoor Populations (Not Including Unnumbered)")); break;
                case ChartOption.WorldRegionTypes: series.Add(new Series("Regions")); break;
                case ChartOption.WorldSitePopulations: series.Add(new Series("Site Populations")); break;
                case ChartOption.WorldDeaths: series.Add(new Series("Deaths")); break;
                case ChartOption.WorldSiteTypes: series.Add(new Series("Sites")); break;
                case ChartOption.WorldUndergroundPopulations: series.Add(new Series("Underground Populations (Not Including Unnumbered)")); break;
                case ChartOption.OtherEventTypes: series.Add(new Series("Event Types")); break;
                case ChartOption.OtherEntityPopulations: series.Add(new Series("Entity Populations")); break;
                case ChartOption.OtherKillsByRace: series.Add(new Series("Kills by Race")); break;
                case ChartOption.OtherDeaths: series.Add(new Series("Deaths")); break;
                case ChartOption.OtherSitePopulations: series.Add(new Series("Site Populations")); break;
                case ChartOption.OtherWarLosses: series.Add(new Series("War Losses")); break;
                case ChartOption.OtherBattleRemaining:
                    series.Add(new Series("Forces - Total"));
                    series.Add(new Series("Forces - Remaining"));
                    break;
            }

            switch (option) //Chart Setup
            {
                case ChartOption.TimelineEvents:
                case ChartOption.TimelineEventsFiltered:
                case ChartOption.TimelineActiveSites:
                case ChartOption.TimelineActiveSitesByRace:
                case ChartOption.TimelineActiveWars:
                case ChartOption.TimelineAliveHFs:
                case ChartOption.TimeLineAliveHFSpecific:
                case ChartOption.TimelineBattles:
                case ChartOption.TimelineBeastAttacks:
                case ChartOption.TimelineBattleDeaths:
                    foreach (Series setup in series)
                    {
                        if (option == ChartOption.TimelineEvents || option == ChartOption.TimelineEventsFiltered)
                            setup.ChartType = SeriesChartType.Area;
                        else
                            setup.ChartType = SeriesChartType.Line;
                        //setup.XValueType = ChartValueType.Int32;
                    }

                    DwarfChart.Legends.Last().LegendStyle = LegendStyle.Row;
                    DwarfChart.Legends.Last().Position.Auto = false;
                    DwarfChart.Legends.Last().Position.Width = 100;
                    DwarfChart.Legends.Last().Position.Y = 100;
                    DwarfChart.Legends.Last().Position.Height = 4;
                    DwarfChart.Titles.Last().Text = "Timeline";
                    DwarfChart.ChartAreas.Last().Area3DStyle.Enable3D = false;
                    DwarfChart.ChartAreas.First().AxisX.MajorGrid.Enabled = true;
                    DwarfChart.ChartAreas.First().AxisX.Interval = 0;
                    DwarfChart.ChartAreas.First().AxisX.LabelStyle.Angle = 0;
                    DwarfChart.Legends.Last().Enabled = true;
                    break;
                case ChartOption.WorldHFAlive:
                //case ChartOption.WorldHFDead:
                case ChartOption.WorldHFRaces:
                case ChartOption.WorldOutdoorPopulations:
                case ChartOption.WorldRegionTypes:
                case ChartOption.WorldSitePopulations:
                case ChartOption.WorldDeaths:
                case ChartOption.WorldSiteTypes:
                case ChartOption.WorldUndergroundPopulations:
                case ChartOption.OtherEventTypes:
                case ChartOption.OtherEntityPopulations:
                case ChartOption.OtherKillsByRace:
                //case ChartOption.OtherEntityWarDeaths:
                //case ChartOption.OtherEntityWarKills:
                //case ChartOption.OtherEntityWarLosses:
                case ChartOption.OtherDeaths:
                case ChartOption.OtherSitePopulations:
                case ChartOption.OtherWarLosses:
                    series.First().ChartType = SeriesChartType.Pie;
                    if (option == ChartOption.OtherWarLosses)
                        series.First().CustomProperties = "PieLabelStyle=Outside,PieStartAngle=270";
                    else
                        series.First().CustomProperties = "CollectedThreshold=0.75, PieLabelStyle=Outside,PieStartAngle=270";
                    series.First().IsValueShownAsLabel = true;
                    series.First().Label = "#LEGENDTEXT\n#VAL (#PERCENT)";
                    DwarfChart.ChartAreas.Last().Area3DStyle.Enable3D = true;
                    DwarfChart.ChartAreas.First().AxisX.MajorGrid.Enabled = true;
                    DwarfChart.Legends.Last().Enabled = false;
                    DwarfChart.Titles.Last().Text = series.First().Name;
                    break;
                //DwarfChart.LegendsViewer.Last().LegendStyle = LegendStyle.Column;
                //DwarfChart.LegendsViewer.Last().Position.Auto = true; break;
                case ChartOption.WorldHFRemaining:
                case ChartOption.OtherBattleRemaining:
                    foreach (Series setup in series)
                    {
                        setup.ChartType = SeriesChartType.Column;
                        setup.IsValueShownAsLabel = true;
                        setup.CustomProperties = "DrawSideBySide=False";
                    }
                    //series.Last().CustomProperties += ",LabelStyle=Bottom";
                    DwarfChart.ChartAreas.Last().Area3DStyle.Enable3D = false;
                    DwarfChart.ChartAreas.Last().AxisX.IntervalOffset = 0;
                    DwarfChart.ChartAreas.First().AxisX.MajorGrid.Enabled = false;
                    DwarfChart.ChartAreas.First().AxisX.Interval = 1;
                    DwarfChart.ChartAreas.First().AxisX.LabelStyle.Angle = -30;
                    DwarfChart.Legends.Last().Enabled = false;
                    DwarfChart.Titles.Last().Text = series.Last().Name;
                    break;
            }

            switch (option) //Generate Series
            {
                case ChartOption.TimelineActiveSites:
                case ChartOption.TimelineActiveSitesByRace:
                case ChartOption.TimelineActiveWars:
                case ChartOption.TimelineAliveHFs:
                case ChartOption.TimeLineAliveHFSpecific:
                case ChartOption.TimelineBattles:
                case ChartOption.TimelineBeastAttacks:
                case ChartOption.TimelineEvents:
                case ChartOption.TimelineEventsFiltered:
                case ChartOption.TimelineBattleDeaths:
                    int startYear = 0, endYear = 0;
                    List<WorldEvent> eventsList = null;
                    List<BeastAttack> beastAttacks;
                    List<Battle> battles;
                    List<War> wars;
                    List<HistoricalFigure> aliveHFs = null;
                    List<HistoricalFigure> hfs = null;

                    if (FocusObject is EventCollection)
                        eventsList = (FocusObject as EventCollection).GetSubEvents();
                    else
                        eventsList = (FocusObject as WorldObject).Events;

                    if (FocusObject.GetType() == typeof(Entity)) wars = (FocusObject as Entity).Wars;
                    else if (FocusObject.GetType() == typeof(War)) wars = new List<War>() { FocusObject as War };
                    else wars = World.Wars;

                    if (FocusObject.GetType() == typeof(HistoricalFigure)) battles = (FocusObject as HistoricalFigure).Battles;
                    else if (FocusObject.GetType() == typeof(Site)) battles = (FocusObject as Site).Warfare.OfType<Battle>().ToList();
                    else if (FocusObject.GetType() == typeof(Entity)) battles = (FocusObject as Entity).Wars.SelectMany(war => war.Collections.OfType<Battle>()).ToList();
                    else if (FocusObject.GetType() == typeof(War)) battles = (FocusObject as War).Collections.OfType<Battle>().ToList();
                    else if (FocusObject.GetType() == typeof(WorldRegion)) battles = (FocusObject as WorldRegion).Battles;
                    else battles = World.Battles;

                    if (FocusObject.GetType() == typeof(HistoricalFigure)) beastAttacks = (FocusObject as HistoricalFigure).BeastAttacks;
                    else if (FocusObject.GetType() == typeof(Site)) beastAttacks = (FocusObject as Site).BeastAttacks;
                    else beastAttacks = World.BeastAttacks;

                    eventsList = eventsList.OrderBy(events => events.Year).ToList();
                    if (eventsList.Count > 0)
                    {
                        startYear = eventsList.First().Year;
                        endYear = eventsList.Last().Year;
                    }

                    int hfIndex = 0;
                    if (option == ChartOption.TimelineAliveHFs || option == ChartOption.TimeLineAliveHFSpecific)
                    {
                        if (option == ChartOption.TimelineAliveHFs)
                            hfs = World.HistoricalFigures.OrderBy(hf => hf.BirthYear).ToList();
                        //aliveHFs = World.HistoricalFigures.Where(hf => hf.BirthYear <= startYear).ToList();
                        else
                            hfs = World.HistoricalFigures.Where(hf => hf.Race == AliveHFRace).OrderBy(hf => hf.BirthYear).ToList(); //====================================================
                        aliveHFs = hfs.Where(hf => hf.BirthYear <= startYear).ToList();
                        //hfs = World.HistoricalFigures.OrderBy(hf => hf.BirthYear).ToList();
                        HistoricalFigure firstHFIndex = hfs.FirstOrDefault(hf => hf.BirthYear > startYear);
                        if (firstHFIndex == null)
                            hfIndex = 0;
                        else
                            hfIndex = hfs.IndexOf(firstHFIndex);
                    }

                    int offset = 0;
                    if (startYear == -1)
                        offset = 1;
                    else
                    {
                        // offset = startYear % 10;
                        // if (offset < 5) offset = 0 - offset;
                    }
                    DwarfChart.ChartAreas.Last().AxisX.IntervalOffset = offset;

                    //uses an event index so the loop doesn't go through every event for each year, only the eventsList for that year
                    int eventIndex = 0;
                    if (eventsList.Count > 0)
                        eventIndex = eventsList.IndexOf(eventsList.First(ev => ev.Year == startYear));
                    int beastAttackStartYear = 0;
                    int beastAttackIndex = 0;
                    if (beastAttacks != null && beastAttacks.Count(ba => ba.StartYear >= startYear) > 0)
                    {
                        if (beastAttacks.FindIndex(ba => ba.StartYear == startYear) >= 0) beastAttackStartYear = startYear;
                        else beastAttackStartYear = beastAttacks.First(ba => ba.StartYear > startYear).StartYear;
                        beastAttackIndex = beastAttacks.IndexOf(beastAttacks.First(ba => ba.StartYear == beastAttackStartYear));
                    }
                    int battleStartYear = 0;
                    int battleIndex = 0;
                    if (battles != null && battles.Count > 0)
                    {
                        if (battles.FindIndex(battle => battle.StartYear == startYear) >= 0) battleStartYear = startYear;
                        else battleStartYear = battles.First(battle => battle.StartYear > startYear).StartYear;
                        battleIndex = battles.IndexOf(battles.First(battle => battle.StartYear == battleStartYear));
                    }
                    for (int year = startYear; year <= endYear; year++)
                    {
                        int count = 0;
                        switch (option)
                        {
                            case ChartOption.TimelineEvents:
                            case ChartOption.TimelineEventsFiltered:
                                while (eventIndex < eventsList.Count && eventsList[eventIndex].Year == year)
                                {
                                    if (option == ChartOption.TimelineEvents) count++;
                                    else if (!(FocusObject.GetType().GetField("Filters").GetValue(null) as List<string>).Contains(eventsList[eventIndex].Type))
                                        count++;
                                    eventIndex++;
                                }
                                break;
                            case ChartOption.TimelineActiveSites:
                                if (FocusObject.GetType() == typeof(Era))
                                    count = World.Entities.Where(entity => entity.IsCiv).Sum(entity => entity.SiteHistory.Count(site => year >= site.StartYear && (year <= site.EndYear || site.EndYear == -1)));
                                else
                                    count = (FocusObject as Entity).SiteHistory.Count(site => year >= site.StartYear && (year <= site.EndYear || site.EndYear == -1));
                                break;
                            case ChartOption.TimelineActiveSitesByRace:
                                foreach (Series race in series)
                                {
                                    count = World.Entities.Where(entity => entity.IsCiv && entity.Race == race.Name).Sum(entity => entity.SiteHistory.Count(site => year >= site.StartYear && (year <= site.EndYear || site.EndYear == -1)));
                                    race.Points.AddXY(year, count);
                                }
                                break;
                            case ChartOption.TimelineActiveWars: count = wars.Count(war => year >= war.StartYear && (year <= war.EndYear || war.EndYear == -1)); break;
                            case ChartOption.TimelineAliveHFs:
                            case ChartOption.TimeLineAliveHFSpecific:
                                aliveHFs.RemoveAll(hf => hf.DeathYear <= year && hf.DeathYear != -1); //Removes Dead HFs
                                while (hfIndex < hfs.Count && hfs[hfIndex].BirthYear == year) //Adds HFs born in current year;
                                {
                                    aliveHFs.Add(hfs[hfIndex]);
                                    hfIndex++;
                                }
                                count = aliveHFs.Count;
                                break;
                            //count = World.HistoricalFigures.Count(hf => year >= hf.BirthYear && (year <= hf.DeathYear || hf.DeathYear == -1)); break;
                            case ChartOption.TimelineBattles:
                            case ChartOption.TimelineBattleDeaths:
                                //count = battles.Count(battle => battle.StartYear == year);
                                while (battleIndex < battles.Count && battles[battleIndex].StartYear == year)
                                {
                                    switch (option)
                                    {
                                        case ChartOption.TimelineBattles: count++; break;
                                        case ChartOption.TimelineBattleDeaths:
                                            Battle yearBattle = battles[battleIndex];
                                            count += yearBattle.AttackerDeathCount + yearBattle.DefenderDeathCount;
                                            break;
                                    }
                                    battleIndex++;
                                }
                                break;
                            case ChartOption.TimelineBeastAttacks:
                                while (beastAttackIndex < beastAttacks.Count && beastAttacks[beastAttackIndex].StartYear == year)
                                {
                                    count++;
                                    beastAttackIndex++;
                                }
                                break;

                            //case ChartOption.TimelineBattleDeaths: count = battles.Where(battle => battle.StartYear == year).Sum(battle => battle.AttackerDeathCount + battle.DefenderDeathCount); break;
                        }
                        if (series.Count == 1) series.First().Points.AddXY(year, count);
                    }
                    int maxPoints = Convert.ToInt32((DwarfChart.ClientRectangle.Width * 0.9)) / 3;
                    if (series.First().Points.Count > maxPoints)
                    {
                        List<double> averagedPoints = new List<double>();
                        int averageMaxCount = series.First().Points.Count / maxPoints;
                        int averageCount = 0;
                        double sum = 0;
                        for (int i = 0; i < series.First().Points.Count; i++)
                        {
                            sum += series.First().Points[i].YValues[0];
                            averageCount++;
                            if (averageCount == averageMaxCount)
                            {
                                averagedPoints.Add(sum / averageCount);
                                sum = 0;
                                averageCount = 0;
                            }
                        }
                        if (averageCount > 0) averagedPoints.Add(sum / averageCount);
                        double yearXPoints = Convert.ToDouble(endYear) / averagedPoints.Count;
                        series.First().Points.Clear();
                        for (int i = 0; i < averagedPoints.Count; i++)
                            series.First().Points.AddXY(i * yearXPoints, averagedPoints[i]);
                    }
                    break;
                case ChartOption.WorldHFAlive:
                    World.HistoricalFigures.Where(hf => hf.DeathYear == -1).GroupBy(hf => hf.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderByDescending(hf => hf.Count).ToList().ForEach(hf => { series.First().Points.AddY(hf.Count); series.First().Points.Last().LegendText = hf.Race; }); break;
                case ChartOption.WorldHFRemaining:
                    var hfTotals = World.HistoricalFigures.GroupBy(hf => hf.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderByDescending(hf => hf.Count).ToList();
                    var hfKilled = World.Events.OfType<HFDied>().GroupBy(death => death.HistoricalFigure.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderBy(hf => hfTotals.IndexOf(hfTotals.First(hf1 => hf1.Race == hf.Race))).ToList();
                    //= World.HistoricalFigures.Where(hf => hf.DeathYear == -1).GroupBy(hf => hf.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderBy(hf => hfTotals.IndexOf(hfTotals.First(hfT => hfT.Race == hf.Race))).ToList();
                    int otherLimit = Convert.ToInt32(hfTotals.Sum(hf => hf.Count) * 0.005);
                    var otherRaces = hfTotals.Where(hf => hf.Count < otherLimit).Select(hf => hf.Race).ToList();
                    int otherTotal = hfTotals.Where(hf => hf.Count < otherLimit).Sum(hf => hf.Count);
                    int otherKilled = hfKilled.Where(hf => otherRaces.Contains(hf.Race)).Sum(hf => hf.Count);
                    hfTotals.RemoveAll(hf => hf.Count < otherLimit);
                    for (int i = 0; i < hfTotals.Count; i++)
                    {
                        series.First().Points.AddXY(i, hfTotals[i].Count);
                        if (hfKilled.Count(hf => hf.Race == hfTotals[i].Race) > 0)
                            series.Last().Points.AddXY(i, hfTotals[i].Count - hfKilled.First(hf => hf.Race == hfTotals[i].Race).Count);
                        else
                            series.Last().Points.AddXY(i, hfTotals[i].Count);
                        series.Last().Points.Last().AxisLabel = Formatting.MakePopulationPlural(hfTotals[i].Race);
                    }
                    series.First().Points.AddXY(hfTotals.Count(hf => hf.Count >= otherLimit), otherTotal);
                    series.Last().Points.AddXY(hfTotals.Count(hf => hf.Count >= otherLimit), otherTotal - otherKilled);
                    series.Last().Points.Last().AxisLabel = "Other";
                    break;
                //case ChartOption.WorldHFDead:
                //    World.HistoricalFigures.Where(hf => hf.DeathYear > 0).GroupBy(hf => hf.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderByDescending(hf => hf.Count).ToList().ForEach(hf => { series.First().Points.AddY(hf.Count); series.First().Points.Last().LegendText = hf.Race; }); break;
                case ChartOption.WorldHFRaces:
                    World.HistoricalFigures.GroupBy(hf => hf.Race).Select(hf => new { Race = hf.Key, Count = hf.Count() }).OrderByDescending(hf => hf.Count).ToList().ForEach(hf => { series.First().Points.AddY(hf.Count); series.First().Points.Last().LegendText = hf.Race; }); break;
                case ChartOption.WorldRegionTypes:
                    World.Regions.GroupBy(region => region.Type).Select(region => new { Type = region.Key, Count = region.Count() }).OrderByDescending(region => region.Count).ToList().ForEach(region => { series.First().Points.AddY(region.Count); series.First().Points.Last().LegendText = region.Type; }); break;
                case ChartOption.WorldSitePopulations:
                    World.SitePopulations.GroupBy(pop => pop.Race).Select(pop => new { Type = pop.Key, Count = pop.Sum(population => population.Count) }).OrderByDescending(pop => pop.Count).ToList().ForEach(pop => { series.First().Points.AddY(pop.Count); series.First().Points.Last().LegendText = pop.Type; }); break;
                case ChartOption.WorldDeaths:
                case ChartOption.OtherDeaths:
                    List<HFDied> hfDeaths = new List<HFDied>();
                    List<Battle.Squad> squads = new List<Battle.Squad>();
                    List<string> deathRaces = new List<string>();
                    if (option == ChartOption.WorldDeaths)
                    {
                        hfDeaths = World.Events.OfType<HFDied>().ToList();
                        //hfDeaths = World.Battles.SelectMany(battle => battle.GetSubEvents().OfType<HFDied>()).ToList();
                        squads = World.Battles.SelectMany(battle => battle.AttackerSquads.Concat(battle.DefenderSquads)).ToList();
                    }
                    else if (FocusObject.GetType() == typeof(Site))
                    {
                        hfDeaths = (FocusObject as Site).Events.OfType<HFDied>().ToList();
                        squads = (FocusObject as Site).Warfare.OfType<Battle>().SelectMany(battle => battle.AttackerSquads.Concat(battle.DefenderSquads)).ToList();
                    }
                    else if (FocusObject.GetType() == typeof(Region))
                    {
                        hfDeaths = (FocusObject as WorldRegion).Events.OfType<HFDied>().ToList();
                        squads = (FocusObject as WorldRegion).Battles.SelectMany(battle => battle.AttackerSquads.Concat(battle.DefenderSquads)).ToList();
                    }
                    else if (FocusObject.GetType() == typeof(Era))
                    {
                        Era era = (FocusObject as Era);
                        hfDeaths = era.Events.OfType<HFDied>().ToList();
                        //hfDeaths = World.Battles.Where(battle => battle.StartYear >= era.StartYear && battle.StartYear <= era.EndYear).SelectMany(battle => battle.GetSubEvents().OfType<HFDied>()).ToList();
                        squads = World.Battles.Where(battle => battle.StartYear >= era.StartYear && battle.StartYear <= era.EndYear).SelectMany(battle => battle.AttackerSquads.Concat(battle.DefenderSquads)).ToList();
                    }

                    hfDeaths.Select(death => death.HistoricalFigure.Race).ToList().ForEach(death => deathRaces.Add(AppHelpers.MakePopulationPlural(death)));
                    foreach (Battle.Squad squad in squads)
                    {
                        string plural = AppHelpers.MakePopulationPlural(squad.Race);
                        for (int i = 0; i < squad.Deaths; i++) deathRaces.Add(plural);
                    }
                    deathRaces.GroupBy(race => race).Select(race => new { Type = race.Key, Count = race.Count() }).OrderByDescending(race => race.Count).ToList().ForEach(race => { series.First().Points.AddY(race.Count); series.First().Points.Last().LegendText = race.Type; });
                    break;
                case ChartOption.WorldSiteTypes:
                    World.Sites.GroupBy(region => region.Type).Select(site => new { Type = site.Key, Count = site.Count() }).OrderByDescending(site => site.Count).ToList().ForEach(site => { series.First().Points.AddY(site.Count); series.First().Points.Last().LegendText = site.Type; }); break;
                case ChartOption.WorldOutdoorPopulations:
                    World.OutdoorPopulations.Where(pop => pop.Count != int.MaxValue).ToList().ForEach(pop => { series.First().Points.AddY(pop.Count); series.First().Points.Last().LegendText = pop.Race; }); break;
                case ChartOption.WorldUndergroundPopulations:
                    World.UndergroundPopulations.Where(pop => pop.Count != int.MaxValue).ToList().ForEach(pop => { series.First().Points.AddY(pop.Count); series.First().Points.Last().LegendText = pop.Race; }); break;
                case ChartOption.OtherEventTypes:
                    if (FocusObject is EventCollection)
                        (FocusObject as EventCollection).GetSubEvents().GroupBy(events => events.Type).Select(events => new { Type = events.Key, Count = events.Count() }).OrderByDescending(events => events.Count).ToList().ForEach(events => { series.First().Points.AddY(events.Count); series.First().Points.Last().LegendText = AppHelpers.EventInfo.Single(eventInfo => eventInfo[0] == events.Type)[1]; });
                    else
                        (FocusObject as WorldObject).Events.GroupBy(events => events.Type).Select(events => new { Type = events.Key, Count = events.Count() }).OrderByDescending(events => events.Count).ToList().ForEach(events => { series.First().Points.AddY(events.Count); series.First().Points.Last().LegendText = AppHelpers.EventInfo.Single(eventInfo => eventInfo[0] == events.Type)[1]; }); break;
                case ChartOption.OtherKillsByRace:
                    (FocusObject as HistoricalFigure).Kills.GroupBy(death => death.HistoricalFigure.Race).Select(death => new { Race = death.Key, Count = death.Count() }).OrderByDescending(death => death.Count).ToList().ForEach(death => { series.First().Points.AddY(death.Count); series.First().Points.Last().LegendText = death.Race; }); break;
                case ChartOption.OtherEntityPopulations:
                    (FocusObject as Entity).Populations.OrderByDescending(pop => pop.Count).ToList().ForEach(pop => { series.First().Points.AddY(pop.Count); series.First().Points.Last().LegendText = pop.Race; }); break;
                //case ChartOption.OtherDeaths:
                //    (FocusObject as WorldRegion).Events.OfType<HFDied>().GroupBy(death => death.HistoricalFigure.Race).Select(death => new { Race = death.Key, Count = death.Count() }).OrderByDescending(death => death.Count).ToList().ForEach(death => { series.First().Points.AddY(death.Count); series.First().Points.Last().LegendText = death.Race; }); break;
                //case ChartOption.OtherSiteDeaths:
                //    (FocusObject as Site).Events.OfType<HFDied>().GroupBy(death => death.HistoricalFigure.Race).Select(death => new { Race = death.Key, Count = death.Count() }).OrderByDescending(death => death.Count).ToList().ForEach(death => { series.First().Points.AddY(death.Count); series.First().Points.Last().LegendText = death.Race; }); break;
                case ChartOption.OtherSitePopulations:
                    (FocusObject as Site).Populations.OrderByDescending(pop => pop.Count).ToList().ForEach(pop => { series.First().Points.AddY(pop.Count); series.First().Points.Last().LegendText = pop.Race; }); break;
                case ChartOption.OtherWarLosses:
                    List<War> warsList = new List<War>();
                    if (FocusObject.GetType() == typeof(War)) warsList.Add(FocusObject as War);
                    else if (FocusObject.GetType() == typeof(Entity))
                        foreach (War addWar in (FocusObject as Entity).Wars) warsList.Add(addWar);
                    List<Entity> entities = warsList.SelectMany(war => new List<Entity> { war.Attacker, war.Defender }).ToList();
                    entities = entities.GroupBy(entity => entity).Select(entity => entity.Key).ToList();
                    entities.RemoveAll(entity => entity.Parent != null && entities.Contains(entity.Parent));
                    foreach (Entity entity in entities)
                    {
                        List<Battle> battles1 = warsList.SelectMany(wars1 => wars1.Collections.OfType<Battle>()).ToList();
                        List<HFDied> hfDeathsList = new List<HFDied>();
                        List<Battle.Squad> squadsList = new List<Battle.Squad>();
                        List<string> deathRacesList = new List<string>();
                        hfDeathsList = battles1.Where(battle => battle.Attacker == entity || battle.Attacker.Parent == entity).SelectMany(battle => battle.GetSubEvents().OfType<HFDied>().Where(death => battle.NotableAttackers.Contains(death.HistoricalFigure))).ToList();
                        hfDeathsList = hfDeathsList.Concat(battles1.Where(battle => battle.Defender == entity || battle.Defender.Parent == entity).SelectMany(battle => battle.GetSubEvents().OfType<HFDied>().Where(death => battle.NotableDefenders.Contains(death.HistoricalFigure))).ToList()).ToList();
                        squadsList = battles1.Where(battle => battle.Attacker == entity || battle.Attacker.Parent == entity).SelectMany(battle => battle.AttackerSquads).ToList();
                        squadsList = squadsList.Concat(battles1.Where(battle => battle.Defender == entity || battle.Defender.Parent == entity).SelectMany(battle => battle.DefenderSquads).ToList()).ToList();
                        hfDeathsList.Select(death => death.HistoricalFigure.Race).ToList().ForEach(death => deathRacesList.Add(AppHelpers.MakePopulationPlural(death)));

                        //squadsList.GroupBy(squad => squad.Race).Select(squad => new { Race = squad.Key, Count = squad.Sum(race => race.Deaths) });
                        foreach (Battle.Squad squad in squadsList)
                        {
                            string plural = AppHelpers.MakePopulationPlural(squad.Race);
                            for (int i = 0; i < squad.Deaths; i++) deathRacesList.Add(plural);
                        }

                        var deathsList = deathRacesList.GroupBy(race => race).Select(race => new { Type = race.Key, Count = race.Count() }).OrderByDescending(race => race.Count).ToList();
                        int deathOtherLimit = Convert.ToInt32(deathsList.Sum(death => death.Count) * 0.02);
                        deathsList.Where(death => death.Count >= deathOtherLimit).ToList().ForEach(race => { series.First().Points.AddY(race.Count); series.First().Points.Last().LegendText = race.Type; series.First().Points.Last().Color = entity.LineColor; series.First().Points.Last().BorderColor = Color.Gray; series.First().Points.Last().LabelBackColor = Color.FromArgb(127, entity.LineColor); });
                        int deathOtherCount = deathsList.Where(death => death.Count < deathOtherLimit).Sum(death => death.Count);
                        if (deathOtherCount > 0)
                        {
                            series.First().Points.AddY(deathOtherCount);
                            series.First().Points.Last().LegendText = "Other";
                            series.First().Points.Last().Color = entity.LineColor;
                            series.First().Points.Last().BorderColor = Color.Gray;
                            series.First().Points.Last().LabelBackColor = Color.FromArgb(127, entity.LineColor);
                        }
                    }
                    break;
                case ChartOption.OtherBattleRemaining:
                    Battle battle1 = (FocusObject as Battle);
                    List<string> attackers = battle1.NotableAttackers.Select(hf => AppHelpers.MakePopulationPlural(hf.Race)).ToList();
                    List<string> attackersKilled = battle1.NotableAttackers.Where(hf => battle1.GetSubEvents().OfType<HFDied>().Count(death => death.HistoricalFigure == hf) > 0).Select(hf => AppHelpers.MakePopulationPlural(hf.Race)).ToList();
                    foreach (Battle.Squad squad in battle1.AttackerSquads)
                    {
                        string plural = AppHelpers.MakePopulationPlural(squad.Race);
                        for (int i = 0; i < squad.Numbers; i++) attackers.Add(plural);
                        for (int i = 0; i < squad.Deaths; i++) attackersKilled.Add(plural);
                    }
                    var attackerTotals = attackers.GroupBy(attacker => attacker).Select(result => new { Type = result.Key, Count = result.Count() }).OrderByDescending(attacker => attacker.Count).ToList();
                    var attackerTotalsKilled = attackersKilled.GroupBy(attacker => attacker).Select(result => new { Type = result.Key, Count = result.Count() }).OrderBy(attacker => attackerTotals.IndexOf(attackerTotals.First(race => race.Type == attacker.Type))).ToList();

                    for (int i = 0; i < attackerTotals.Count; i++)
                    {
                        series.First().Points.AddXY(i, attackerTotals[i].Count);
                        if (attackerTotalsKilled.Count(race => race.Type == attackerTotals[i].Type) > 0)
                            series.Last().Points.AddXY(i, attackerTotals[i].Count - attackerTotalsKilled.First(race => race.Type == attackerTotals[i].Type).Count);
                        else
                            series.Last().Points.AddXY(i, attackerTotals[i].Count);
                        series.First().Color = Color.LightGray;
                        series.Last().Points.Last().Color = battle1.Attacker.LineColor;
                        series.Last().Points.Last().AxisLabel = attackerTotals[i].Type;
                        //series.Last().Points.Last().LabelBackColor = Color.FromArgb(127, battle1.Attacker.LineColor);
                    }

                    series.First().Points.AddXY(attackerTotals.Count, 0);
                    series.First().Points.Last().IsEmpty = true;
                    series.First().Points.Last().Label = "";
                    series.Last().Points.AddXY(attackerTotals.Count, 0);
                    series.Last().Points.Last().IsEmpty = true;
                    series.Last().Points.Last().Label = "";
                    series.Last().Points.Last().AxisLabel = "VS.";

                    List<string> defenders = battle1.NotableDefenders.Select(hf => AppHelpers.MakePopulationPlural(hf.Race)).ToList();
                    List<string> defendersKilled = battle1.NotableDefenders.Where(hf => battle1.GetSubEvents().OfType<HFDied>().Count(death => death.HistoricalFigure == hf) > 0).Select(hf => AppHelpers.MakePopulationPlural(hf.Race)).ToList();
                    foreach (Battle.Squad squad in battle1.DefenderSquads)
                    {
                        string plural = AppHelpers.MakePopulationPlural(squad.Race);
                        for (int i = 0; i < squad.Numbers; i++) defenders.Add(plural);
                        for (int i = 0; i < squad.Deaths; i++) defendersKilled.Add(plural);
                    }
                    var defenderTotals = defenders.GroupBy(defender => defender).Select(result => new { Type = result.Key, Count = result.Count() }).OrderByDescending(defender => defender.Count).ToList();
                    var defenderTotalsKilled = defendersKilled.GroupBy(defender => defender).Select(result => new { Type = result.Key, Count = result.Count() }).OrderBy(defender => defenderTotals.IndexOf(defenderTotals.First(race => race.Type == defender.Type))).ToList();

                    for (int i = 0; i < defenderTotals.Count; i++)
                    {
                        series.First().Points.AddXY(i + attackerTotals.Count + 1, defenderTotals[i].Count);
                        if (defenderTotalsKilled.Count(race => race.Type == defenderTotals[i].Type) > 0)
                            series.Last().Points.AddXY(i + attackerTotals.Count + 1, defenderTotals[i].Count - defenderTotalsKilled.First(race => race.Type == defenderTotals[i].Type).Count);
                        else
                            series.Last().Points.AddXY(i + attackerTotals.Count + 1, defenderTotals[i].Count);
                        series.First().Color = Color.LightGray;
                        series.Last().Points.Last().Color = battle1.Defender.LineColor;
                        series.Last().Points.Last().AxisLabel = defenderTotals[i].Type;
                        //series.Last().Points.Last().LabelBackColor = Color.FromArgb(127, battle1.Defender.LineColor);
                    }
                    break;

            }

            return series;
        }
예제 #21
0
 public void MenuClick(ChartMenuItem sender, ChartOption option)
 {
     switch (option)
     {
         case ChartOption.TimelineActiveSites:
         case ChartOption.TimelineActiveSitesByRace:
         case ChartOption.TimelineActiveWars:
         case ChartOption.TimelineAliveHFs:
         case ChartOption.TimeLineAliveHFSpecific:
         case ChartOption.TimelineBattles:
         case ChartOption.TimelineBeastAttacks:
         case ChartOption.TimelineEvents:
         case ChartOption.TimelineEventsFiltered:
         case ChartOption.TimelineBattleDeaths:
             if (option == ChartOption.TimeLineAliveHFSpecific && !SeriesOptions.Contains(ChartOption.TimeLineAliveHFSpecific))
             {
                 dlgHF selectHFRace = new dlgHF(World);
                 selectHFRace.ShowDialog();
                 if (selectHFRace.SelectedRace == "") return;
                 AliveHFRace = selectHFRace.SelectedRace;
             }
             if (OtherChart) while (SeriesOptions.Count > 0) RemoveSeries(SeriesOptions[0]);
             if (SeriesOptions.Contains(option)) RemoveSeries(option);
             else SeriesOptions.Add(option);
             //sender.Checked = !sender.Checked;
             OtherChart = false;
             break;
         default:
             while (SeriesOptions.Count > 0) RemoveSeries(SeriesOptions[0]);
             SeriesOptions.Add(option);
             OtherChart = true;
             break;
     }
     GenerateSeries();
 }
예제 #22
0
 public ChartMenuItem(ChartPanel chart, ChartOption option)
 {
     Option = option;
     Chart = chart;
     switch (Option)
     {
         case ChartOption.TimelineEvents: Text = "Events"; break;
         case ChartOption.TimelineEventsFiltered: Text = "Events (Filtered)"; break;
         case ChartOption.TimelineBattleDeaths: Text = "Battle Deaths"; break;
         case ChartOption.TimelineActiveSites: Text = "Active Sites"; break;
         case ChartOption.TimelineActiveSitesByRace: Text = "Active Sites by Race"; break;
         case ChartOption.TimelineAliveHFs: Text = "Alive Historical Figures"; break;
         case ChartOption.TimeLineAliveHFSpecific: Text = "Alive Historical Figures..."; break;
         case ChartOption.TimelineActiveWars: Text = "Active Wars"; break;
         case ChartOption.TimelineBattles: Text = "Battles"; break;
         case ChartOption.TimelineBeastAttacks: Text = "Beast Attacks"; break;
         case ChartOption.OtherEventTypes: Text = "Event Types"; break;
         case ChartOption.OtherKillsByRace: Text = "Kills"; break;
         case ChartOption.OtherEntityPopulations: Text = "Site Populations"; break;
         case ChartOption.OtherDeaths: Text = "Deaths"; break; ;
         case ChartOption.OtherSitePopulations: Text = "Populations"; break;
         case ChartOption.OtherWarLosses: Text = "War Losses"; break;
         case ChartOption.OtherBattleRemaining: Text = "Remaining Forces"; break;
         case ChartOption.WorldHFRaces: Text = "Historical Figures"; break;
         case ChartOption.WorldHFAlive: Text = "Historical Figures - Alive"; break;
         case ChartOption.WorldHFRemaining: Text = "Hsitorical Figures - Remaining"; break;
         case ChartOption.WorldSitePopulations: Text = "Site Populations"; break;
         case ChartOption.WorldDeaths: Text = "Deaths"; break;
         case ChartOption.WorldSiteTypes: Text = "Sites"; break;
         case ChartOption.WorldRegionTypes: Text = "Regions"; break;
         case ChartOption.WorldOutdoorPopulations: Text = "Outdoor Populations"; break;
         case ChartOption.WorldUndergroundPopulations: Text = "Underground Populations"; break;
     }
 }
예제 #23
0
        /// <summary>
        /// refer: https://www.cnblogs.com/kulong995/p/5237796.html
        /// </summary>
        /// <returns></returns>
        public static string StdLine()
        {
            IList <string> weeks = ChartsUtil.Weeks();

            IList <int> datas1 = ChartsUtil.Datas(7, 10, 15);

            IList <int> datas2 = ChartsUtil.Datas(7, -2, 5);

            int min   = datas2.Min();
            int index = datas2.IndexOf(min);

            ChartOption option = new ChartOption();

            #region option.title

            /** origional code
             * option.title = new Title()
             * {
             *  show = true,
             *  text = "未来一周天气变化",
             *  subtext = "纯虚构数据"
             * };
             */
            option.title = new List <Title>()
            {
                new Title()
                {
                    show    = true,
                    text    = "未来一周天气变化",
                    subtext = "纯虚构数据"
                }
            };
            #endregion

            #region option.tooltip
            option.tooltip = new Forms.Model.ECharts.ToolTip()
            {
                trigger = TriggerType.axis
            };
            #endregion

            #region option.legend
            option.legend = new Legend()
            {
                data = new List <object>()
                {
                    "最高温度",
                    "最低温度"
                }
            };
            #endregion

            option.calculable = true;

            #region option.xAxis
            option.xAxis = new List <Forms.Model.ECharts.axis.Axis>()
            {
                new Forms.Model.ECharts.axis.CategoryAxis()
                {
                    type        = AxisType.category,
                    boundaryGap = false,
                    data        = new List <object>(weeks)
                }
            };
            #endregion

            #region option.yAxis
            option.yAxis = new List <Axis>()
            {
                new ValueAxis()
                {
                    type      = AxisType.value,
                    axisLabel = new AxisLabel()
                    {
                        formatter = new JRaw("{value} ℃").ToString()
                    }
                }
            };
            #endregion

            #region option.series
            option.series = new List <object>()
            {
                new Line()
                {
                    name      = "最高温度",
                    type      = ChartType.line,
                    data      = datas1,
                    markPoint = new MarkPoint()
                    {
                        data = new List <object>()
                        {
                            new MarkData()
                            {
                                name = "最大值",
                                type = MarkType.max,
                            },
                            new MarkData()
                            {
                                name = "最小值",
                                type = MarkType.min,
                            }
                        }
                    },
                    markLine = new MarkLine()
                    {
                        data = new List <object>()
                        {
                            new MarkData()
                            {
                                name = "平均值",
                                type = MarkType.average
                            }
                        }
                    }
                },
                new Line()
                {
                    name      = "最低温度",
                    type      = ChartType.line,
                    data      = datas2,
                    markPoint = new MarkPoint()
                    {
                        data = new List <object>()
                        {
                            new MarkData()
                            {
                                name  = "周最低",
                                value = min,
                                xAxis = index,
                                yAxis = min + 0.5,
                            }
                        }
                    },
                    markLine = new MarkLine()
                    {
                        data = new List <object>()
                        {
                            new MarkData()
                            {
                                type = MarkType.average,
                                name = "平均值"
                            }
                        }
                    }
                }
            };
            #endregion

            var result = JsonHelper.ObjectToJson2(option);

            return(result);
        }
예제 #24
0
        public static void TestGraphLive(this AbstractIndicator ind, string timeframe, string symbol, int length)
        {
            //------------grab data
            FXSession session = new FXSession();

            session.InitializeSession();

            HistoricPriceEngine h = new HistoricPriceEngine(session);

            h.GetLongHistoricPrices(symbol, timeframe, length);

            while (!h.Complete)
            {
                Thread.Sleep(100);
            }
            //-----------------------

            Quantum       q     = h.Data;
            var           dz    = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, q.Data.Count);
            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add(ind.ToString());
            foreach (var indicator in ind.SubIndicators)
            {
                names.Add(indicator.Key);
            }

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 400, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 200, YPosition = 1
            };
            for (int i = 2; i < chartOptions.Length; i++)
            {
                chartOptions[i] = new ChartOption()
                {
                    Height = 0, YPosition = 1, Layover = true
                }
            }
            ;

            int counter = 0;

            foreach (Tick tick in q)
            {
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;

                dz[4, counter] = ind.HandleNextTick(tick);

                int icounter = 5;
                foreach (var subind in ind.SubIndicators.Values)
                {
                    dz[icounter, counter] = subind[0];
                    icounter++;
                }

                counter++;
            }


            Visualize.GenerateMultiPaneGraph(names.ToArray(), q.Data.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html",
                                             chartOptions);

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
예제 #25
0
        public BatchReport GetBatchReport(string symbol, IEnumerable <IEXDataType> types, ChartOption range, int itemCount)
        {
            string rangeStr       = range.ToString().StartsWith("_") ? range.ToString().Remove(0, 1) : range.ToString();
            string baseRequestUri = GetIEXBaseRequestUri(IEXRequestType.BatchReportForAStock);
            string requestUrl     = string.Format(baseRequestUri, symbol, types.ToStringDelimeter(), rangeStr, itemCount.LimitToMax());

            Console.WriteLine(requestUrl);

            string jsonstring = base.GetString(requestUrl).Result;

            return(SerializerHandler.DeserializeObj <BatchReport>(jsonstring));
        }
예제 #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (function.isAjax())
            {
                string action = Request.Form["action"];
                string result = "";
                switch (action)
                {
                case "createimg":
                {
                    ChartTitle title = JsonConvert.DeserializeObject <ChartTitle>(Request.Form["title"], new JsonSerializerSettings()
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        });                                                                                                                                                                    //数组中包含空数据等仍会造成问题
                    string      toolbox = Request.Form["toolbox"];
                    ChartOption option  = null;
                    switch (Type)
                    {
                        #region AJAX请求
                    case "bar":
                    case "line":
                    {
                        option = new BarChartOption(title, toolbox, Type);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ((BarChartOption)option).AddData(packmod.rowdata, packmod.series, Tag);
                    }
                    break;

                    case "pie":
                    {
                        option = new PieChartOption(title, toolbox);
                        ChartLegend  legend  = new ChartLegend();
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        legend.data = packmod.rowdata;
                        ((PieChartOption)option).AddData(legend, packmod.series, Tag);
                    }
                    break;

                    case "dash":
                    {
                        option = new DashOption(title, toolbox);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ((DashOption)option).AddData(packmod.series);
                    }
                    break;

                    case "funnel":
                    {
                        option = new FunnelChartOption(title, toolbox);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ChartLegend  legend  = new ChartLegend();
                        legend.data = packmod.rowdata;
                        ((FunnelChartOption)option).AddData(legend, packmod.series);
                    }
                    break;

                    case "scatter":
                    {
                        option = new ScatterChartOption(title, toolbox);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ChartLegend  legend  = new ChartLegend();
                        legend.data = packmod.rowdata;
                        ((ScatterChartOption)option).AddData(legend, packmod.series);
                    }
                    break;

                    case "circle":
                    {
                        option = new CircleChartOption(title, toolbox);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ChartLegend  legend  = new ChartLegend();
                        legend.data = packmod.rowdata;
                        ((CircleChartOption)option).AddData(legend, packmod.series);
                    }
                    break;

                    case "map":
                    {
                        option = new MapChartOption(title, toolbox);
                        ChartPackage packmod = JsonConvert.DeserializeObject <ChartPackage>(Request.Form["packmod"]);
                        ChartLegend  legend  = new ChartLegend();
                        legend.data = packmod.rowdata;
                        ((MapChartOption)option).AddData(legend, packmod.series);
                    }
                    break;
                        #endregion
                    }
                    option.calculable = bool.Parse(Request.Form["calculable"]);
                    result            = option.ToString();
                    break;
                }
                }
                Response.Clear();
                Response.Write(result); Response.Flush(); Response.End();
            }
            else if (!IsPostBack)
            {
                if (Mid > 0)
                {
                    chartMod             = chartBll.SelReturnModel(Mid);
                    ChartTitle_Hid.Value = chartMod.ChartTitle;
                    Cdate_Hid.Value      = chartMod.CDate.ToString();
                    ToolBox_Hid.Value    = chartMod.ToolBox;
                    Package_Hid.Value    = chartMod.Package;
                    code.Text            = chartMod.option;
                    function.Script(this, "LoadEditConfig();");
                }
                else//调用初始化方法
                {
                    function.Script(this, "LoadNewConfig();");
                }
                Call.SetBreadCrumb(Master, "<li><a href='" + customPath2 + "Main.aspx'>工作台</a></li><li><a href='Default.aspx'>智慧图表</a></li><li><a href='AddChart.aspx'>创建图表</a></li><li class='active'><a href='" + Request.RawUrl + "'>图表配置</a>[" + chartMod.GetTypeStr(Type) + "]</li>");
            }
        }
        /// <summary>
        /// Enable Zoom and Pan Controls.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="selectionChanged">Selection changed callabck. Triggered when user select a point with selec tool.</param>
        /// <param name="cursorMoved">Cursor moved callabck. Triggered when user move the mouse in chart area.</param>
        /// <param name="zoomChanged">Callback triggered when chart has 
        /// zoomed in or out (and on first painting of the chart).</param>
        /// <param name="option">Additional user options</param>
        /// <remarks>
        /// <para>Callback are optional (pass in null to ignore).</para>
        /// <para>WARNING: Add or Remove Chart Area or Chart Series after enabled zoom and pan controls may cause unexpected behavior.</para>
        /// <para>Recommended to enable the zoom and pan controls after configure the <see cref="ChartArea"/> and <see cref="Series"/>.</para>
        /// </remarks>
        public static void EnableZoomAndPanControls(this Chart sender,
            CursorPositionChanged selectionChanged,
            CursorPositionChanged cursorMoved,
            ZoomChanged zoomChanged = null, ChartOption option = null)
        {
            if (!ChartTool.ContainsKey(sender))
            {
                ChartTool[sender] = new ChartData(sender);
                ChartData ptrChartData = ChartTool[sender];
                ptrChartData.Option = (option == null) ? new ChartOption() : option;
                ptrChartData.Backup();
                ptrChartData.PositionChangedCallback = selectionChanged;
                ptrChartData.CursorMovedCallback = cursorMoved;
                ptrChartData.ZoomChangedCallback = zoomChanged;

                //Scan through series to identify valid ChartArea
                Chart ptrChart = sender;
                foreach (ChartArea cArea in ptrChart.ChartAreas)
                {
                    IEnumerable<Series> chartSeries = ptrChart.Series.Where(n => n.ChartArea == cArea.Name);
                    if (chartSeries.Count() == 0)
                    {
                        Debug.WriteLine(string.Format("WARNING: Chart Area [{0}] does not contains any series.", cArea.Name));
                    }
                    else if (chartSeries.Where(n => UnsupportedChartType.Contains(n.ChartType)).Count() > 0)
                    {
                        Debug.WriteLine(string.Format("WARNING: Chart Area [{0}] contains unsupported series.", cArea.Name));
                    }
                    else ptrChartData.SupportedChartArea.Add(cArea);
                }

                //Populate Context menu
                if (ptrChart.ContextMenuStrip == null)
                {
                    //Context menu is empty, use ChartContextMenuStrip directly
                    ptrChart.ContextMenuStrip = new ContextMenuStrip();
                    ptrChart.ContextMenuStrip.Items.AddRange(ChartTool[ptrChart].MenuItems.ToArray());
                }
                else
                {
                    //User assigned context menu to chart. Merge current menu with ChartContextMenuStrip.
                    ContextMenuStrip newMenu = new ContextMenuStrip();
                    newMenu.Items.AddRange(ChartTool[sender].MenuItems.ToArray());

                    foreach (object ptrItem in ChartTool[sender].ContextMenuStrip.Items)
                    {
                        if (ptrItem is ToolStripMenuItem) newMenu.Items.Add(((ToolStripMenuItem)ptrItem).Clone());
                        else if (ptrItem is ToolStripSeparator) newMenu.Items.Add(new ToolStripSeparator());
                    }
                    ptrChart.ContextMenuStrip = newMenu;
                    ptrChart.ContextMenuStrip.AddHandlers(ChartTool[sender].ContextMenuStrip);
                }
                ptrChart.ContextMenuStrip.Opening += ChartContext_Opening;
                ptrChart.ContextMenuStrip.ItemClicked += ChartContext_ItemClicked;
                ptrChart.MouseWheel += ChartControl_MouseWheel;
                ptrChart.MouseDown += ChartControl_MouseDown;
                ptrChart.MouseMove += ChartControl_MouseMove;
                ptrChart.MouseUp += ChartControl_MouseUp;

                //Override settings.
                foreach (ChartArea ptrChartArea in ptrChart.ChartAreas)
                {
                    ptrChartArea.CursorX.AutoScroll = false;
                    ptrChartArea.CursorX.Interval = 1e-06;
                    ptrChartArea.CursorY.AutoScroll = false;
                    ptrChartArea.CursorY.Interval = 1e-06;

                    ptrChartArea.AxisX.ScrollBar.Enabled = false;
                    ptrChartArea.AxisX2.ScrollBar.Enabled = false;
                    ptrChartArea.AxisY.ScrollBar.Enabled = false;
                    ptrChartArea.AxisY2.ScrollBar.Enabled = false;
                }
                SetChartControlState(sender, MSChartExtensionToolState.Select);
            }
        }
예제 #28
0
        internal static void InsertBatch(IEnumerable <CIKInfo> cikInfos, List <IEXDataType> listIexDataTypes, ChartOption chartOption, int itemCount, Period period)
        {
            int total      = cikInfos.Count();
            int count      = 0;
            int batchCount = 50;
            CompanyCollection companyRepo = new CompanyCollection();

            do
            {
                var symbols = cikInfos.Select(x => x.Ticker).Skip(count).Take(batchCount).ToArray();
                count += symbols.Count();

                var dictSymbolComp = companyRepo.GetCompanyId(symbols.ToList());
                //get data
                IEXClientHandler response = new IEXClientHandler();
                var results = response.GetBatchReport(symbols, listIexDataTypes, ChartOption._1d, itemCount, period);


                //insert to db
                var comp  = new MongoDBRepository <Company>(nameof(Company));
                var stat  = new MongoDBRepository <Stat>("IEXStat");
                var fin   = new MongoDBRepository <Financial>(nameof(Financial));
                var quote = new MongoDBRepository <Quote>("Quote");


                foreach (string symbol in results.Keys)
                {
                    ObjectId compId = ObjectId.GenerateNewId(); //ObjectId.GenerateNewId().ToString();
                    results[symbol].Company._id = compId;
                    if (results[symbol].Company != null)
                    {
                        comp.MongoInsert(results[symbol].Company).Wait();
                    }

                    if (results[symbol].Stat != null)
                    {
                        results[symbol].Stat.companyId = compId;
                        stat.MongoInsert(results[symbol].Stat).Wait();
                    }

                    if (results[symbol].Financials.financials != null)
                    {
                        Parallel.For(0, results[symbol].Financials.financials.Count, (i) =>
                        {
                            results[symbol].Financials.financials[i].companyId = compId;
                        });

                        fin.MongoInsertMany(results[symbol].Financials.financials).Wait();
                    }

                    if (results[symbol].Quote != null)
                    {
                        results[symbol].Quote.companyId = compId;
                        quote.MongoInsert(results[symbol].Quote).Wait();
                    }
                }
            } while (count < total);
        }
예제 #29
0
        public static string GetOption_HK()
        {
            #region const option string
            var result = @"{
      // google map component
      gmap: {
        // initial options of Google Map
        // See https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions for details
        // initial map center, accepts an array like [lng, lat] or an object like { lng, lat }
        center: [112.0,31.0],
        // center: { lng: 108.39, lat: 39.9 },
        // initial map zoom
        zoom: 5,

        // whether echarts layer should be rendered when the map is moving. `true` by default.
        // if false, it will only be re-rendered after the map `moveend`.
        // It's better to set this option to false if data is large.
        renderOnMoving: true,
        // the zIndex of echarts layer for Google Map. `2000` by default.
        echartsLayerZIndex: 2019,
        // whether to enable gesture handling. `true` by default.
        // since v1.4.0
        roam: false

        // More initial options...
      },
      tooltip : {
        trigger: 'item'
      },
      animation: true,
      series: [
        {
          name: 'PM2.5',
          type: 'scatter',
          // use `gmap` as the coordinate system
          coordinateSystem: 'gmap',
          // data items [[lng, lat, value], [lng, lat, value], ...]
          data: convertData(data),
          symbolSize: function (val) {
            return val[2] / 10;
          },
          encode: {
            value: 2,
            lng: 0,
            lat: 1
          },
          label: {
            formatter: '{b}',
            position: 'right',
            show: false
          },
          itemStyle: {
            color: '#00c1de'
          },
          emphasis: {
            label: {
              show: true
            }
          }
        },
        {
          name: 'Top 5',
          type: 'effectScatter',
          coordinateSystem: 'gmap',
          data: convertData(data.sort(function (a, b) {
            return b.value - a.value;
          }).slice(0, 6)),
          symbolSize: function (val) {
            return val[2] / 10;
          },
          encode: {
            value: 2,
            lng: 0,
            lat: 1
          },
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          label: {
            formatter: '{b}',
            position: 'right',
            show: true
          },
          itemStyle: {
            color: '#fff',
            shadowBlur: 10,
            shadowColor: '#333'
          },
          zlevel: 1
        }
      ]
}";
            #endregion

            ChartOption option = new ChartOption();

            #region option.gmap
            var coordination = new List <double>();
            coordination.Add(114.1198);
            coordination.Add(22.3553);

            option.gmap = new Forms.Model.ECharts.gmap.GMap()
            {
                center             = coordination, // Kwai Chung Park 22.355287655768507, 114.11980401763222
                zoom               = 12,
                roam               = true,         // allow gesture
                renderOnMoving     = true,
                echartsLayerZIndex = 2001
            };
            #endregion

            #region option.tooltip
            option.tooltip = new ToolTip()
            {
                trigger = TriggerType.item
            };
            #endregion

            option.animation = true;

            #region option.series
            var itemStyle            = new Forms.Model.ECharts.style.ItemStyle();
            itemStyle.Normal().color = "#fff";
            itemStyle.normal.shadowBlur  = 10;
            itemStyle.normal.shadowColor = "#333";

            option.series = new List <object>()
            {
                #region series #1: 全部 data
                new Map()
                {
                    name             = "Sales ($)",
                    type             = ChartType.scatter,
                    coordinateSystem = CoordinateSystemType.gmap,
                    data             = new ModelEx.ChartsData_GMap().DataSet1,
                    label            = new Forms.Model.ECharts.style.StyleLabel()
                    {
                        formatter = "{b}",
                        position  = StyleLabelType.right,
                        show      = true
                    },
                    itemStyle = new Forms.Model.ECharts.style.ItemStyle()
                    {
                        normal = new Forms.Model.ECharts.style.Normal()
                        {
                            color = "Blue"   // 可以用 hex 或 color name
                        }
                    },
                    encode = new JRaw("{value: 2, lng: 0, lat: 1 }")    // 呢個次序要同 data 夾
                },
                #endregion
                #region series #2: Top 5 data
                new Map()
                {
                    name             = "Top 5",
                    type             = ChartType.effectScatter,
                    coordinateSystem = CoordinateSystemType.gmap,
                    data             = new ModelEx.ChartsData_GMap().DataSet2, //! 排序 & 選出 top 5
                    label            = new Forms.Model.ECharts.style.StyleLabel()
                    {
                        formatter = "{b}",
                        position  = StyleLabelType.right,
                        show      = true
                    },
                    itemStyle = new Forms.Model.ECharts.style.ItemStyle()
                    {   //! HACK: 改 normal 啲 params 係有反應嘅,不過就唔知幾時會用到 emphasis?
                        normal = new Forms.Model.ECharts.style.Normal()
                        {
                            color       = "red",
                            shadowBlur  = 10,
                            shadowColor = "#333",
                        },
                        emphasis = new Forms.Model.ECharts.style.Emphasis()
                        {
                            color       = "#fff",
                            shadowBlur  = 10,
                            shadowColor = "#333",
                        }
                    },
                    effectScatter = new EffectScatter()
                    {
                        showEffectOn = ShowEffectType.render,
                        rippleEffect = new RippleEffect()
                        {
                            brushType = BrushType.stroke
                        }
                    },
                    encode = new JRaw("{value: 2, lng: 0, lat: 1 }"),
                    zlevel = 1
                }
                #endregion
            };
            #endregion

            result = JsonHelper.ObjectToJson2(option);

            return(result);
        }
예제 #30
0
        public static void GenerateMultiPaneGraph(string[] symbols, DateTime[] dateTimes, DenseMatrix data, string filename, ChartOption[] options = null, HighstockFlag[] flags = null, string JSONFILENAME = "temp.json")
        {
            //Set default options
            if (ReferenceEquals(null, options) || options.Length != symbols.Length)
            {
                options = new ChartOption[symbols.Length];
                for (int i = 0; i < symbols.Length; i++)
                {
                    options[i] = new ChartOption()
                    {
                        ChartType = "spline", Height = 200, YPosition = i
                    };
                }
            }

            WriteDataToJson(symbols, dateTimes, data, JSONFILENAME);

            StringBuilder GraphJSBuilder = new StringBuilder();

            GraphJSBuilder.Append(@"<script type='text/javascript'>                             " + "\n");
            GraphJSBuilder.Append(@"$(function() {                                              " + "\n");
            GraphJSBuilder.Append(@"	$.getJSON('"+ JSONFILENAME + "', function(data) {                 " + "\n");

            //add ohlc data (first 4 values)
            GraphJSBuilder.Append("var ohlc =[];" + "\n");

            for (int i = 1; i < symbols.Length; i++)
            {
                GraphJSBuilder.Append("var " + "symbol" + i + "=[];" + "\n");
            }

            GraphJSBuilder.Append(@"dataLength = data.length;" + "\n");
            GraphJSBuilder.Append(@"for (i = 0; i < dataLength; i++) { " + "\n");
            for (int i = 1; i < symbols.Length; i++)
            {
                GraphJSBuilder.Append(@"ohlc.push([ data[i][0], data[i][1], data[i][2], data[i][3], data[i][4] ]);" + "\n"); //ohlc
                GraphJSBuilder.Append(@"symbol" + i + ".push([ data[i][0],data[i][" + (i + 4) + "]]);" + "\n");              //push indicator data
            }
            GraphJSBuilder.Append(@"}" + "\n");
            GraphJSBuilder.Append(@"      var groupingUnits = [                           " + "\n");
            GraphJSBuilder.Append(@"            ['hour', [1,2,3] ],                       " + "\n");
            GraphJSBuilder.Append(@"            ['day',  [1,2,3] ],                       " + "\n");
            GraphJSBuilder.Append(@"            ['week', [1,2]   ],                       " + "\n");
            GraphJSBuilder.Append(@"            ['month',[1]     ]];                      " + "\n");
            GraphJSBuilder.Append(@"		$('#container').highcharts('StockChart', {    "+ "\n");
            GraphJSBuilder.Append(@"		    rangeSelector: {selected: 1  },           "+ "\n");
            GraphJSBuilder.Append(@"		    title: {  text: '"+ symbols[0] + "'},    " + "\n");
            GraphJSBuilder.Append(@"            legend: { enabled: true },                " + "\n");
            GraphJSBuilder.Append(@"            chart:{zoomType: 'x'},                    " + "\n");
            GraphJSBuilder.Append(@"            scrollbar: { enabled:false},              " + "\n");

            GraphJSBuilder.Append(" yAxis: [" + "\n");
            for (int i = 0; i < symbols.Length; i++)
            {
                double top = 70;
                //get height of element
                for (int j = 0; j < i; j++)
                {
                    top += options[j].Height + 10;
                }

                GraphJSBuilder.Append(
                    "{" +
                    (!options[i].Layover?"title: {text: '" + symbols[i] + "'}, ":"") +
                    "height:" + options[i].Height + ", " +
                    ((i == 0) ? "" : "top:" + top + ",") +
                    "lineWidth:2, " +
                    "offset:0" +
                    "}" +
                    ((i == symbols.Length - 1) ? "" : ",") + "\n");
            }
            GraphJSBuilder.Append(@"]," + "\n");

            //Add Series Data----------------------
            GraphJSBuilder.Append(@"series: [" + "\n");

            //ohlc
            GraphJSBuilder.Append(
                "{" +
                "type: 'candlestick'," +
                "name: '" + symbols[0] + "', " +
                "id: '" + symbols[0] + "', " +
                "data: ohlc," +
                "dataGroup:{units:groupingUnits}" +
                "}," + "\n");

            //indicator
            for (int i = 1; i < symbols.Length; i++)
            {
                GraphJSBuilder.Append(
                    "{" +
                    "type: '" + options[i].ChartType + "'," +
                    "name: '" + symbols[i] + "', " +
                    "id: '" + symbols[i] + "', " +
                    "data:symbol" + i + "," +
                    "yAxis:" + options[i].YPosition + "," +
                    "dataGroup:{units:groupingUnits}" +
                    "}" + ((i == symbols.Length - 1) ? "" : ",") + "\n");
            }

            if (flags != null)
            {
                //add flags------------
                GraphJSBuilder.Append(
                    ",{" +
                    "type : 'flags'," +
                    "data : [");

                if (!ReferenceEquals(null, flags))
                {
                    for (int i = 0; i < flags.Length; i++)
                    {
                        GraphJSBuilder.Append(
                            "{" +
                            "x : Date.UTC(" + flags[i].Date.Year + "," + (flags[i].Date.Month - 1) + "," +
                            flags[i].Date.Day + "," +
                            flags[i].Date.Hour + "," + flags[i].Date.Minute + ")," +
                            "title : '" + flags[i].Title + "'," +
                            "text : '" + flags[i].Text + "'" +
                            "}" + ((i == flags.Length - 1) ? "" : ",") + "\n"
                            );
                    }
                }

                GraphJSBuilder.Append(
                    "]," +
                    "onSeries : '" + symbols[0] + "'," +
                    "shape : 'squarepin'," +
                    "width : 9," +
                    "height: 10," +
                    "stickyTracking: false," +
                    "style: {fontSize:'9px',fontWeight: 'normal'}" +
                    "}"
                    );

                //endflags---------------------
            }

            GraphJSBuilder.Append(@"]" + "\n");
            //endseries-------------------------------------


            //calculate height
            double height = 170;

            for (int i = 0; i < options.Length; i++)
            {
                height += options[i].Height + ((options[i].Height > 0)? 20:0);
            }

            GraphJSBuilder.Append(@"});});});   " + "\n");
            GraphJSBuilder.Append(@"</script>     " + "\n");
            GraphJSBuilder.Append(@"<div id='container' style='height:" + height + "; width:90%; margin: 0 auto'></div>");



            using (var file = new StreamWriter(@filename))
            {
                file.WriteLine("<html><head>");
                foreach (string s in HighStocksIncludes)
                {
                    file.WriteLine(s);
                }
                file.WriteLine("</head><body>");
                file.WriteLine(GraphJSBuilder.ToString());
                file.WriteLine("<script src=\"style.js\"></script>");
                file.WriteLine("</body></html>");
            }
        }
예제 #31
0
        public Dictionary <string, BatchReport> GetBatchReport(string[] symbols, IEnumerable <IEXDataType> types, ChartOption range, int itemCount, Period period = Period.Annual)
        {
            string rangeStr       = range.ToString().StartsWith("_") ? range.ToString().Remove(0, 1) : range.ToString();
            string baseRequestUri = GetIEXBaseRequestUri(IEXRequestType.BatchReportMarketForMultiStocks);
            string requestUrl     = string.Format(
                baseRequestUri,
                symbols.ToStringDelimeter(),
                types.ToStringDelimeter(),
                rangeStr,
                itemCount.LimitToMax());

            if (types.Contains(IEXDataType.financials))
            {
                requestUrl = requestUrl + $"&period={period}";
            }
            requestUrl = requestUrl.ToLower();
            Console.WriteLine(requestUrl);

            string jsonstring = base.GetString(requestUrl.ToLower()).Result;

            return(SerializerHandler.DeserializeObj <Dictionary <string, BatchReport> >(jsonstring));
        }
예제 #32
0
        public static void TestChannel(this AbstractChannel ind, string filename, int length)
        {
            Quantum q = Quantum.ExcelToQuantum(filename, "symbol", 0);

            var dz = new DenseMatrix(4 + 3, q.Data.Count);

            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add("HIGH");
            names.Add(ind.ToString());
            names.Add("LOW");

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 500, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };
            chartOptions[2] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };
            chartOptions[3] = new ChartOption()
            {
                Height = 0, YPosition = 0, Layover = true
            };

            int counter = 0;

            foreach (Tick tick in q)
            {
                ind.HandleNextTick(tick);
                dz[0, counter] = tick.BidOpen;
                dz[1, counter] = tick.BidHigh;
                dz[2, counter] = tick.BidLow;
                dz[3, counter] = tick.BidClose;
                dz[4, counter] = ind.HI(0);
                dz[5, counter] = ind.MID(0);
                dz[6, counter] = ind.LOW(0);

                counter++;
            }

            Visualize.GenerateMultiPaneGraph(new[] { "data", "high", ind.ToString(), "low" }, q.Data.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html"
                                             , new ChartOption[]
            {
                new ChartOption()
                {
                    Height = 500
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                },
                new ChartOption()
                {
                    Height = 0, Layover = true, YPosition = 0
                }
            });

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }
예제 #33
0
        public static void TestMultiSymbolGraph(this AbstractMultiSymbolIndicator ind, string[] filename, int length)
        {
            List <Quantum> lq = new List <Quantum>();

            foreach (string s in filename)
            {
                lq.Add(Quantum.ExcelToQuantum(s, s, 0));
            }
            MultiQuantum multiQuantum = MultiQuantum.OrganizeMultiQuantum(lq);


            var           dz    = new DenseMatrix(4 + 1 + ind.SubIndicatorSize, multiQuantum.Length);
            List <string> names = new List <string>();

            names.Add("symbol");
            names.Add(ind.ToString());
            foreach (var indicator in ind.SubIndicators)
            {
                names.Add(indicator.Key);
            }

            //chartoptions
            ChartOption[] chartOptions = new ChartOption[names.Count];
            chartOptions[0] = new ChartOption()
            {
                Height = 400, YPosition = 0
            };
            chartOptions[1] = new ChartOption()
            {
                Height = 200, YPosition = 1
            };
            for (int i = 2; i < chartOptions.Length; i++)
            {
                chartOptions[i] = new ChartOption()
                {
                    Height = 0, YPosition = 1, Layover = true
                }
            }
            ;

            int counter = 0;

            foreach (List <Tick> t in multiQuantum)
            {
                dz[0, counter] = t[0].BidOpen;
                dz[1, counter] = t[0].BidHigh;
                dz[2, counter] = t[0].BidLow;
                dz[3, counter] = t[0].BidClose;

                dz[4, counter] = ind.HandleNextTicks(t.ToArray());

                int icounter = 5;
                foreach (var subind in ind.SubIndicators.Values)
                {
                    dz[icounter, counter] = subind[0];
                    icounter++;
                }

                counter++;
            }


            Visualize.GenerateMultiPaneGraph(names.ToArray(), multiQuantum.Keys.ToArray(), dz, QSConstants.DEFAULT_DATA_FILEPATH + @"results.html",
                                             chartOptions);

            Console.WriteLine("Done Generating Graph for " + ind.ToString());
        }