private void FormDailySummary_Load(object sender, EventArgs e)
        {
            using (MyMiniTradingSystemContext context = new MyMiniTradingSystemContext())
            {
                var groupQuery =
                    from data in context.DailySummarys
                    where data.UserCode == DefaultUserCode
                    group data by data.PositionCommodityCode;

                foreach (var group in groupQuery)
                {
                    this.cboItem.Items.Add(group.Key);
                }



                var dateQuery =
                    from data in context.DailySummarys
                    where
                    data.UserCode == DefaultUserCode
                    orderby
                    data.DailySummaryDate
                    select data;

                DailySummary firstData = dateQuery.FirstOrDefault();
                if (firstData != null)
                {
                    this.dtpStart.Value   = firstData.DailySummaryDate;
                    this.dtpStart.MinDate = firstData.DailySummaryDate;
                }

                this.dtpFinish.Value   = DateTime.Today;
                this.dtpFinish.MaxDate = DateTime.Today;
            }
        }
Beispiel #2
0
 public void DailySummaryEmail()
 {
     using (Service = new EmailService())
     {
         DailySummary _summary = new DailySummary();
     }
 }
        public ActionResult GetBestCriteria(string CriteriaValue)
        {
            List <DailySummary> BestCriteria = new List <DailySummary>();

            using (TAS2013Entities dc = new TAS2013Entities())
            {
                DateTime To                = (DateTime)dc.DailySummaries.Max(x => x.Date);
                DateTime From              = To.AddDays(-20);
                var      GetSummaries      = dc.DailySummaries.Where(aa => aa.Criteria == CriteriaValue && (aa.Date >= From && aa.Date <= To)).ToList();
                var      DistinctCriterias = GetSummaries.Select(aa => new { aa.CriteriaValue }).Distinct().ToList();
                foreach (var distinctcriteria in DistinctCriterias)
                {
                    DailySummary gatherinfo = new DailySummary();

                    List <DailySummary> intermediate = GetSummaries.Where(aa => aa.CriteriaValue == distinctcriteria.CriteriaValue).ToList();
                    gatherinfo = InitializeDailySummaryValues(intermediate);

                    foreach (DailySummary inter in intermediate)
                    {
                        gatherinfo = AddValues(gatherinfo, inter);
                    }
                    BestCriteria.Add(gatherinfo);
                }
            }
            Console.Write(CriteriaValue);
            return(Json(BestCriteria, JsonRequestBehavior.AllowGet));
        }
        public static void TestBody_RecipientInterrupted()
        {
            var recipient = Create.User("Pierre-Emerick Aubameyang");

            var allocatedUsers   = Create.Users("Petr Čech", "Héctor Bellerín");
            var interruptedUsers = Create.Users("Sokratis Papastathopoulos", "Mohamed Elneny").Concat(new[] { recipient });

            var allUsers = allocatedUsers.Concat(interruptedUsers);

            var allocations = Create.Allocations(allocatedUsers, default(LocalDate));
            var requests    = Create.Requests(allUsers, default(LocalDate));

            var email = new DailySummary(recipient, allocations, requests);

            Assert.All(allocatedUsers, a => email.HtmlBody.Contains(a.FullName, StringComparison.InvariantCulture));
            Assert.All(allocatedUsers, a => email.PlainTextBody.Contains(a.FullName, StringComparison.InvariantCulture));

            const string ExpectedHtmlInterruptedText =
                "(Interrupted: <strong>Pierre-Emerick Aubameyang</strong>, Mohamed Elneny, Sokratis Papastathopoulos)";
            const string ExpectedPlainInterruptedText =
                "(Interrupted: *Pierre-Emerick Aubameyang*, Mohamed Elneny, Sokratis Papastathopoulos)";

            Assert.True(email.HtmlBody.Contains(ExpectedHtmlInterruptedText, StringComparison.InvariantCulture));
            Assert.True(email.PlainTextBody.Contains(ExpectedPlainInterruptedText, StringComparison.InvariantCulture));
        }
