private void FindMinDelta() { // find the smallest difference between any two dates - this will give us the major and minor unit components // since values are sorted, all we need to do is loop the list once and compare two adjacent values this.minDelta = TimeSpan.Zero; int count = this.values.Count; DateTimePoint prevPoint = null; for (int i = 0; i < count; i++) { DateTimePoint point = this.values[i]; if (prevPoint != null && prevPoint.Date != point.Date) { TimeSpan diff = point.Date - prevPoint.Date; if (diff < this.minDelta || this.minDelta == TimeSpan.Zero) { this.minDelta = diff; } } prevPoint = point; } // min delta will not be initialized if only one point is present in the chart if (this.minDelta == TimeSpan.Zero) { this.minDelta = new TimeSpan(this.values[0].Date.Ticks); } }
private void TransferToChartValuesHelper( List <PacketInfo> packetInfo, GearedValues <DateTimePoint> packetLengthChartValues, GearedValues <ObservablePoint> timeDiffChartValues, PacketInfoWrapper prevPacketInfoWrapper) { int timeDiffStartOffset = timeDiffChartValues.Count; List <DateTimePoint> dateTimePoints = new List <DateTimePoint>(); List <ObservablePoint> timeDiffPoints = new List <ObservablePoint>(); foreach (PacketInfo p in packetInfo) { DateTimePoint dtp = new DateTimePoint(p.time, p.length); dateTimePoints.Add(dtp); if (prevPacketInfoWrapper.p != null) { int diffMs = (int)(p.time - prevPacketInfoWrapper.p.time).TotalMilliseconds; ObservablePoint point = new ObservablePoint(timeDiffPoints.Count + timeDiffStartOffset, diffMs); timeDiffPoints.Add(point); } prevPacketInfoWrapper.p = p; } packetInfo.Clear(); packetLengthChartValues.AddRange(dateTimePoints); timeDiffChartValues.AddRange(timeDiffPoints); }
private void pingable_PingCompleted(object sender, PingCompletedEventArgs e) { Application.Current.Dispatcher.Invoke(() => { var reply = e.Reply; var point = new DateTimePoint(DateTime.Now, reply.RoundtripTime); if (reply.Status == IPStatus.Success) { Status += $"{point.DateTime.ToString("HH:mm:ss")} - ping pong\n"; SeriesCollection[0].Values.Add(point); _success.Add(true); } else { Status += $"{point.DateTime.ToString("HH:mm:ss.")} - fail! {reply.Status}\n"; SeriesCollection[1].Values.Add(point); _success.Add(false); } if (_success.Count > Math.Max(3600000 / Config.Interval, 3600)) { var index = _success[0] ? 0 : 1; SeriesCollection[index].Values.RemoveAt(0); _success.RemoveAt(0); AxisMin = ((DateTimePoint)SeriesCollection[index].Values[0]).DateTime.AddSeconds(-5).Ticks; Notify("AxisMin"); } AxisMax = point.DateTime.AddSeconds(1).Ticks; Notify("AxisMax"); Notify("Status"); }); }
private async Task <ChartValues <DateTimePoint> > GetData() { string _api_function = api_function.Text; string _api_stock_symbol = api_stock_symbol.Text; string _api_output_size = api_output_size.Text; string urlParameters = string.Format("query?function={0}&symbol={1}&outputsize={2}&apikey=WPR105SZICA1KKXP", _api_function, _api_stock_symbol, _api_output_size); Dictionary <string, Dictionary <string, string> > price = await GetData_API.RunAsync(client, urlParameters); int size = price.Count; var array = new DateTimePoint[size]; var values = new ChartValues <DateTimePoint>(); int i = 0; foreach (KeyValuePair <string, Dictionary <string, string> > entry in price) { DateTime datetime = DateTime.Parse(entry.Key); Double price_close = Convert.ToDouble(entry.Value["4. close"]); array[i] = new DateTimePoint(datetime, price_close); i += 1; } Array.Reverse(array); values.AddRange(array); return(values); }
/// <summary> /// Create a new chart data point /// </summary> /// <param name="minerPaymentsGroupedByDay"></param> /// <returns></returns> private DateTimePoint CreateChartDataPoint(MinerPaymentsGroupedByDay minerPaymentsGroupedByDay) { DateTimePoint dateTimePoint = new DateTimePoint(); dateTimePoint.Value = (double)minerPaymentsGroupedByDay.PaymentAmountFiat; dateTimePoint.DateTime = new DateTime(minerPaymentsGroupedByDay.PaymentDate.Year, minerPaymentsGroupedByDay.PaymentDate.Month, minerPaymentsGroupedByDay.PaymentDate.Day); return(dateTimePoint); }
/// <summary> /// Create chart series for each coin /// </summary> private void PlotPaymentChart() { try { // Exit if no fiat currency is selected if (Application.Current.Properties["Currency"] == null) { return; } // New list of strings used for labels when plotting the chart List <string> labels = new List <string>(); // New collection of series seriesCollection = new SeriesCollection(); foreach (MinerPaymentSummary MinerPaymentSummary in MinerPaymentsData.MinerPaymentSummaryList) { StackedAreaSeries stackedColumnSeries = new StackedAreaSeries(); ChartValues <DateTimePoint> chartValues = new ChartValues <DateTimePoint>(); // Format series fill, stroke, etc FormatChartSeries(MinerPaymentSummary, stackedColumnSeries); // Iterate through each day and add a chart point foreach (MinerPaymentsGroupedByDay minerPaymentsGroupedByDay in MinerPaymentSummary.MinerPaymentsGroupedByDayList.Where(x => x.PaymentDate >= DateTime.Now.AddDays(-30)).OrderByDescending(y => y.PaymentDate)) { DateTimePoint dateTimePoint = CreateChartDataPoint(minerPaymentsGroupedByDay); chartValues.Add(dateTimePoint); } // Add coin symbol to labels to show up in the UI labels.Add(MinerPaymentSummary.CoinType.ToString()); // Add 0 values for any dates with no payments in order to render the chart properly PaymentChartDataBackFill paymentChartDataBackFill = new PaymentChartDataBackFill(); stackedColumnSeries.Values = paymentChartDataBackFill.BackFillList(chartValues); seriesCollection.Add(stackedColumnSeries); } // Add a line series for the Total Line seriesCollection.Add(this.AddTotalLineSeries()); // Axis label formats XFormatter = val => new DateTime((long)val).ToShortDateString(); YFormatter = val => String.Format("{0} {1}", Math.Round(val, 4).ToString(), Application.Current.Properties["Currency"].ToString()); // Rebind UI OnPropertyChanged("SeriesCollection"); OnPropertyChanged("XFormatter"); OnPropertyChanged("YFormatter"); } catch (Exception e) { ShowError(String.Format("{0} {1}", "Error plotting payment chart", e.Message)); } }
private void BuildTimeSlots() { // TODO: We should build time slots for all the points, not just the ones within the plot range ValueRange <DateTime> autoRange = this.GetAutoRange(); decimal startTicks = autoRange.minimum.Ticks; decimal endTicks = autoRange.maximum.Ticks; if (startTicks == endTicks) { this.BuildSingleTimeSlot(); return; } int pointCount = this.values.Count; int pointIndex = 0; decimal currentTicks = startTicks; decimal nextTicks; while (currentTicks <= endTicks) { nextTicks = this.GetNextTicks(currentTicks, 1); if (pointIndex < pointCount) { DateTimePoint point = this.values[pointIndex]; // value falls within the slot if (point.Date.Ticks < nextTicks) { TimeSlot slot = new TimeSlot() { StartTicks = currentTicks, Ticks = nextTicks - currentTicks }; point.Slot = slot; // move to next point index pointIndex++; while (pointIndex < pointCount) { DateTimePoint nextPoint = this.values[pointIndex]; if (nextPoint.Date.Ticks >= nextTicks) { break; } nextPoint.Slot = slot; pointIndex++; slot.PointCount++; } } } currentTicks = nextTicks; } }
private void ClientMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) { var str = Encoding.Default.GetString(e.Message); var observation = JsonConvert.DeserializeObject <Observation>(str); var lPhenomenonTime = observation.GetPhenomenonTime(true).Value; var newpoint = new DateTimePoint(lPhenomenonTime, (double)observation.Result); Dispatcher.Invoke(() => { SeriesCollection[0].Values.Add(newpoint); }); }
/// <summary> /// Calculate the total payment amount for each day and create a total line series to plot /// </summary> /// <returns></returns> private LineSeries AddTotalLineSeries() { LineSeries totalLineSeries = new LineSeries(); ChartValues <DateTimePoint> chartValues = new ChartValues <DateTimePoint>(); // Group payments by date and get sum of all fiat payment amounts List <MinerPaymentsGroupedByDay> result = profitabilityData.MinerPaymentsGroupedByDayUnionedList .GroupBy(l => l.PaymentDateTicks) .Select(cl => new MinerPaymentsGroupedByDay { PaymentDateTicks = cl.First().PaymentDateTicks, PaymentAmountFiat = cl.Sum(c => c.PaymentAmountFiat) }).ToList(); // Iterate through each date and add new data points to the line series foreach (MinerPaymentsGroupedByDay minerPaymentsGroupedByDay in result) { DateTimePoint dateTimePoint = new DateTimePoint(); dateTimePoint.DateTime = minerPaymentsGroupedByDay.PaymentDate; dateTimePoint.Value = Convert.ToDouble(minerPaymentsGroupedByDay.PaymentAmountFiat); chartValues.Add(dateTimePoint); } PaymentChartDataBackFill paymentChartDataBackFill = new PaymentChartDataBackFill(); totalLineSeries.Values = paymentChartDataBackFill.BackFillList(chartValues); // Format series var converter = new System.Windows.Media.BrushConverter(); Brush brushStroke = (Brush)converter.ConvertFromString("#FFFFFF"); brushStroke.Opacity = 0; totalLineSeries.Title = "TOTAL"; totalLineSeries.LineSmoothness = 0.7; totalLineSeries.PointGeometrySize = 0; totalLineSeries.Stroke = brushStroke; totalLineSeries.StrokeThickness = 0; return(totalLineSeries); }
private void BuildValues(AxisUpdateContext context) { this.values.Clear(); if (context.Series == null) { return; } AxisPlotDirection direction = this.type == AxisType.First ? AxisPlotDirection.Vertical : AxisPlotDirection.Horizontal; foreach (ChartSeriesModel series in context.Series) { // tell each series what is the plot direction series.SetValue(AxisModel.PlotDirectionPropertyKey, direction); if (!series.presenter.IsVisible) { continue; } foreach (DataPoint point in series.DataPointsInternal) { object value = point.GetValueForAxis(this); DateTime date; if (!DateTimeHelper.TryGetDateTime(value, out date)) { continue; } DateTimePoint datePoint = new DateTimePoint() { Point = point, Date = date }; this.values.Add(datePoint); } } // sort all the values chronologically this.values.Sort(); }
//добафить новую запись в график public void AddNewRecordFromInput(DateTime date, double value) { mainChart.Dispatcher.BeginInvoke(new Action(delegate() { DateTimePoint newTimePoint = new DateTimePoint(date, value); try { DateTimePoint exisitingTimePoint = _temperatureLineSeriesValues.First(d => d.DateTime == newTimePoint.DateTime); if (exisitingTimePoint != null) { _temperatureLineSeriesValues.Remove(exisitingTimePoint); } } catch (Exception) { } _temperatureLineSeriesValues.Add(newTimePoint); RefreshChart(); })); }
/// <summary> /// Identify and missing data points and add a new ZERO datapoint using the appropriate datetime /// </summary> /// <param name="list"></param> /// <returns></returns> private ChartValues <DateTimePoint> GetListAllDates(ChartValues <DateTimePoint> list) { DateTime tmpInterval = RoundDown(DateTime.UtcNow.ToLocalTime().Subtract(TimeSpan.FromDays(datePointTimeWindow - datePointTimeIntervalDays)), TimeSpan.FromDays(datePointTimeIntervalDays)); var upperBound = DateTime.UtcNow.ToLocalTime(); while (tmpInterval <= upperBound) { if (list.Any(x => RoundDown(x.DateTime, TimeSpan.FromDays(datePointTimeIntervalDays)) == tmpInterval) == false) { DateTimePoint dateTimePoint = new DateTimePoint { Value = 0, DateTime = tmpInterval }; list.Add(dateTimePoint); } tmpInterval = tmpInterval.Add(TimeSpan.FromDays(datePointTimeIntervalDays)); } ; return(list); }
private async void LoadData() { var client = new SensorThingsClient(serverurl); var response = await client.GetDatastream(datastreamid); var datastream = response.Result; var observationsResponse = await datastream.GetObservations(client); var observations = observationsResponse.Result; var obs = observations.Items.OrderBy(m => m.PhenomenonTime.Start); foreach (var observation in obs) { var lPhenomenonTime = observation.GetPhenomenonTime(true).Value; var res = Convert.ToDouble(observation.Result); var newpoint = new DateTimePoint(lPhenomenonTime, res); Dispatcher.Invoke(() => { SeriesCollection[0].Values.Add(newpoint); }); } }
/// <summary> /// Load list of miner monitor stats /// </summary> public void InitMonitorMining24Hour() { try { if (Application.Current.Properties["AccountID"] != null && WorkerName != null) { // Load list of miner monitor stats MinerMonitorStatsAPI minerMonitorStatsAPI = new MinerMonitorStatsAPI(); MinerMonitorStatList24Hour = minerMonitorStatsAPI.GetMinerMonitorStats24Hour(); // LineChart data ChartValuesHashRate = new ChartValues <DateTimePoint>(); ChartValuesPower = new ChartValues <DateTimePoint>(); // Filter list by worker List <MinerMonitorStat> MinerMonitorStatListFiltered = new List <MinerMonitorStat>(); MinerMonitorStatListFiltered = MinerMonitorStatList24Hour.Where(x => x.WorkerName == WorkerName && x.CoinType == CoinType).OrderBy(y => y.Created).ToList(); // Calculate average values and display if (MinerMonitorStatListFiltered.Count > 0) { Calculate24HourAverageHashrate(MinerMonitorStatListFiltered); Calculate24HourAveragePower(MinerMonitorStatListFiltered); } else { Hashrate24HourAverage = "0"; Power24HourAverage = "0"; } // Populate series to be graphed foreach (MinerMonitorStat minerMonitorStat in MinerMonitorStatListFiltered) { DateTimePoint dateTimePoint = new DateTimePoint(); // HashRate dateTimePoint.DateTime = minerMonitorStat.Created.ToLocalTime(); dateTimePoint.Value = HashrateFormatter.FormatNumeric(minerMonitorStat.CoinType, minerMonitorStat.HashRate); ChartValuesHashRate.Add(dateTimePoint); // Power DateTimePoint dateTimePointPower = new DateTimePoint(); dateTimePointPower.DateTime = minerMonitorStat.Created.ToLocalTime(); dateTimePointPower.Value = minerMonitorStat.Power; ChartValuesPower.Add(dateTimePointPower); } // Backfill lists as needed WorkerChartDataBackFill chartDataBackFill = new WorkerChartDataBackFill(); ChartValuesHashRate = chartDataBackFill.BackFillList(ChartValuesHashRate); ChartValuesPower = chartDataBackFill.BackFillList(ChartValuesPower); // Axis label formats XFormatter = val => new DateTime((long)val).ToString(); YFormatter = val => val.ToString(); // Notify UI of change OnPropertyChanged("ChartValuesHashRate"); OnPropertyChanged("ChartValuesPower"); } } catch (Exception e) { ShowError(string.Format("Error loading monitor data: {0}", e.Message)); } }
private Dictionary <string, object> CodigoDeAdomd2DimensionSA(string query) { Dictionary <string, object> resultado = new Dictionary <string, object>(); AdomdConnection con = new AdomdConnection("Data Source=DESKTOP-MF82JHU;catalog=FullOlapCube"); con.Open(); AdomdCommand cmd = new AdomdCommand(query, con); CellSet cs = cmd.ExecuteCellSet(); TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples; Microsoft.AnalysisServices.AdomdClient.Tuple tp = cs.Axes[1].Set.Tuples[1]; string tituloX = tp.Members[0].ParentLevel.Caption; string tituloY = ""; foreach (Microsoft.AnalysisServices.AdomdClient.Tuple column in tuplesOnColumns) { tituloY = column.Members[0].Caption; } TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples; //List<string> listaNombres = new List<string>(); //List<double> listaValores = new List<double>(); int row = 0; int rowAux = 0; List <LineSeries> seriesList = new List <LineSeries>(); List <string> seriesLabel = new List <string>(); //Convert cvv = new Convert(); while (row < tuplesOnRows.Count) { string firstCategory = tuplesOnRows[rowAux].Members[0].Caption; StackedAreaSeries ls = new StackedAreaSeries(); ls.Title = firstCategory; ChartValues <DateTimePoint> cv = new ChartValues <DateTimePoint>(); while (tuplesOnRows[row].Members[0].Caption == firstCategory) { //for (int members = 0; members < tuplesOnRows[row].Members.Count; members++) //{ DateTimePoint dtp = new DateTimePoint(); dtp.DateTime = new DateTime(Convert.ToInt32(tuplesOnRows[row].Members[1].Caption), 1, 1); seriesLabel.Add(tuplesOnRows[row].Members[1].Caption); //} for (int col = 0; col < tuplesOnColumns.Count; col++) { dtp.Value = Convert.ToDouble(cs.Cells[col, row].FormattedValue); cv.Add(dtp); //listaValores.Add(Convert.ToDouble(cs.Cells[col, row].FormattedValue)); } row++; if (row == tuplesOnRows.Count) { break; } } ls.Values = cv; rowAux = row; seriesList.Add(ls); } con.Close(); resultado.Add("listaNombres", seriesLabel); resultado.Add("listaValores", seriesList); resultado.Add("tituloX", tituloX); resultado.Add("tituloY", tituloY); return(resultado); }
private async void UpdateData_Click(object sender, RoutedEventArgs e) { ChartValues <DateTimePoint> _values = await GetData(); // calc high point double VQ = 9.10; // VTI volatility, % int count = _values.Count; var array_high = new DateTimePoint[count]; var array_mid_warning = new DateTimePoint[count]; var array_low = new DateTimePoint[count]; var high_point = _values[0].Value; array_high[0] = new DateTimePoint(_values[0].DateTime, high_point); array_mid_warning[0] = new DateTimePoint(_values[0].DateTime, high_point * (1 - VQ / 100 / 2)); array_low[0] = new DateTimePoint(_values[0].DateTime, high_point * (1 - VQ / 100)); for (var i = 1; i <= count - 1; i++) { if (_values[i].Value >= high_point) { high_point = _values[i].Value; } else if (high_point * (1 - VQ / 100) >= _values[i].Value) // later time price is lower than the previous price ... _values[i + 1].Value < _values[i].Value { high_point = _values[i].Value; } array_high[i] = new DateTimePoint(_values[i].DateTime, high_point); array_mid_warning[i] = new DateTimePoint(_values[i].DateTime, high_point * (1 - VQ / 100 / 2)); array_low[i] = new DateTimePoint(_values[i].DateTime, high_point * (1 - VQ / 100)); } var values_high = new ChartValues <DateTimePoint>(); var values_mid = new ChartValues <DateTimePoint>(); var values_low = new ChartValues <DateTimePoint>(); values_high.AddRange(array_high); values_mid.AddRange(array_mid_warning); values_low.AddRange(array_low); SeriesCollection = new SeriesCollection { new LineSeries { Title = "Highest Price", Values = values_high, Fill = Brushes.Green, Stroke = Brushes.Green, LineSmoothness = 0, StrokeThickness = 1, PointGeometrySize = 0 }, new LineSeries { Title = "Mid Price (Warning)", Values = values_mid, Fill = Brushes.Yellow, Stroke = Brushes.Yellow, LineSmoothness = 0, StrokeThickness = 1, PointGeometrySize = 0 }, new LineSeries { Title = "Trailing Stop", Values = values_low, //Fill = Brushes.Red, Stroke = Brushes.Red, LineSmoothness = 0, StrokeThickness = 1, PointGeometrySize = 0 }, new LineSeries { Title = "close price", Values = _values, //Fill = Brushes.Yellow, Stroke = Brushes.White, LineSmoothness = 0, StrokeThickness = 3, PointGeometrySize = 0, }, }; ZoomingMode = ZoomingOptions.X; XFormatter = val => new DateTime((long)val).ToString("yy-MM-dd"); YFormatter = val => val.ToString("C"); DataContext = this; }