Beispiel #5
0
        private void SummarizeData(Stock stock)
        {
            Eod lastEod = _summaryRepository.GetLastEod(stock.Symbol);

            if (lastEod == null)
            {
                return;
            }
            DailySummary lastSummary = _summaryRepository.GetLastSummary(stock.Symbol);

            if (lastSummary != null && lastEod.Date <= lastSummary.Date)
            {
                return;
            }

            //when extend, change code to DailyV002, DailyV003 and so on.
            var daily = new DailyV001();

            daily.Symbol = stock.Symbol;
            daily.Date   = lastEod.Date;
            var adx = _summaryRepository.GetADX(daily.Symbol, daily.Date);

            if (adx == null)
            {
                return;
            }
            daily.ADX14 = adx.ADX14;

            var sma = _summaryRepository.GetSMA(daily.Symbol, daily.Date);

            if (sma == null)
            {
                return;
            }
            daily.SMAShortTerm = sma.SMA5;
            daily.SMAMidTerm   = sma.SMA10;
            daily.SMALongTerm  = sma.SMA20;

            var rsi = _summaryRepository.GetRSI(daily.Symbol, daily.Date);

            if (rsi == null)
            {
                return;
            }
            daily.RSI14 = rsi.LastRSI;

            var rsiPredict = _summaryRepository.GetRSIPredict(daily.Symbol, daily.Date);

            if (rsiPredict == null)
            {
                return;
            }
            daily.R30Price = rsiPredict.PredictRsi30Price;
            daily.R70Price = rsiPredict.PredictRsi70Price;

            //todo
            daily.VolumePercentAgainstAvg = 0;

            _summaryRepository.SaveDailySummary(daily.ToDailySummary());
        }
        public void Create(DailySummaryBM dailySummary)
        {
            DailySummary dailySummaryDM = _mapper.Map <DailySummary> (dailySummary);

            _context.DailySummaries.Add(dailySummaryDM);
            _context.SaveChanges();
        }
Beispiel #7
0
        public void RiskExposureTest_AND2()
        {
            var configuration = new V1ExposureRiskCalculationConfiguration()
            {
                DailySummary_DaySummary_ScoreSum = new V1ExposureRiskCalculationConfiguration.Threshold()
                {
                    Op    = V1ExposureRiskCalculationConfiguration.Threshold.OPERATION_GREATER_EQUAL,
                    Value = 1170.0
                },
                ExposureWindow_ScanInstance_SecondsSinceLastScanSum = new V1ExposureRiskCalculationConfiguration.Threshold()
                {
                    Op    = V1ExposureRiskCalculationConfiguration.Threshold.OPERATION_GREATER_EQUAL,
                    Value = 900.0
                },
            };

            var dailySummary = new DailySummary()
            {
                DateMillisSinceEpoch = 0,
                DaySummary           = new ExposureSummaryData()
                {
                    ScoreSum = 1170.0
                },
                ConfirmedClinicalDiagnosisSummary = new ExposureSummaryData(),
                ConfirmedTestSummary = new ExposureSummaryData(),
                RecursiveSummary     = new ExposureSummaryData(),
                SelfReportedSummary  = new ExposureSummaryData()
            };

            var exposureWindows = new List <ExposureWindow>()
            {
                new ExposureWindow()
                {
                    CalibrationConfidence = CalibrationConfidence.High,
                    DateMillisSinceEpoch  = 0,
                    Infectiousness        = Infectiousness.High,
                    ReportType            = ReportType.Unknown,
                    ScanInstances         = new List <ScanInstance>()
                    {
                        new ScanInstance()
                        {
                            SecondsSinceLastScan = 600,
                            TypicalAttenuationDb = 1
                        },
                        new ScanInstance()
                        {
                            SecondsSinceLastScan = 240,
                            TypicalAttenuationDb = 10
                        }
                    }
                }
            };

            IExposureRiskCalculationService service = CreateService();

            RiskLevel result = service.CalcRiskLevel(dailySummary, exposureWindows, configuration);

            Assert.Equal(RiskLevel.Low, result);
        }
 public ActionResult GetGraphValues(string CriteriaValue)
 {
     using (TAS2013Entities dc = new TAS2013Entities())
     {
         DailySummary ds = dc.DailySummaries.Where(aa => aa.SummaryDateCriteria == CriteriaValue).FirstOrDefault();
         return(Json(ds, JsonRequestBehavior.AllowGet));
     }
 }
Beispiel #9
0
        public RiskLevel CalcRiskLevel(
            DailySummary dailySummary,
            List <ExposureWindow> exposureWindowList,
            V1ExposureRiskCalculationConfiguration configuration
            )
        {
            if (
                configuration.DailySummary_DaySummary_ScoreSum.Op == Threshold.OPERATION_NOP &&
                configuration.DailySummary_WeightedDurationAverage.Op == Threshold.OPERATION_NOP &&
                configuration.ExposureWindow_ScanInstance_SecondsSinceLastScanSum.Op == Threshold.OPERATION_NOP &&
                configuration.ExposureWindow_ScanInstance_TypicalAttenuationDb_Max.Op == Threshold.OPERATION_NOP &&
                configuration.ExposureWindow_ScanInstance_TypicalAttenuationDb_Min.Op == Threshold.OPERATION_NOP
                )
            {
                _loggerService.Info("All conditions are NOP.");
                return(RiskLevel.Low);
            }

            var allScanInstances = exposureWindowList
                                   .SelectMany(ew => ew.ScanInstances);

            double secondsSinceLastScanSum = allScanInstances
                                             .Sum(si => si.SecondsSinceLastScan);

            double weightedDurationAverage = 0;

            if (secondsSinceLastScanSum > 0)
            {
                weightedDurationAverage = dailySummary.DaySummary.WeightedDurationSum / secondsSinceLastScanSum;
            }

            double typicalAttenuationDbMax = 0;

            if (allScanInstances.Count() > 0)
            {
                typicalAttenuationDbMax = allScanInstances.Max(si => si.TypicalAttenuationDb);
            }

            double typicalAttenuationDbMin = 0;

            if (allScanInstances.Count() > 0)
            {
                typicalAttenuationDbMin = allScanInstances.Min(si => si.TypicalAttenuationDb);
            }

            // AND
            if (configuration.DailySummary_DaySummary_ScoreSum.Cond(dailySummary.DaySummary.ScoreSum) &&
                configuration.DailySummary_WeightedDurationAverage.Cond(weightedDurationAverage) &&
                configuration.ExposureWindow_ScanInstance_SecondsSinceLastScanSum.Cond(secondsSinceLastScanSum) &&
                configuration.ExposureWindow_ScanInstance_TypicalAttenuationDb_Max.Cond(typicalAttenuationDbMax) &&
                configuration.ExposureWindow_ScanInstance_TypicalAttenuationDb_Min.Cond(typicalAttenuationDbMin)
                )
            {
                return(RiskLevel.High);
            }

            return(RiskLevel.Low);
        }
        public void GetDataByAccount()
        {
            var result = App.Repository.Memo.GetDailySummaryByAccount(DateTime.Now);

            foreach (var r in result)
            {
                DailySummary.Add(r);
            }
        }
Beispiel #11
0
        public JsonCompatibleExposureDailySummary(DailySummary dailySummary)
        {
            Timestamp = dailySummary.Timestamp;
            Summary   = dailySummary.GetReport(ReportType.ConfirmedTest);
            Dictionary <ReportType, DailySummaryReport> summaryBasedOnReportType = new Dictionary <ReportType, DailySummaryReport>();

            summaryBasedOnReportType.Add(ReportType.ConfirmedTest, Summary);
            Reports = summaryBasedOnReportType;
        }
Beispiel #12
0
        //todo:make it generic
        public DailyV001 GetDailySummaryListForDate(string symbol, DateTime date)
        {
            DailySummary value = _context.GetDailySummary(symbol, date);

            if (value == null)
            {
                return(null);
            }
            return(EntityHelper.DeserializeFromXml <DailyV001>(value.Data));
        }
        public static void TestTo(string to)
        {
            var recipient = new ApplicationUser {
                Email = to
            };

            var email = new DailySummary(
                recipient, default(IReadOnlyList <Allocation>), default(IReadOnlyList <Request>));

            Assert.Equal(to, email.To);
        }
Beispiel #14
0
        public void RiskInDailySummaryAboveThreshold_ReturnsFalseWhenBelowConfiguredLimit(string locale)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);

            LocalPreferencesHelper.ScoreSumThreshold = 780;
            DailySummaryReport dailySummaryReport = new DailySummaryReport(0, 779, 0);
            DailySummary       dailySummary       = new DailySummary(SystemTime.Now(), dailySummaryReport,
                                                                     new Dictionary <ReportType, DailySummaryReport>());
            bool isAboveThreshold = ExposureDetectedHelper.RiskInDailySummaryAboveThreshold(dailySummary);

            Assert.False(isAboveThreshold);
        }
        public DailySummaryBM Get(DateTime CreatedDate)
        {
            DailySummary dailySummary = _context.DailySummaries
                                        .AsNoTracking()
                                        .FirstOrDefault(x => !x.DateDeleted.HasValue && x.DateCreated == CreatedDate);

            if (dailySummary == null)
            {
                return(null);
            }

            return(_mapper.Map <DailySummaryBM> (dailySummary));
        }
        public bool Remove(int id)
        {
            bool isEntityExists = _context.DailySummaries.Any(x => !x.DateDeleted.HasValue && x.Id == id);

            if (isEntityExists)
            {
                DailySummary dailySummary = _context.DailySummaries.First(x => x.Id == id);

                _context.DailySummaries.Remove(dailySummary);
                _context.SaveChanges();
            }

            return(isEntityExists);
        }
Beispiel #17
0
        public void RiskExposureTest_AllNOP()
        {
            var configuration = new V1ExposureRiskCalculationConfiguration()
            {
                // All conditions are NOP
            };

            var dailySummary = new DailySummary()
            {
                DateMillisSinceEpoch = 0,
                DaySummary           = new ExposureSummaryData()
                {
                    ScoreSum = 2000.0
                },
                ConfirmedClinicalDiagnosisSummary = new ExposureSummaryData(),
                ConfirmedTestSummary = new ExposureSummaryData(),
                RecursiveSummary     = new ExposureSummaryData(),
                SelfReportedSummary  = new ExposureSummaryData()
            };

            var exposureWindows = new List <ExposureWindow>()
            {
                new ExposureWindow()
                {
                    CalibrationConfidence = CalibrationConfidence.High,
                    DateMillisSinceEpoch  = 0,
                    Infectiousness        = Infectiousness.High,
                    ReportType            = ReportType.Unknown,
                    ScanInstances         = new List <ScanInstance>()
                    {
                        new ScanInstance()
                        {
                            SecondsSinceLastScan = 600,
                            TypicalAttenuationDb = 1
                        },
                        new ScanInstance()
                        {
                            SecondsSinceLastScan = 600,
                            TypicalAttenuationDb = 10
                        }
                    }
                }
            };

            IExposureRiskCalculationService service = CreateService();

            RiskLevel result = service.CalcRiskLevel(dailySummary, exposureWindows, configuration);

            Assert.Equal(RiskLevel.Low, result);
        }
Beispiel #18
0
        private void FormDailySummaryValue_Load(object sender, EventArgs e)
        {
            using (MyMiniTradingSystemContext context = new MyMiniTradingSystemContext())
            {
                var groupQuery =
                    from data in context.DailySummarys
                    where data.UserCode == DefaultUserCode
                    group data by data.PositionCommodityCode;

                foreach (var group in groupQuery)
                {
                    // Create a data series
                    Series series1 = new Series()
                    {
                        // 名称.
                        Name = group.Key,

                        // 类型.
                        ChartType = SeriesChartType.StackedArea,

                        // 显示数值.
                        IsValueShownAsLabel = true,
                    };

                    // Add series to the chart
                    this.chart1.Series.Add(series1);
                }



                var dateQuery =
                    from data in context.DailySummarys
                    where
                    data.UserCode == DefaultUserCode
                    orderby
                    data.DailySummaryDate
                    select data;

                DailySummary firstData = dateQuery.FirstOrDefault();
                if (firstData != null)
                {
                    this.dtpStart.Value   = firstData.DailySummaryDate;
                    this.dtpStart.MinDate = firstData.DailySummaryDate;
                }

                this.dtpFinish.Value   = DateTime.Today;
                this.dtpFinish.MaxDate = DateTime.Today;
            }
        }
        public ActionResult GetGraphValuesForMultipleSelect(string GeneralCriteria, List <string> Ids)
        {
            List <DailySummary> GetListOfDailySummaries = new List <DailySummary>();

            foreach (string id in Ids)
            {
                string CriteriaValue = "";
                CriteriaValue = GeneralCriteria + id;
                using (TAS2013Entities dc = new TAS2013Entities())
                {
                    DailySummary ds = dc.DailySummaries.Where(aa => aa.SummaryDateCriteria == CriteriaValue).FirstOrDefault();
                    GetListOfDailySummaries.Add(ds);
                }
            }
            return(Json(GetListOfDailySummaries, JsonRequestBehavior.AllowGet));
        }
        private void ShowDailySummaryView(object sender, EventArgs e)
        {
            DailySummary rptVwDailySummary = new DailySummary();

            _grdTimeEntry.DataSource = null;
            _grdTimeEntry.DataSource = rptVwDailySummary.Fetch(_connection, _sUserId);

            _mnItmEdit_DeleteEntry.Enabled = false;

            _mnItmView_Detailed.Checked         = false;
            _mnItmView_DailyTaskSummary.Checked = false;
            _mnItmView_DailySummary.Checked     = true;
            _mnItmView_TaskSummary.Checked      = false;
            _mnItmView_DailyTaskStatus.Checked  = false;

            #region Old Script

            //StringBuilder strSql = new StringBuilder();

            //strSql.AppendLine("SELECT  NumMonth, NumDay, SUM(Time) * 24 AS ElapsedTime ");
            //strSql.AppendLine("FROM (SELECT DATEPART(mm, ActionTime) AS NumMonth, DATEPART(dd, ActionTime) AS NumDay, ");
            //strSql.AppendLine(             "SUM(CONVERT(float, ActionTime)) * - 1 AS Time, UserId, ActionTypeID, Task ");
            //strSql.AppendLine(      "FROM TimeLog ");
            //strSql.AppendLine(      "WHERE ActionTypeID = 0 ");
            //strSql.AppendLine(      "GROUP BY DATEPART(mm, ActionTime), DATEPART(dd, ActionTime), UserId, ActionTypeID, Task ");

            //strSql.AppendLine(      "UNION ");

            //strSql.AppendLine(      "SELECT DATEPART(mm, ActionTime) AS NumMonth, DATEPART(dd, ActionTime) AS NumDay, ");
            //strSql.AppendLine(             "SUM(CONVERT(float, ActionTime)) AS Time, UserId, ActionTypeID, Task ");
            //strSql.AppendLine(      "FROM TimeLog AS TimeLog_1 ");
            //strSql.AppendLine(      "WHERE ActionTypeID = 1 ");
            //strSql.AppendLine(      "GROUP BY DATEPART(mm, ActionTime), DATEPART(dd, ActionTime), UserId, ActionTypeID, Task ");

            //strSql.AppendLine(      "UNION ");

            //strSql.AppendLine(      "SELECT DATEPART(mm, GETDATE()) AS NumMonth, DATEPART(dd, GETDATE()) AS NumDay, ");
            //strSql.AppendLine(             "CASE WHEN (ActionTypeID = 0) THEN CONVERT(float, GETDATE()) ELSE 0 END AS Time, ");
            //strSql.AppendLine(             "UserID, 1 AS ActionTypeID, Task ");
            //strSql.AppendLine(      "FROM (SELECT TOP 1 * FROM TimeLog ORDER BY ActionTime DESC) AS LSTACT) AS TBL ");
            //strSql.AppendLine("WHERE UserId = '" + _sUserId + "' ");
            //strSql.AppendLine("GROUP BY NumMonth, NumDay ");
            //strSql.AppendLine("ORDER BY NumMonth, NumDay");

            #endregion
        }
        public bool Edit(DailySummaryBM dailySummary)
        {
            bool isEntityExists = _context.DailySummaries.Any(x => !x.DateDeleted.HasValue && x.Id == dailySummary.Id);

            if (isEntityExists)
            {
                DailySummary dailySummaryDM = _context.DailySummaries.AsNoTracking().First(x => x.Id == dailySummary.Id);

                dailySummaryDM.Desription   = dailySummary.Desription;
                dailySummaryDM.DateModified = DateTime.Now;

                _context.DailySummaries.Update(dailySummaryDM);
                _context.SaveChanges();
            }

            return(isEntityExists);
        }
        public static void TestSubject_RecipientInterrupted()
        {
            var date = 18.December(2018);

            var recipient = Create.User("Pierre-Emerick Aubameyang");

            var allocatedUsers   = Create.Users("Petr Čech", "Héctor Bellerín");
            var interruptedUsers = Create.Users("Sokratis Papastathopoulos", "Mohamed Elneny").Concat(new[] { recipient });

            var allUsers = allocatedUsers.Concat(interruptedUsers);

            var allocations = Create.Allocations(allocatedUsers, date);
            var requests    = Create.Requests(allUsers, date);

            var email = new DailySummary(recipient, allocations, requests);

            Assert.Equal("[INTERRUPTED] 18 Dec Daily allocations summary", email.Subject);
        }
        public ActionResult GetGraphValuesForMultipleSelectAndDifferentDate(string GeneralCriteria, List <string> Ids, string datefrom, string dateto)
        {
            List <DailySummary> GetListOfDailySummaries = new List <DailySummary>();

            using (TAS2013Entities dc = new TAS2013Entities())
            {
                foreach (var id in Ids)
                {
                    for (DateTime date = Convert.ToDateTime(datefrom); date.Date <= Convert.ToDateTime(dateto).Date; date = date.AddDays(1))
                    {
                        string       query = date.Year.ToString().Substring(2) + (("0" + date.Month).Count() != 2 ? date.Month + "" : ("0" + date.Month)) + (("0" + date.Day).Count() != 2 ? date.Day + "" : ("0" + date.Day)) + GeneralCriteria + id;
                        DailySummary ds    = dc.DailySummaries.Where(aa => aa.SummaryDateCriteria == query).FirstOrDefault();
                        GetListOfDailySummaries.Add(ds);
                    }
                }

                return(Json(GetListOfDailySummaries, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #24
0
        public void RiskExposureTest(string scoreSumOp, double scoreSumValue, double scoreSum, RiskLevel expected)
        {
            var configuration = new V1ExposureRiskCalculationConfiguration()
            {
                DailySummary_DaySummary_ScoreSum = new V1ExposureRiskCalculationConfiguration.Threshold()
                {
                    Op    = scoreSumOp,
                    Value = scoreSumValue
                }
            };

            var dailySummary = new DailySummary()
            {
                DateMillisSinceEpoch = 0,
                DaySummary           = new ExposureSummaryData()
                {
                    ScoreSum = scoreSum
                },
                ConfirmedClinicalDiagnosisSummary = new ExposureSummaryData(),
                ConfirmedTestSummary = new ExposureSummaryData(),
                RecursiveSummary     = new ExposureSummaryData(),
                SelfReportedSummary  = new ExposureSummaryData()
            };

            var exposureWindows = new List <ExposureWindow>()
            {
                new ExposureWindow()
                {
                    CalibrationConfidence = CalibrationConfidence.High,
                    DateMillisSinceEpoch  = 0,
                    Infectiousness        = Infectiousness.High,
                    ReportType            = ReportType.Unknown,
                    ScanInstances         = new List <ScanInstance>()
                }
            };

            IExposureRiskCalculationService service = CreateService();

            RiskLevel result = service.CalcRiskLevel(dailySummary, exposureWindows, configuration);

            Assert.Equal(expected, result);
        }
        public ActionResult GetGraphValuesForDifferentDatesSS(string CriteriaValue, string datefrom, string dateto)
        {
            List <DailySummary> GetListOfDailySummaries = new List <DailySummary>();
            string criteria = CriteriaValue.Substring(0, 1);
            string value    = CriteriaValue.Substring(1);

            if (value.ToLower() != "null")
            {
                using (TAS2013Entities dc = new TAS2013Entities())
                {
                    for (DateTime date = Convert.ToDateTime(datefrom); date.Date <= Convert.ToDateTime(dateto).Date; date = date.AddDays(1))
                    {
                        string       query     = date.Year.ToString().Substring(2) + (("0" + date.Month).Count() != 2 ? date.Month + "" : ("0" + date.Month)) + (("0" + date.Day).Count() != 2 ? date.Day + "" : ("0" + date.Day)) + criteria + value;
                        short        criteriav = Convert.ToInt16(value);
                        DailySummary ds        = dc.DailySummaries.Where(aa => aa.SummaryDateCriteria == query).First();
                        GetListOfDailySummaries.Add(ds);
                    }
                }
            }
            return(Json(GetListOfDailySummaries, JsonRequestBehavior.AllowGet));
        }
        private DailySummary InitializeDailySummaryValues(List <DailySummary> intermediate)
        {
            DailySummary gatherinfo = new DailySummary();

            gatherinfo.CriteriaName   = intermediate.FirstOrDefault().CriteriaName;
            gatherinfo.CriteriaValue  = intermediate.FirstOrDefault().CriteriaValue;
            gatherinfo.Criteria       = intermediate.FirstOrDefault().Criteria;
            gatherinfo.AActualMins    = 0;
            gatherinfo.AbsentEmps     = 0;
            gatherinfo.ActualWorkMins = 0;
            gatherinfo.AEIMins        = 0;
            gatherinfo.AEOMins        = 0;
            gatherinfo.AExpectedMins  = 0;
            gatherinfo.ALIMins        = 0;
            gatherinfo.ALOMins        = 0;
            gatherinfo.ALossMins      = 0;
            gatherinfo.AOTMins        = 0;

            gatherinfo.EIEmps           = 0;
            gatherinfo.EIMins           = 0;
            gatherinfo.EOEmps           = 0;
            gatherinfo.EOMins           = 0;
            gatherinfo.ExpectedWorkMins = 0;
            gatherinfo.HalfLvEmps       = 0;
            gatherinfo.LIEmps           = 0;
            gatherinfo.LIMins           = 0;
            gatherinfo.LOEmps           = 0;
            gatherinfo.LOMins           = 0;
            gatherinfo.LossWorkMins     = 0;
            gatherinfo.LvEmps           = 0;
            gatherinfo.OnTimeEmps       = 0;
            gatherinfo.OTEmps           = 0;
            gatherinfo.OTMins           = 0;
            gatherinfo.PresentEmps      = 0;
            gatherinfo.ShortLvEmps      = 0;
            gatherinfo.TotalEmps        = 0;
            return(gatherinfo);
        }
        /// <summary>
        /// 创建某用户的每日总结.
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public bool BuildOneUserDailySummary(string userCode, DateTime date)
        {
            bool result = false;

            try
            {
                using (MyMiniTradingSystemContext context = new MyMiniTradingSystemContext())
                {
                    // 先查询有没有仓位.
                    var pQuery =
                        from data in context.Positions
                        where
                        data.UserCode == userCode &&
                        data.Quantity > 0
                        select
                        data;


                    List <Position> userPositionList = pQuery.ToList();

                    if (userPositionList.Count == 0)
                    {
                        ResultMessage = "用户没有任何持仓!";
                        return(result);
                    }



                    List <DailySummary> newDataList = new List <DailySummary>();


                    foreach (Position userPosition in userPositionList)
                    {
                        CommodityPrice cp =
                            context.CommodityPrices.FirstOrDefault(p => p.CommodityCode == userPosition.CommodityCode && p.TradingStartDate == date);

                        if (cp == null)
                        {
                            ResultMessage = String.Format("未能检索到{0}的{1:yyyy-MM-dd}的行情数据!", userPosition.CommodityCode, date);
                            return(result);
                        }


                        DailySummary newData = new DailySummary()
                        {
                            // 用户.
                            UserCode = userCode,

                            // 商品.
                            PositionCommodityCode = userPosition.CommodityCode,

                            // 日期.
                            DailySummaryDate = date,

                            // 数量.
                            PositionQuantity = userPosition.Quantity,

                            // 收盘.
                            ClosePrice = cp.ClosePrice,

                            // 市值.
                            PositionValue = userPosition.Quantity * cp.ClosePrice,

                            // 有效.
                            IsActive = true,
                        };



                        // 止损 = 收盘 - 3ATR.
                        newData.StopLossPrice = newData.ClosePrice - 3 * cp.Atr;


                        // 取得前日数据.
                        DailySummary prevData =
                            context.DailySummarys.Where(p => p.UserCode == newData.UserCode &&
                                                        p.PositionCommodityCode == newData.PositionCommodityCode &&
                                                        p.DailySummaryDate < newData.DailySummaryDate).OrderByDescending(p => p.DailySummaryDate).FirstOrDefault();

                        if (prevData != null)
                        {
                            // 存在前日数据.
                            if (prevData.StopLossPrice > newData.StopLossPrice)
                            {
                                // 浮动止损, 只能上升,不能下降.
                                newData.StopLossPrice = prevData.StopLossPrice;
                            }
                        }


                        if (newData.ClosePrice <= newData.StopLossPrice)
                        {
                            // 当日收盘低于止损.
                            // 明日应当完成平仓操作.
                            newData.Todo = "准备平仓";
                        }



                        newData.BeforeInsertOperation();

                        newDataList.Add(newData);
                    }



                    // 先删除历史数据(如果有.)
                    var oldQuery =
                        from data in context.DailySummarys
                        where
                        data.UserCode == userCode &&
                        data.DailySummaryDate == date
                        select data;

                    List <DailySummary> oldDataList = oldQuery.ToList();
                    if (oldDataList.Count > 0)
                    {
                        context.DailySummarys.RemoveRange(oldDataList);
                    }


                    // 插入新数据.
                    context.DailySummarys.AddRange(newDataList);


                    // 保存.
                    context.SaveChanges();

                    result = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);

                result        = false;
                ResultMessage = ex.Message;
            }



            return(result);
        }
        /// <summary>
        /// 更新每日总结.
        /// </summary>
        /// <param name="newData"></param>
        /// <returns></returns>
        public bool InsertOrUpdateDailySummary(DailySummary newData)
        {
            bool result = false;

            try
            {
                using (MyMiniTradingSystemContext context = new MyMiniTradingSystemContext())
                {
                    // 查询数据是否已存在.
                    var query =
                        from data in context.DailySummarys
                        where
                        data.PositionCommodityCode == newData.PositionCommodityCode &&
                        data.UserCode == newData.UserCode &&
                        data.DailySummaryDate == newData.DailySummaryDate
                        select data;


                    DailySummary oldData = query.FirstOrDefault();

                    if (oldData != null)
                    {
                        // 更新.

                        // 数量.
                        oldData.PositionQuantity = newData.PositionQuantity;
                        // 收.
                        oldData.ClosePrice = newData.ClosePrice;
                        // 市值.
                        oldData.PositionValue = newData.PositionValue;
                        // 止损.
                        oldData.StopLossPrice = newData.StopLossPrice;

                        oldData.BeforeUpdateOperation();
                    }
                    else
                    {
                        // 插入.

                        newData.BeforeInsertOperation();

                        context.DailySummarys.Add(newData);
                    }

                    // 保存.
                    context.SaveChanges();

                    result = true;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);

                result        = false;
                ResultMessage = ex.Message;
            }



            return(result);
        }
Beispiel #29
0
        public async Task <(List <DailySummary>, List <ExposureWindow>)> SetExposureDataAsync(
            List <DailySummary> dailySummaryList,
            List <ExposureWindow> exposueWindowList
            )
        {
            _loggerService.StartMethod();

            List <DailySummary> existDailySummaryList = await GetDailySummariesAsync();

            List <ExposureWindow> existExposureWindowList = await GetExposureWindowsAsync();

            List <DailySummary> filteredExistDailySummaryList = new List <DailySummary>();

            // Filter and merge DailySummaries that have same DateMillisSinceEpoch value.
            foreach (var existDailySummary in existDailySummaryList)
            {
                var conflictDailySummaryList = dailySummaryList
                                               .Where(ds => ds.DateMillisSinceEpoch == existDailySummary.DateMillisSinceEpoch)
                                               .ToList();

                var conflictDailySummaryListCount = conflictDailySummaryList.Count();
                if (conflictDailySummaryListCount == 0)
                {
                    filteredExistDailySummaryList.Add(existDailySummary);
                    continue;
                }
                else if (conflictDailySummaryListCount > 1)
                {
                    _loggerService.Warning($"The list conflictDailySummaryList count should be 1 but {conflictDailySummaryListCount}." +
                                           "conflictDailySummaryList will be sorted and selected first value.");
                    conflictDailySummaryList.Sort(_dailySummaryComparer);
                }

                // `conflictDailySummaryList` count must be 1,
                // because the DailySummary objects that have same DateMillisSinceEpoch value must be saved after merge.
                DailySummary newDailySummary = conflictDailySummaryList.First();

                if (existDailySummary.Equals(newDailySummary))
                {
                    filteredExistDailySummaryList.Add(existDailySummary);
                }
                else
                {
                    MergeDailySummarySelectMaxValues(existDailySummary, newDailySummary);
                }
            }

            List <DailySummary>   unionDailySummaryList   = filteredExistDailySummaryList.Union(dailySummaryList).ToList();
            List <ExposureWindow> unionExposureWindowList = existExposureWindowList.Union(exposueWindowList).ToList();

            unionDailySummaryList.Sort(_dailySummaryComparer);
            unionExposureWindowList.Sort(_exposureWindowComparer);

            await SaveExposureDataAsync(unionDailySummaryList, unionExposureWindowList);

            List <DailySummary>   newDailySummaryList   = unionDailySummaryList.Except(filteredExistDailySummaryList).ToList();
            List <ExposureWindow> newExposureWindowList = unionExposureWindowList.Except(existExposureWindowList).ToList();

            _loggerService.EndMethod();

            return(newDailySummaryList, newExposureWindowList);
        }
Beispiel #30
0
        /// <summary>
        /// Select and merge the maximum values of each DailySummary objects.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        private void MergeDailySummarySelectMaxValues(DailySummary from, DailySummary to)
        {
            _loggerService.StartMethod();

            if (from.DateMillisSinceEpoch != to.DateMillisSinceEpoch)
            {
                _loggerService.Info($"DateMillisSinceEpoch is not match: {from.DateMillisSinceEpoch}, {to.DateMillisSinceEpoch}");
                return;
            }

            if (from.DaySummary != null)
            {
                if (to.DaySummary == null)
                {
                    to.DaySummary = new ExposureSummaryData();
                }
                to.DaySummary.ScoreSum            = Math.Max(from.DaySummary.ScoreSum, to.DaySummary.ScoreSum);
                to.DaySummary.MaximumScore        = Math.Max(from.DaySummary.MaximumScore, to.DaySummary.MaximumScore);
                to.DaySummary.WeightedDurationSum = Math.Max(from.DaySummary.WeightedDurationSum, to.DaySummary.WeightedDurationSum);
            }

            if (from.ConfirmedTestSummary != null)
            {
                if (to.ConfirmedTestSummary == null)
                {
                    to.ConfirmedTestSummary = new ExposureSummaryData();
                }
                to.ConfirmedTestSummary.ScoreSum            = Math.Max(from.ConfirmedTestSummary.ScoreSum, to.ConfirmedTestSummary.ScoreSum);
                to.ConfirmedTestSummary.MaximumScore        = Math.Max(from.ConfirmedTestSummary.MaximumScore, to.ConfirmedTestSummary.MaximumScore);
                to.ConfirmedTestSummary.WeightedDurationSum = Math.Max(from.ConfirmedTestSummary.WeightedDurationSum, to.ConfirmedTestSummary.WeightedDurationSum);
            }

            if (from.ConfirmedClinicalDiagnosisSummary != null)
            {
                if (to.ConfirmedClinicalDiagnosisSummary == null)
                {
                    to.ConfirmedClinicalDiagnosisSummary = new ExposureSummaryData();
                }
                to.ConfirmedClinicalDiagnosisSummary.ScoreSum            = Math.Max(from.ConfirmedClinicalDiagnosisSummary.ScoreSum, to.ConfirmedClinicalDiagnosisSummary.ScoreSum);
                to.ConfirmedClinicalDiagnosisSummary.MaximumScore        = Math.Max(from.ConfirmedClinicalDiagnosisSummary.MaximumScore, to.ConfirmedClinicalDiagnosisSummary.MaximumScore);
                to.ConfirmedClinicalDiagnosisSummary.WeightedDurationSum = Math.Max(from.ConfirmedClinicalDiagnosisSummary.WeightedDurationSum, to.ConfirmedClinicalDiagnosisSummary.WeightedDurationSum);
            }

            if (from.SelfReportedSummary != null)
            {
                if (to.SelfReportedSummary == null)
                {
                    to.SelfReportedSummary = new ExposureSummaryData();
                }
                to.SelfReportedSummary.ScoreSum            = Math.Max(from.SelfReportedSummary.ScoreSum, to.SelfReportedSummary.ScoreSum);
                to.SelfReportedSummary.MaximumScore        = Math.Max(from.SelfReportedSummary.MaximumScore, to.SelfReportedSummary.MaximumScore);
                to.SelfReportedSummary.WeightedDurationSum = Math.Max(from.SelfReportedSummary.WeightedDurationSum, to.SelfReportedSummary.WeightedDurationSum);
            }

            if (from.RecursiveSummary != null)
            {
                if (to.RecursiveSummary == null)
                {
                    to.RecursiveSummary = new ExposureSummaryData();
                }
                to.RecursiveSummary.ScoreSum            = Math.Max(from.RecursiveSummary.ScoreSum, to.RecursiveSummary.ScoreSum);
                to.RecursiveSummary.MaximumScore        = Math.Max(from.RecursiveSummary.MaximumScore, to.RecursiveSummary.MaximumScore);
                to.RecursiveSummary.WeightedDurationSum = Math.Max(from.RecursiveSummary.WeightedDurationSum, to.RecursiveSummary.WeightedDurationSum);
            }

            _loggerService.EndMethod();
        }