コード例 #1
0
 public void update(RealTimeData sub)
 {
     this.sub = sub;
     foreach (Company company in sub.companies)
     {
         if (companyName == company.companyName)
         {
             //Clear previous entries from the dataGridView and reset heads?? Not sure how/why, but it prevents crashes...
             dataGridView1.Rows.Clear();
             dataGridView1.ColumnCount          = 2;
             dataGridView1.ColumnHeadersVisible = true;
             //Sort the buy orders according to its implementation of CompareTo
             company.buyOrders.Sort();
             foreach (BuyOrder buyOrder in company.buyOrders.Take(10)) //only take top 10
             {
                 this.dataGridView1.Rows.Add(buyOrder.orderSize, buyOrder.orderPrice);
             }
             dataGridView2.Rows.Clear();
             dataGridView1.ColumnCount          = 2;
             dataGridView1.ColumnHeadersVisible = true;
             //Sort the sell orders according to its implementation of CompareTo
             company.sellOrders.Sort();
             foreach (SellOrder sellOrder in company.sellOrders.Take(10)) //only take top 10
             {
                 this.dataGridView2.Rows.Add(sellOrder.orderPrice, sellOrder.orderSize);
             }
         }
     }
 }
コード例 #2
0
        public List <RealTimeData> GetRealtimeDataBy(string enterpriseID, string sceneID)
        {
            BLL.BasicStorage    storage = new BLL.BasicStorage();
            DataSet             ds      = storage.GetCollectingParam(enterpriseID, sceneID);
            List <RealTimeData> list    = new List <RealTimeData>();

            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    foreach (DataRow dr in dt.Rows)
                    {
                        RealTimeData realTimeData = new RealTimeData();
                        realTimeData.ID           = Guid.Parse(dr["ID"].ToString());
                        realTimeData.EnterpriseID = Guid.Parse(dr["EnterpriseID"].ToString());
                        realTimeData.Name         = dr["Name"].ToString();
                        realTimeData.Phone        = dr["Phone"].ToString();
                        realTimeData.EName        = dr["EName"].ToString();
                        realTimeData.Params       = dr["Params"].ToString();
                        realTimeData.AirTemp      = Double.Parse(dr["AirTemp"].ToString());

                        realTimeData.AirHi    = Double.Parse(dr["AirHi"].ToString());
                        realTimeData.SoilTemp = Double.Parse(dr["SoilTemp"].ToString());
                        realTimeData.SoilHi   = Double.Parse(dr["SoilHi"].ToString());
                        realTimeData.CO       = Double.Parse(dr["CO"].ToString());
                        realTimeData.Shine    = Double.Parse(dr["Shine"].ToString());
                        realTimeData.PickTime = string.IsNullOrEmpty(dr["PickTime"].ToString()) ? DateTime.Now : DateTime.Parse(dr["PickTime"].ToString());

                        list.Add(realTimeData);
                    }
                }
            }
            return(list);
        }
コード例 #3
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <BlogContext>();

                var helper = new Utils.Utility(db);

                float        marketLow  = _arg.MarketLow;
                float        marketHigh = _arg.MarketHigh;
                RealTimeData ret        = null;


                var realData = await helper.GetRealTimeDataWithDate(stockId, _arg.BaseDate);


                if (realData != null && realData.ZongShiZhi != null)
                {
                    if (marketLow * 1e8 <= realData.LiuTongShiZhi && realData.LiuTongShiZhi <= marketHigh * 1e8)
                    {
                        ret = realData;
                    }
                }



                //如果是null,表示不符合筛选条件

                return(ret);;
            }
        }
コード例 #4
0
ファイル: Utility.cs プロジェクト: zfkingth/StockQuantization
        /// <summary>
        /// 获取包括筛选时间的股票市值,换手率的的 real time data,如果没有会查询历史数据进行转换。
        /// </summary>
        /// <param name="stockId"></param>
        /// <param name="baseDate"></param>
        /// <returns></returns>
        public async Task <RealTimeData> GetRealTimeDataWithDate(string stockId, DateTime baseDate)
        {
            RealTimeData rt = null;

            var realData = await(from i in _db.RealTimeDataSet
                                 where i.StockId == stockId && i.Date <= baseDate && i.Open != 0
                                 orderby i.Date descending
                                 select i).AsNoTracking().FirstOrDefaultAsync();

            if (realData != null)
            {
                rt = realData;
            }
            else
            {
                var dayDataItem = await(from i in _db.DayDataSet
                                        where i.StockId == stockId && i.Date <= baseDate && i.Open != 0
                                        orderby i.Date descending
                                        select i
                                        ).AsNoTracking().FirstOrDefaultAsync();
                if (dayDataItem != null)
                {
                    rt = await ConvertDayToReal(dayDataItem);
                }
            }

            return(rt);
        }
コード例 #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="list">需要处理的股票代码列表</param>
        /// <param name="handle">处理函数</param>
        /// <param name="retList">返回结果</param>
        private void ProcessDataInParallel(List <string> list,
                                           Func <string, Task <RealTimeData> > handle,
                                           List <RealTimeData> retList)
        {
            // Use ConcurrentQueue to enable safe enqueueing from multiple threads.
            var    exceptions = new ConcurrentQueue <Exception>();
            object locker     = new object();
            var    po         = new ParallelOptions()
            {
                CancellationToken      = cts.Token,
                MaxDegreeOfParallelism = CurrentThreadNum,
            };


            // Execute the complete loop and capture all exceptions.
            Parallel.ForEach(list, po, (item) =>
            {
                try
                {
                    po.CancellationToken.ThrowIfCancellationRequested();

                    RealTimeData real = null;
                    //using (var asyncBridge = AsyncHelper.Wait)
                    //{
                    //    asyncBridge.Run(handle(item), (callArg) => real = callArg);
                    //}

                    real = handle(item).Result;

                    Interlocked.Increment(ref _progressedCnt);

                    if (real != null)
                    {
                        lock (locker)
                        {
                            retList.Add(real);
                        }
                    }
                }
                // Store the exception and continue with the loop.
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                    if (exceptions.Count >= 3)
                    {
                        var nex = new Exception("too many exception in Parallel.ForEach clause");
                        exceptions.Enqueue(nex);
                        throw new AggregateException(exceptions); //未捕获的异常会导致Parallel.ForEach退出。
                    }
                }
            });

            // Throw the exceptions here after the loop completes.
            if (exceptions.Count > 0)
            {
                throw new AggregateException(exceptions);
            }
        }
コード例 #6
0
 public placeBidOrderForm(RealTimeData data)
 {
     this.data = data;
     InitializeComponent();
     //Add companies to the drop down list
     foreach (Company company in data.companies)
     {
         comboBox1.Items.Add(company.companyName);
     }
 }
コード例 #7
0
 RealTimeData data; //used to modify the subject
 public placeAskOrderForm(RealTimeData data)
 {
     this.data = data;
     InitializeComponent();
     //populate the dropdown company list from the companies in the subject
     foreach (Company company in data.companies)
     {
         comboBox1.Items.Add(company.companyName);
     }
 }
コード例 #8
0
        private List <RealTimeData> ParseRealData(Stream stream)
        {
            List <RealTimeData> list = new List <RealTimeData>();

            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                var val = reader.ReadToEnd();

                Regex regex = new Regex(@"{[^{}]+}");

                var matches = regex.Matches(val);

                for (int m = 0; m < matches.Count; m++)
                {
                    string ss = matches[m].Value;


                    dynamic stuff = Newtonsoft.Json.Linq.JObject.Parse(ss);

                    string stockId = stuff["code"];

#if DEBUG
                    System.Diagnostics.Debug.WriteLine(stockId);
                    System.Diagnostics.Debug.WriteLine(ss);
#endif


                    DateTime date = ((DateTime)stuff["time"]);


                    if (stuff["open"] != null)
                    {
                        //每一支股票只保留多个实时数据

                        RealTimeData realItem = new RealTimeData();
                        realItem.StockId = stockId;
                        realItem.Date    = date;


                        realItem.Open       = stuff["open"];
                        realItem.High       = stuff["high"];
                        realItem.Low        = stuff["low"];
                        realItem.Close      = stuff["price"];
                        realItem.ZhangDieFu = stuff["percent"] * 100f;//和历史数据统一为百分比
                        realItem.Volume     = stuff["volume"];
                        realItem.Amount     = stuff["turnover"];
                        realItem.StockName  = stuff["name"];

                        list.Add(realItem);
                    }
                }
            }

            return(list);
        }
コード例 #9
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            DayData dayData = null;


            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <StockContext>();

                var helper = new Utils.Utility(db);



                int nearestDayNum = _arg.NearDaysNum;
                int riseNum       = _arg.NRiseNum;

                var dayDataList = await helper.GetDayData(stockId, nearestDayNum, _arg.BaseDate);


                if (dayDataList.Count > 0)
                {
                    //对数据进行处理
                    for (int i = 0; i < dayDataList.Count - riseNum + 1; i++)
                    {
                        int j = 0;
                        for (; j < riseNum; j++)
                        {
                            if (dayDataList[dayDataList.Count - 1 - (i + j)].Close <= dayDataList[dayDataList.Count - 1 - (i + j)].Open)
                            {
                                //不符合连涨条件
                                break;
                            }
                        }

                        if (j == riseNum)
                        {
                            //符合条件,不需要再检索
                            //加入
                            dayData = dayDataList[dayDataList.Count - 1 - i];
                            break;
                        }
                    }
                }
                //如果是null,表示不符合筛选条件

                RealTimeData real = null;
                if (dayData != null)
                {
                    real = await helper.ConvertDayToReal(dayData);
                }

                return(real);
            }
        }
コード例 #10
0
        private async Task WriteRealTdDb(RealTimeData realItem)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <BlogContext>();

                var stockId = realItem.StockId;
                var date    = realItem.Date;


                //数据库中只保留多个时间点的实时数据,


                if (await db.RealTimeDataSet.AnyAsync(s => s.StockId == stockId && s.Date == date))
                {
                    //如果有这个数据则处理下一个股票的数据
                    System.Diagnostics.Debug.WriteLine($"{stockId} {date} 的实时数据已存在");
                    return;
                }

                var previous = await(from i in db.DayDataSet
                                     where i.StockId == stockId    //没有换手就是停牌,确保数据库中没有停牌的数据
                                     orderby i.Date descending
                                     select i).FirstOrDefaultAsync();



                db.RealTimeDataSet.Add(realItem);

                if (previous != null)
                {
                    if (previous.LiuTongShiZhi != null && previous.Close != 0)
                    {
                        float liutongNum = (previous.LiuTongShiZhi.Value / previous.Close);
                        realItem.HuanShouLiu = realItem.Volume / liutongNum * 100f;

                        realItem.LiuTongShiZhi = realItem.Close * liutongNum;
                    }

                    if (previous.ZongShiZhi != null && previous.Close != 0)
                    {
                        float allNum = (previous.ZongShiZhi.Value / previous.Close);

                        realItem.ZongShiZhi = realItem.Close * allNum;
                    }
                }



                await db.SaveChangesAsync();
                await UpdateDateFlag(stockId, date);
            }
        }
コード例 #11
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <BlogContext>();

                var helper = new Utils.Utility(db);

                float   low     = _arg.ZhangFuLow;
                float   high    = _arg.ZhangFuHigh;
                int     numcnt  = _arg.CircleDaysNum;
                DayData dayData = null;



                //当天的数据算一个
                var dayDataList = await helper.GetDayData(stockId, numcnt, _arg.BaseDate);

                //单独只使用涨跌幅,不需要复权

                if (dayDataList.Count == numcnt)
                {
                    float mul = 1;
                    for (int i = 0; i < dayDataList.Count; i++)
                    {
                        var fudu = dayDataList[i].ZhangDieFu;
                        if (fudu != null)
                        {
                            mul *= (1 + fudu.Value / 100f);
                        }
                    }


                    if (low / 100f <= mul - 1 && mul - 1 <= high / 100f)
                    {
                        dayData = dayDataList[0];
                    }
                }



                //如果是null,表示不符合筛选条件

                RealTimeData real = null;
                if (dayData != null)
                {
                    real = await helper.ConvertDayToReal(dayData);
                }

                return(real);
            }
        }
コード例 #12
0
        private void showDataMessage(RealTimeData realTimeData)
        {
            if (null == realTimeData)
            {
                return;
            }

            if (null != dataShowControl1)
            {
                dataShowControl1.ShowMessage(realTimeData);
            }
        }
コード例 #13
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            DayData dayData = null;


            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <StockContext>();

                var  helper  = new Utils.Utility(db);
                bool fitFlag = false;

                int objIndex = _arg.StockIdList.IndexOf(stockId);

                DateTime startDate = _arg.DateList[objIndex];
                //当天的数据算一个
                var dayDataList = await helper.GetDayData(stockId, startDate, _arg.BaseDate);


                if (dayDataList.Count > 0)
                {
                    //使用成交量,需要复权
                    //复权,会改变dayDataList中的数据
                    await Utils.CalcData.FuQuan(db, stockId, dayDataList);

                    //
                    //获取均线数据
                    var closePrice = (from ii in dayDataList
                                      select ii.Close).Max();

                    if (closePrice != 0)
                    {
                        var startItem = dayDataList.LastOrDefault();
                        dayData            = startItem;
                        dayData.ZhangDieFu = (closePrice - startItem.Close) / startItem.Close * 100;

                        fitFlag = true;
                    }
                }


                //如果是null,表示不符合筛选条件

                RealTimeData real = null;
                if (fitFlag)
                {
                    real = await helper.ConvertDayToReal(dayData);
                }

                return(real);
            }
        }
コード例 #14
0
 //Will fill all applicable columns of stock state summary for all companies in the subject
 public void update(RealTimeData sub)
 {
     this.sub = sub;
     dataGridView1.Rows.Clear();
     // Create an unbound DataGridView by declaring a column count, prevents mising header after clear
     dataGridView1.ColumnCount          = 8;
     dataGridView1.ColumnHeadersVisible = true;
     foreach (Company company in sub.companies)
     {
         this.dataGridView1.Rows.Add(company.companyName, company.symbol, company.openPrice, company.getLastPrice(), company.priceChange, company.picture, company.percentChange, company.getVolume());
     }
 }
コード例 #15
0
ファイル: Form1.cs プロジェクト: cocfire/Docs
 private void RsServer_OnReceiveRealtimeData(RSServer server, RealTimeData data)
 {                                             //实时数据接收处理
     foreach (NodeData ndata in data.NodeList) //遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
     {
         string str = "实时数据->设备编号:" + data.DeviceID + "\t经度:" + data.Lng + "\t纬度:" + data.Lat + "\t坐标类型:" + data.CoordinateType.ToString() + "\t节点编号:" + ndata.NodeID +
                      "\t温度:" + ndata.Tem +
                      "\t湿度:" + ndata.Hum +
                      "\t继电器状态:" + data.RelayStatus +
                      "\t浮点型数据:" + ndata.FloatValue +
                      "\t32位有符号数据:" + ndata.SignedInt32Value +
                      "\t32位无符号数据:" + ndata.UnSignedInt32Value;
         Invoke(new Action(() =>
         {
             rhtResult.AppendText(str + "\r\n");
         }));
     }
 }
コード例 #16
0
    public override int GetHashCode()
    {
        int hash = 1;

        if (EntityUUID.Length != 0)
        {
            hash ^= EntityUUID.GetHashCode();
        }
        if (realTimeData_ != null)
        {
            hash ^= RealTimeData.GetHashCode();
        }
        hash ^= components_.GetHashCode();
        if (_unknownFields != null)
        {
            hash ^= _unknownFields.GetHashCode();
        }
        return(hash);
    }
コード例 #17
0
ファイル: Utility.cs プロジェクト: zfkingth/StockQuantization
        public DayData ConvertRealToDay(RealTimeData item)
        {
            DayData ret = new DayData();

            ret.StockId       = item.StockId;
            ret.Date          = item.Date;
            ret.Open          = item.Open;
            ret.High          = item.High;
            ret.Low           = item.Low;
            ret.Close         = item.Close;
            ret.Amount        = item.Amount;
            ret.Volume        = item.Volume;
            ret.ZhangDieFu    = item.ZhangDieFu;
            ret.HuanShouLiu   = item.HuanShouLiu;
            ret.LiuTongShiZhi = item.LiuTongShiZhi;
            ret.ZongShiZhi    = item.ZongShiZhi;


            return(ret);
        }
コード例 #18
0
 public void MergeFrom(EntityData other)
 {
     if (other == null)
     {
         return;
     }
     if (other.EntityUUID.Length != 0)
     {
         EntityUUID = other.EntityUUID;
     }
     if (other.realTimeData_ != null)
     {
         if (realTimeData_ == null)
         {
             RealTimeData = new global::EntityRealtimeData();
         }
         RealTimeData.MergeFrom(other.RealTimeData);
     }
     components_.Add(other.components_);
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
コード例 #19
0
        /// <summary>
        /// 获取实时测试状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public RealTimeData GetRealTimeTest(string input)
        {
            string[]     TestData = DataDivision(input);
            RealTimeData realtime = new RealTimeData();

            if (!CRC_Check(input))
            {
                realtime.DataState = "Data CRC Error";
                return(null);
            }
            realtime._codeindex     = TestData[3] + TestData[4];
            realtime._testmode      = TestData[7] + TestData[8];
            realtime._teststatus    = TestData[10] + TestData[9];//后面没有到低位交换
            realtime._testprocess   = TestData[11] + TestData[12];
            realtime._pressurevalue = TestData[13] + TestData[14] + TestData[15] + TestData[16];
            realtime._pressureunit  = TestData[17] + TestData[18] + TestData[19] + TestData[20];
            realtime._leakvalue     = TestData[21] + TestData[22] + TestData[23] + TestData[24];
            realtime._leakunit      = TestData[25] + TestData[26] + TestData[27] + TestData[28];
            realtime.DataState      = "OK";
            return(realtime);
        }
コード例 #20
0
ファイル: Utility.cs プロジェクト: zfkingth/StockQuantization
        public async Task <RealTimeData> ConvertDayToReal(DayData item)
        {
            RealTimeData ret = new RealTimeData();

            ret.StockId = item.StockId;

            ret.StockName = await GetStockNameById(item.StockId);

            ret.Date          = item.Date;
            ret.Open          = item.Open;
            ret.High          = item.High;
            ret.Low           = item.Low;
            ret.Close         = item.Close;
            ret.Amount        = item.Amount;
            ret.Volume        = item.Volume;
            ret.ZhangDieFu    = item.ZhangDieFu;
            ret.HuanShouLiu   = item.HuanShouLiu;
            ret.LiuTongShiZhi = item.LiuTongShiZhi;
            ret.ZongShiZhi    = item.ZongShiZhi;


            return(ret);;
        }
コード例 #21
0
        //显示数据
        public void ShowMessage(RealTimeData realTimeData)
        {
            double newValue   = 0.0;
            int    iValue     = 0;
            long   lTimestamp = 0L;

            time_now = DateTime.Now;
            if (null == realTimeData)
            {
                return;
            }

            lTimestamp = realTimeData.Timestamp;
            d_now      = lTimestamp;
            if (ViewHistory || !m_bisReceive)
            {
                return;
            }

            if (null != realTimeData.realTags)
            {
                var tag = realTimeData.realTags.Where(o => o.Tag == DrillTag).FirstOrDefault();
                if (null != tag)
                {
                    newValue = UnitConversion(tag.Value);
                    iValue   = (int)newValue;
                    AddMemo(iValue.ToString("#0"), lTimestamp, IsValidate(iValue));
                    zedInvalidateByTime(lTimestamp);
                    zedFourChartInvalidate(lTimestamp);
                    showFormMessage();
                    showFourchartToolTip();
                    removeMemo();
                    ++m_idataShowCount;
                }
            }
        }
コード例 #22
0
        //显示DataShow接收到的实时数据
        public void ShowMessage(RealTimeData realTimeData)
        {
            if (null == realTimeData)
            {
                return;
            }

            foreach (var data in m_dicTags)
            {
                var dataShow = data.Value;
                if (null != dataShow)
                {
                    int iIndex = (int)data.Key;
                    var tag    = realTimeData.realTags.Where(o => o.Tag == dataShow.DTag).FirstOrDefault();
                    if (null != tag)
                    {
                        double value = 0;
                        if (double.TryParse(tag.Value.ToString(), out value))
                        {
                            string strBoxID = realTimeData.BoxId.ToString();
                            var    newValue = Comm.UnitConversion(listTag, dataShow.DTag, strBoxID, value);
                            if ((bool)listTag.Where(o => o.Tag == dataShow.DTag).FirstOrDefault().IsBool)
                            {
                                dataShow.Value.Text = newValue > 0 ? "Yes" : "No";
                            }
                            else
                            {
                                dataShow.Value.Text = newValue.ToString("#0.00");
                            }

                            isAlarm(dataShow.DTag, strBoxID, newValue.ToString(), iIndex);
                        }
                    }
                }
            }
        }
コード例 #23
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <StockContext>();

                var helper = new Utils.Utility(db);

                float        low  = _arg.TurnOverRateLow;
                float        high = _arg.TurnOverRateHigh;
                RealTimeData ret  = null;


                var realData = await helper.GetRealTimeDataWithDate(stockId, _arg.BaseDate);

                if (realData != null)
                {
                    var zhibiao = realData.HuanShouLiu;

                    if (zhibiao != null)
                    {
                        if (low <= zhibiao && zhibiao <= high)
                        {
                            ret = realData;
                        }
                    }
                }



                //如果是null,表示不符合筛选条件

                return(ret);;
            }
        }
コード例 #24
0
        private void Write(RealTimeData value)
        {
            string currentPaht = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string path        = currentPaht + "\\Files\\Currencies\\";

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                path += _args.Symbol + ".csv";

                using (StreamWriter writer = File.AppendText(path))
                {
                    writer.WriteLine(value.Date.ToString("dd-MM-yyyy HH:MM:ss") + "," + value.Value / _exchangeRate);
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
        }
コード例 #25
0
        /// <summary>
        /// Processes real-time exports.
        /// </summary>
        private void ProcessRealTimeExports(RealTimeData[] items)
        {
            IList<ExportRecord> exportRecords;
            foreach (RealTimeData item in items)
            {
                try
                {
                    List<IDataPoint> filteredData = new List<IDataPoint>();

                    exportRecords = item.Export.FindRecords(item.Listener.ID);
                    if (exportRecords.Count == 1 && exportRecords[0].Identifier == -1)
                    {
                        // Include all data from the listener.
                        filteredData.AddRange(item.Data);
                    }
                    else
                    {
                        // Export data for selected records only (filtered).
                        foreach (IDataPoint dataPoint in item.Data)
                        {
                            if (exportRecords.FirstOrDefault(record => record.Identifier == dataPoint.HistorianID) != null)
                                filteredData.Add(dataPoint);
                        }
                    }

                    ProcessRealTimeExport(item.Export, item.Listener, filteredData);
                    item.Export.LastProcessResult = ExportProcessResult.Success;
                }
                catch (Exception ex)
                {
                    OnExportProcessException(item.Export, ex);
                }
            }
        }
コード例 #26
0
ファイル: RawDataExporter.cs プロジェクト: avs009/gsf
        private void ProcessRealTimeExport(RealTimeData[] items)
        {
            DataSet rawData;
            IList<ExportRecord> exportRecords;
            foreach (RealTimeData item in items)
            {
                try
                {                  
                    lock (m_rawData)
                    {
                        m_rawData.TryGetValue(item.Export.Name, out rawData);
                    }

                    if (rawData != null)
                    {
                        // Buffer-up the parsed data for the export.
                        exportRecords = item.Export.FindRecords(item.Listener.ID);
                        if (exportRecords.Count == 1 && exportRecords[0].Identifier == -1)
                        {
                            // Include all data from the listener.
                            if (Monitor.TryEnter(rawData))
                            {
                                try
                                {
                                    foreach (IDataPoint dataPoint in item.Data)
                                    {
                                        rawData.Tables[0].Rows.Add(item.Listener.ID, dataPoint.HistorianID, dataPoint.Time.ToString(), dataPoint.Value, (int)dataPoint.Quality);
                                    }
                                }
                                catch
                                {
                                    throw;
                                }
                                finally
                                {
                                    Monitor.Exit(rawData);
                                }
                            }
                        }
                        else
                        {
                            // Buffer data for selected records only (filtered).
                            ExportRecord comparer = new ExportRecord(item.Listener.ID, -1);
                            if (Monitor.TryEnter(rawData))
                            {
                                try
                                {
                                    foreach (IDataPoint dataPoint in item.Data)
                                    {
                                        if (exportRecords.FirstOrDefault(record => record.Identifier == dataPoint.HistorianID) != null)
                                            rawData.Tables[0].Rows.Add(item.Listener.ID, dataPoint.HistorianID, dataPoint.Time.ToString(), dataPoint.Value, (int)dataPoint.Quality);
                                    }
                                }
                                catch
                                {
                                    throw;
                                }
                                finally
                                {
                                    Monitor.Exit(rawData);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnStatusUpdate(string.Format("Data prep failed for export \"{0}\" - {1}", item.Export.Name, ex.Message));
                }
            }
        }
コード例 #27
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            DayData dayData = null;


            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <StockContext>();

                var helper = new Utils.Utility(db);

                //当天的数据算一个
                var dayDataList = await helper.GetDayData(stockId, _arg.CircleDaysNum + _arg.NearDaysNum, _arg.BaseDate);

                //使用成交量,需要复权
                //复权,会改变dayDataList中的数据
                await Utils.CalcData.FuQuan(db, stockId, dayDataList);


                int breakIndex = 0;

                if (dayDataList.Count == _arg.CircleDaysNum + _arg.NearDaysNum)
                {
                    //求出最近的最高价格,收盘
                    int   i             = 0;
                    float maxClosePrice = 0;
                    for (; i < _arg.NearDaysNum; i++)
                    {
                        float current = dayDataList[i].Close;
                        if (current > maxClosePrice)
                        {
                            maxClosePrice = current;
                            breakIndex    = i;
                        }
                    }

                    //如果不是严格模式
                    if (!_arg.StrictMode)
                    {
                        //如果收盘价高于收盘价,最高价高于最高价,就排除邻近的一根日线

                        var nearItem = dayDataList[breakIndex + 1];

                        if (dayDataList[breakIndex].Close >= nearItem.Close &&
                            dayDataList[breakIndex].High > nearItem.High)
                        {
                            bool allMatch = false;
                            for (int tempj = i + 1; tempj < dayDataList.Count; tempj++)
                            {
                                if (dayDataList[tempj].High > nearItem.Close)
                                {
                                    allMatch = true;
                                    break;
                                }
                            }
                            if (allMatch)
                            {
                                i++;
                            }
                        }
                    }


                    //求出之前的最高的盘中最高价格
                    float previousMaxHigh = 0;

                    for (; i < dayDataList.Count - _arg.NearDaysNum; i++)
                    {
                        float current = dayDataList[i].High;
                        if (current > previousMaxHigh)
                        {
                            previousMaxHigh = current;
                        }
                    }

                    //符合回调条件的点
                    bool match = false;
                    if (maxClosePrice > previousMaxHigh)
                    {
                        for (i = 0; i < _arg.CircleDaysNum; i++)
                        {
                            //从最早的数据开始遍历
                            var listItem = dayDataList[dayDataList.Count - 1 - i];
                            if (listItem.High >= previousMaxHigh)
                            {
                                //寻找到高点

                                //后面的最低价格
                                float suffixMinLow = float.MaxValue;

                                //寻找后续最低点
                                for (int j = i + 1; j < _arg.CircleDaysNum; j++)
                                {
                                    float current = dayDataList[dayDataList.Count - 1 - j].Low;
                                    if (current < suffixMinLow)
                                    {
                                        suffixMinLow = current;
                                    }
                                }

                                float fudu = (listItem.High - suffixMinLow) / listItem.High;

                                if (fudu >= _arg.HuiTiaoFuDuLow / 100f && fudu <= _arg.HuiTiaoFuDuHigh / 100f)
                                {
                                    //符合回调幅度的高点
                                    match = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (match)
                    {
                        //符合条件
                        dayData = dayDataList[breakIndex];
                    }
                }



                //如果是null,表示不符合筛选条件

                RealTimeData real = null;
                if (dayData != null)
                {
                    real = await helper.ConvertDayToReal(dayData);
                }

                return(real);
            }
        }
コード例 #28
0
ファイル: UXlsWorkbookGlobals.cs プロジェクト: mwilian/demos
        private void SaveToStream(IDataStream DataStream, TSaveData SaveData, int SheetIndex)
        {
            if ((sBOF == null) || (sEOF == null))
            {
                XlsMessages.ThrowException(XlsErr.ErrSectionNotLoaded);
            }

            sBOF.SaveToStream(DataStream, SaveData, 0);
            FileEncryption.SaveFirstPart(DataStream, SaveData); //WriteProt
            if (DataStream.Encryption.Engine != null)           //FilePass
            {
                byte[] Fp = DataStream.Encryption.Engine.GetFilePassRecord();
                DataStream.WriteRaw(Fp, Fp.Length);
            }

            if (IsXltTemplate)
            {
                TTemplateRecord.SaveNewRecord(DataStream);
            }

            FileEncryption.SaveSecondPart(DataStream, SaveData);

            TGlobalRecordSaver g = new TGlobalRecordSaver(DataStream, SaveData);

            g.SaveRecord(CodePage);

            FLel.SaveToStream(DataStream, SaveData, 0);
            TDSFRecord.SaveDSF(DataStream);
            g.SaveRecord(Excel9File);

            if (SheetIndex < 0)
            {
                FBoundSheets.SaveTabIds(DataStream);
            }
            g.SaveRecord(GetMacroRec(ObjProj));
            g.SaveRecord(GetMacroRec(ObNoMacros));
            g.SaveRecord(CodeNameRecord);

            FFnGroups.SaveToStream(DataStream, SaveData, 0);
            g.SaveRecord(OleObjectSize);
            FWorkbookProtection.SaveToStream(DataStream, SaveData);
            foreach (TWindow1Record w1 in Window1)
            {
                g.SaveRecord(w1);
            }
            TBackupRecord.SaveRecord(DataStream, Backup);
            THideObjRecord.SaveRecord(DataStream, HideObj);
            T1904Record.SaveRecord(DataStream, Dates1904);

            TPrecisionRecord.SaveRecord(DataStream, PrecisionAsDisplayed);
            TRefreshAllRecord.SaveRecord(DataStream, RefreshAll);

            g.SaveRecord(BookBool);

            Fonts.SaveToStream(DataStream, SaveData, 0);
            Formats.SaveToStream(DataStream, SaveData, 0);
            StyleXF.SaveAllToStream(DataStream, ref SaveData, CellXF);

            DXF.SaveToStream(DataStream, SaveData, 0);
            Styles.SaveToStream(DataStream, SaveData, 0);
            TableStyles.SaveToStream(DataStream, SaveData, 0);
            g.SaveRecord(Palette);
            g.SaveRecord(ClrtClient);

            PivotCache.SaveToStream(DataStream, SaveData, 0);
            DocRoute.SaveToStream(DataStream, SaveData, 0);

            UserBView.SaveToStream(DataStream, SaveData, 0);
            TUsesELFsRecord.SaveRecord(DataStream, UsesELFs);

            if (SheetIndex < 0)
            {
                FBoundSheets.SaveToStream(DataStream, SaveData);
                MetaData.SaveToStream(DataStream, SaveData, 0);
            }
            else
            {
                FBoundSheets.SaveRangeToStream(DataStream, SaveData, SheetIndex);
            }

            g.SaveRecord(MTRSettings);
            g.SaveRecord(ForceFullCalculation);
            g.SaveRecord(Country);

            FReferences.SaveToStream(DataStream, SaveData);
            FNames.SaveToStream(DataStream, SaveData, 0); //Should be after FBoundSheets.SaveToStream
            RealTimeData.SaveToStream(DataStream, SaveData, 0);
            g.SaveRecord(RecalcId);

            if (SheetIndex < 0)
            {
                FHeaderImages.SaveToStream(DataStream, SaveData);
                FDrawingGroup.SaveToStream(DataStream, SaveData);
            }

            FSST.SaveToStream(DataStream, SaveData);
            WebPub.SaveToStream(DataStream, SaveData, 0);
            g.SaveRecord(WOpt);
            //CrErr is ignored
            g.SaveRecord(BookExt);
            FeatHdr.SaveToStream(DataStream, SaveData, 0);
            DConn.SaveToStream(DataStream, SaveData, 0);
            ThemeRecord.SaveToStream(DataStream, SaveData, 0);
            g.SaveRecord(CompressPictures);
            g.SaveRecord(Compat12);
            g.SaveRecord(GUIDTypeLib);
            FFutureRecords.SaveToStream(DataStream, SaveData, 0);
            sEOF.SaveToStream(DataStream, SaveData, 0);
        }
コード例 #29
0
        private RealTimeData GetData()
        {
            if (_args.DefaultCurrency != "USD" && _exchangeRate == 1 && _args.Type != TypeSeries.CURRENCY)
            {
                try
                {
                    Int_CURRENCY_EXCHANGE_RATE            currency_exchange_rate         = _connection.GetQueryObject_CURRENCY_EXCHANGE_RATE();
                    IAvapiResponse_CURRENCY_EXCHANGE_RATE currency_exchange_rateResponse =
                        currency_exchange_rate.QueryPrimitive("USD", _args.DefaultCurrency);
                    var data2 = currency_exchange_rateResponse.Data;
                    if (data2.Error)
                    {
                        MessageBox.Show("Failed to fetch data for exchage rate", "Error");
                    }
                    else
                    {
                        _exchangeRate = double.Parse(data2.ExchangeRate);
                    }
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Failed to fetch currency exchange rate for chosen currency. Values will be show in USD", "Error");
                }
            }

            if (_args.Type == TypeSeries.STOCK)
            {
                Int_TIME_SERIES_INTRADAY time_series_intraday =
                    _connection.GetQueryObject_TIME_SERIES_INTRADAY();

                try
                {
                    //Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_1min;
                    //if (Refreshrate == "1 minute(s)")
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_1min;
                    //}
                    //else if (Refreshrate == "5 minutes(s)")
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_5min;
                    //}
                    //else if (Refreshrate == "15 minute(s)")
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_15min;
                    //}
                    //else if (Refreshrate == "30 minute(s)")
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_30min;
                    //}
                    //else if (Refreshrate == "60 minute(s)")
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_60min;
                    //}
                    //else
                    //{
                    //    cst = Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.none;
                    //}
                    IAvapiResponse_TIME_SERIES_INTRADAY time_series_intradayResponse =
                        time_series_intraday.Query(
                            _args.Symbol,
                            Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_1min,
                            Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_outputsize.compact);

                    var data = time_series_intradayResponse.Data;
                    if (data.Error)
                    {
                        MessageBox.Show("Failed to fetch data for " + _args.Symbol, "Error");
                    }
                    else
                    {
                        return(new RealTimeData
                        {
                            Value = double.Parse(data.TimeSeries.First().close) * _exchangeRate,
                            Date = DateTime.ParseExact(data.TimeSeries.First().DateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
                            Trend = 0
                        });
                    }
                }
                catch (Exception)
                {
                    //MessageBox.Show("Failed to send request", "Error");
                    Console.WriteLine("Desila je greska za deonice!");
                }
            }
            else if (_args.Type == TypeSeries.DIGITAL_CURRENCY)
            {
                Int_DIGITAL_CURRENCY_INTRADAY digital_currency_intraday =
                    _connection.GetQueryObject_DIGITAL_CURRENCY_INTRADAY();
                try
                {
                    IAvapiResponse_DIGITAL_CURRENCY_INTRADAY digital_currency_intradayResponse =
                        digital_currency_intraday.QueryPrimitive(_args.Symbol, "USD");

                    var data = digital_currency_intradayResponse.Data;
                    if (data.Error)
                    {
                        MessageBox.Show("Failed to fetch data for " + _args.FullName);
                    }
                    else
                    {
                        return(new RealTimeData
                        {
                            Value = double.Parse(data.TimeSeries.First().Price) * _exchangeRate,
                            Date = DateTime.ParseExact(data.TimeSeries.First().DateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
                            Trend = 0
                        });
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Desila je greska za kripto valute!");
                }
            }
            else if (_args.Type == TypeSeries.CURRENCY)
            {
                try
                {
                    Int_CURRENCY_EXCHANGE_RATE            currency_exchange_rate         = _connection.GetQueryObject_CURRENCY_EXCHANGE_RATE();
                    IAvapiResponse_CURRENCY_EXCHANGE_RATE currency_exchange_rateResponse =
                        currency_exchange_rate.QueryPrimitive(_args.Symbol, _args.DefaultCurrency);
                    var data2 = currency_exchange_rateResponse.Data;
                    if (data2.Error)
                    {
                        MessageBox.Show("Failed to fetch data for exchage rate for " + _args.Symbol, "Error");
                    }
                    else
                    {
                        var temp = new RealTimeData
                        {
                            Value = double.Parse(data2.ExchangeRate),
                            Date  = DateTime.Now,
                            Trend = 0
                        };
                        Write(temp);
                        return(temp);
                    }
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Failed to fetch data for exchage rate for " + _args.Symbol, "Error");
                }
            }

            return(new RealTimeData());
        }
コード例 #30
0
        private void ExcelReplaceValueDiffByType(IWorkbook workbook, ISheet sheet, IRow row, dynamic valuePair, DateTime startTime, DateTime endTime,
                                                 int reportType, string bmfId, string precision, int startIndex, ref int endIndex)
        {
            ICellStyle cellstyle = GetCellStyle(workbook, precision);

            switch (reportType)
            {
                #region 年(每月)
            case 1:
                var monthList = (List <MonRecord>)valuePair;
                for (DateTime sTime = startTime; sTime <= endTime; sTime = sTime.AddMonths(1), startIndex++)
                {
                    ICell cell      = row.CreateCell(startIndex);
                    var   cellValue = monthList.FirstOrDefault(a => a.MfId == bmfId && a.HTime == sTime);
                    if (cellValue == null)
                    {
                        cellValue = new MonRecord();
                    }
                    cell.SetCellValue(cellValue == null ? 0.00 : GetPrecision(precision, cellValue.TotalData));
                    cell.CellStyle = cellstyle;
                }
                endIndex = startIndex;
                break;

                #endregion
                #region 月(每天)
            case 2:
                var dayList = (List <DayRecord>)valuePair;
                for (DateTime sTime = startTime; sTime <= endTime; sTime = sTime.AddDays(1), startIndex++)
                {
                    ICell cell      = row.CreateCell(startIndex);
                    var   cellValue = dayList.FirstOrDefault(a => a.MfId == bmfId && a.HTime == sTime);
                    if (cellValue == null)
                    {
                        cellValue = new DayRecord();
                    }
                    cell.SetCellValue(cellValue != null ? GetPrecision(precision, cellValue.TotalData) : 0.00);
                    cell.CellStyle = cellstyle;
                }
                endIndex = startIndex;
                break;

                #endregion
                #region  比
            case 3:
                var yoyList = (List <ComparsionDto>)valuePair;
                for (DateTime sTime = startTime; sTime <= endTime; sTime = sTime.AddMonths(1), startIndex++)
                {
                    var yoyEntity = yoyList.FirstOrDefault(a => a.MfId == bmfId && a.HTime == sTime);
                    if (yoyEntity == null)
                    {
                        yoyEntity = new ComparsionDto();
                    }
                    ICell currentCell = row.CreateCell(startIndex);
                    currentCell.SetCellValue(GetPrecision(precision, yoyEntity.CurrentData));
                    currentCell.CellStyle = cellstyle;
                    startIndex            = startIndex + 1;
                    ICell lastCell = row.CreateCell(startIndex);
                    lastCell.SetCellValue(GetPrecision(precision, yoyEntity.LastData));
                    lastCell.CellStyle = cellstyle;
                    startIndex         = startIndex + 1;
                    ICell rateCell = row.CreateCell(startIndex);
                    rateCell.SetCellValue(GetPrecision(precision, yoyEntity.Rate));
                    rateCell.CellStyle = cellstyle;
                }
                var   totalCurrent = yoyList.Where(a => a.MfId == bmfId).Sum(a => a.CurrentData);
                var   totalLast    = yoyList.Where(a => a.MfId == bmfId).Sum(a => a.LastData);
                var   totalRate    = totalLast == 0 ? 100 : (totalCurrent - totalLast) / totalLast;
                ICell totalCell    = row.CreateCell(startIndex);
                totalCell.SetCellValue(GetPrecision(precision, totalCurrent));
                totalCell.CellStyle = cellstyle;
                startIndex          = startIndex + 1;
                ICell totalLastCell = row.CreateCell(startIndex);
                totalLastCell.SetCellValue(GetPrecision(precision, totalLast));
                totalLastCell.CellStyle = cellstyle;
                startIndex = startIndex + 1;
                ICell totalRateCell = row.CreateCell(startIndex);
                totalRateCell.SetCellValue(GetPrecision(precision, totalRate));
                totalRateCell.CellStyle = cellstyle;
                endIndex = startIndex;
                break;

                #endregion
                #region 环比
            case 4:
                var qoqList   = (List <ComparsionClass>)valuePair;
                var mfId      = new Guid(bmfId);
                var qoqEntity = qoqList.FirstOrDefault(a => a.ReferenceId == mfId);
                if (qoqEntity == null)
                {
                    qoqEntity = new ComparsionClass();
                }
                ICell yesterdayValue = row.CreateCell(startIndex);
                yesterdayValue.SetCellValue(GetPrecision(precision, qoqEntity.YesterDayVal));
                yesterdayValue.CellStyle = cellstyle;
                startIndex++;
                ICell todayValue = row.CreateCell(startIndex);
                todayValue.SetCellValue(GetPrecision(precision, qoqEntity.CurrentVal));
                todayValue.CellStyle = cellstyle;
                startIndex++;
                ICell qoqRate   = row.CreateCell(startIndex);
                var   rateValue = qoqEntity.YesterDayVal == 0 ? 0 : GetPrecision(precision, (qoqEntity.CurrentVal - qoqEntity.YesterDayVal) * 100 / qoqEntity.YesterDayVal);
                qoqRate.SetCellValue(rateValue);
                qoqRate.CellStyle = cellstyle;
                startIndex++;
                ICell monthValue = row.CreateCell(startIndex);
                monthValue.SetCellValue(GetPrecision(precision, qoqEntity.CurrentMonthVal));
                monthValue.CellStyle = cellstyle;
                startIndex++;
                ICell lastMonthValue = row.CreateCell(startIndex);
                lastMonthValue.SetCellValue(GetPrecision(precision, qoqEntity.LastMonthVal));
                lastMonthValue.CellStyle = cellstyle;
                startIndex++;
                ICell qoqMonthRate   = row.CreateCell(startIndex);
                var   monthRateValue = qoqEntity.LastMonthVal == 0 ? 0.0 : GetPrecision(precision, (qoqEntity.CurrentMonthVal - qoqEntity.LastMonthVal) * 100 / qoqEntity.LastMonthVal);
                qoqMonthRate.SetCellValue(monthRateValue);
                qoqMonthRate.CellStyle = cellstyle;

                endIndex = startIndex;
                break;

                #endregion
                #region 日抄表能耗
            case 5:
                var dayCheckList   = (List <RealTimeData>)valuePair;
                var dayCheckEntity = dayCheckList.FirstOrDefault(a => a.mftId == bmfId);
                if (dayCheckEntity == null)
                {
                    dayCheckEntity = new RealTimeData();
                }
                ICell preValue = row.CreateCell(startIndex);
                preValue.SetCellValue(GetPrecision(precision, dayCheckEntity.PreData));
                preValue.CellStyle = cellstyle;
                startIndex++;
                ICell preDateValue = row.CreateCell(startIndex);
                preDateValue.SetCellValue(dayCheckEntity.LastTime);
                preDateValue.CellStyle = cellstyle;
                startIndex++;
                ICell currentDateValue = row.CreateCell(startIndex);
                currentDateValue.SetCellValue(dayCheckEntity.Htime);
                currentDateValue.CellStyle = cellstyle;
                startIndex++;
                ICell currentValue = row.CreateCell(startIndex);
                currentValue.SetCellValue(GetPrecision(precision, dayCheckEntity.NextData));
                currentValue.CellStyle = cellstyle;
                startIndex++;
                ICell energyValue = row.CreateCell(startIndex);
                energyValue.SetCellValue(GetPrecision(precision, dayCheckEntity.Sum));
                energyValue.CellStyle = cellstyle;
                startIndex++;

                endIndex = startIndex;
                break;

                #endregion
                #region 峰谷平
            case 6:
                #endregion
                #region 日跨时间范围
            case 7:
                #endregion
                #region 班组能耗
            case 8:
                #endregion
                #region 时间点
            case 9:
                #endregion
                #region 灵活式
            case 10:
                break;
                #endregion
            }
        }
コード例 #31
0
        private void GetReportDataSource(ISheet sheet, HSSFWorkbook workbook, int rptType, string precision,
                                         string startTime, string endTime, bool isShouldResizeColumn, Guid companyId)
        {
            List <Guid> bmfIds = new List <Guid>();

            GetBmfIds(sheet, bmfIds);

            Trans    trans = new Trans();
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;

            switch (rptType)
            {
                #region 年(每月)报表
            case 1:
                trans.stime = startTime;
                trans.etime = trans.stime;
                var monthRecords = DataHelper.GetMonRecordByWhere(trans, bmfIds, companyId);
                SheetVariableReplace(sheet, workbook, monthRecords.OrderBy(a => a.HTime).ToList(),
                                     new DateTime(int.Parse(trans.stime), 1, 1),
                                     new DateTime(int.Parse(trans.stime), 12, 31),
                                     rptType, precision, isShouldResizeColumn);
                break;

                #endregion
                #region 月(每日)报表
            case 2:
                var dateArr = startTime.Split('-');
                var year    = dateArr[0];
                var month   = dateArr[1];
                var days    = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));
                trans.stime = year + "-" + month + "-01";
                trans.etime = year + "-" + month + "-" + days;
                var dayRecords = DataHelper.GetDayRecordByWhere(trans, bmfIds, companyId);
                SheetVariableReplace(sheet, workbook, dayRecords.OrderBy(a => a.HTime).ToList(),
                                     DateTime.Parse(trans.stime), DateTime.Parse(trans.etime),
                                     rptType, precision, isShouldResizeColumn);
                break;

                #endregion
                #region  比报表
            case 3:
                trans.stime = startTime;
                trans.etime = trans.stime;
                var yearMonthRecords = DataHelper.GetMonRecordByWhere(trans, bmfIds, companyId);
                trans.stime     = (Convert.ToInt32(trans.stime) - 1).ToString();
                trans.tempetime = trans.stime;
                var      lastYearMonthRecords = DataHelper.GetMonRecordByWhere(trans, bmfIds, companyId);
                var      yoyList   = new List <ComparsionDto>();
                DateTime yoysTime  = new DateTime(int.Parse(startTime), 1, 1);
                DateTime yoyeTime  = new DateTime(int.Parse(startTime), 12, 1);
                DateTime lastHtime = yoysTime.AddYears(-1);
                foreach (var bmfId in bmfIds)
                {
                    lastHtime = yoysTime.AddYears(-1);
                    for (DateTime sstime = yoysTime; sstime <= yoyeTime; sstime = sstime.AddMonths(1), lastHtime = lastHtime.AddMonths(1))
                    {
                        var    mfId        = bmfId.ToString();
                        double totalData   = 0.0d;
                        var    currentData = yearMonthRecords.FirstOrDefault(a => a.MfId == mfId && a.HTime == sstime);
                        var    lastData    = lastYearMonthRecords.FirstOrDefault(a => a.MfId == mfId && a.HTime == lastHtime);
                        if (lastData == null || lastData.TotalData == 0)
                        {
                            if (currentData != null && currentData.TotalData != 0)
                            {
                                totalData = 100;
                            }
                            else
                            {
                                totalData = 0;
                            }
                        }
                        else if (currentData == null || currentData.TotalData == 0)
                        {
                            if (lastData != null && lastData.TotalData != 0)
                            {
                                totalData = -100;
                            }
                            else
                            {
                                totalData = 0;
                            }
                        }
                        else
                        {
                            totalData = (currentData.TotalData - lastData.TotalData) / lastData.TotalData;
                        }

                        ComparsionDto record = new ComparsionDto
                        {
                            HTime       = sstime,
                            MfId        = mfId,
                            CurrentData = currentData == null ? 0 : currentData.TotalData,
                            LastData    = lastData == null ? 0 : lastData.TotalData,
                            Rate        = totalData,
                        };
                        yoyList.Add(record);
                    }
                }
                SheetVariableReplace(sheet, workbook, yoyList.OrderBy(a => a.HTime).ToList(),
                                     yoysTime, yoyeTime, rptType, precision, isShouldResizeColumn);
                break;

                #endregion
                #region 环比
            case 4:
                bmfIds = bmfIds.Distinct().ToList();
                var now       = DateTime.Now;
                var yesterday = now.AddDays(-1);
                var qoqmonth  = DateTime.Parse(now.ToString("yyyy-MM-01"));
                var lastMonth = qoqmonth.AddMonths(-1);
                List <ComparsionClass> cmpList = new List <ComparsionClass>();
                foreach (var mfId in bmfIds)
                {
                    BaseRecord      dayRecord  = DataHelper.GetDayRecord(mfId, companyId, now);
                    ComparsionClass comparsion = new ComparsionClass();
                    comparsion.CurrentVal      = dayRecord == null ? 0 : dayRecord.TotalData;
                    dayRecord                  = DataHelper.GetDayRecord(mfId, companyId, yesterday);
                    comparsion.YesterDayVal    = dayRecord == null ? 0 : dayRecord.TotalData;
                    dayRecord                  = DataHelper.GetMonthRecord(mfId, companyId, qoqmonth);
                    comparsion.CurrentMonthVal = dayRecord == null ? 0 : dayRecord.TotalData;
                    dayRecord                  = DataHelper.GetMonthRecord(mfId, companyId, lastMonth);
                    comparsion.LastMonthVal    = dayRecord == null ? 0 : dayRecord.TotalData;
                    comparsion.ReferenceId     = mfId;
                    cmpList.Add(comparsion);
                }
                SheetVariableReplace(sheet, workbook, cmpList, DateTime.Now, DateTime.Now,
                                     rptType, precision, isShouldResizeColumn);
                break;

                #endregion
                #region 日抄表能耗报表
            case 5:
                var factory = ServiceFactory.CreateService <ICollectValuesService>();
                var time    = DateTime.Parse(startTime);
                stime = time.AddSeconds(-1);
                List <RealTimeData> datas = new List <RealTimeData>();
                foreach (var bmfId in bmfIds)
                {
                    RealTimeData data     = new RealTimeData();
                    var          autodata = factory.GetEarliestAutoDatasByMfIdLessThanTime(companyId, bmfId, stime);//cy
                    if (autodata != null)
                    {
                        data.LastTime = autodata.Mt.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    data.PreData = autodata == null ? 0 : autodata.Mv;
                    var nextautodata = factory.GetEarliestAutoDatasByMfIdLessThanTime(companyId, bmfId, DateTime.Now);    //cy
                    data.NextData = nextautodata == null ? 0 : nextautodata.Mv;
                    data.mftId    = bmfId.ToString();
                    data.Sum      = data.NextData - data.PreData;
                    if (nextautodata != null)
                    {
                        data.Htime = nextautodata.Mt.ToString("yyyy-MM-dd HH:mm:ss");    //当前时间
                    }
                    datas.Add(data);
                }
                factory.CloseService();
                SheetVariableReplace(sheet, workbook, datas, DateTime.Now, DateTime.Now,
                                     rptType, precision, isShouldResizeColumn);
                break;

                #endregion
                #region 峰谷平能耗报表
            case 6:
                #endregion
                #region 日跨时间范围报表
            case 7:
                #endregion
                #region 班组能耗报表
            case 8:
                #endregion
                #region 时间点抄表报表
            case 9:
                #endregion
                #region 灵活式结构
            case 10:
                #endregion
                #region  定类型报表
            case 11:
                break;
                #endregion
            }
        }
コード例 #32
0
        private async Task <RealTimeData> Filter(string stockId)
        {
            DayData dayData = null;


            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <StockContext>();

                var helper = new Utils.Utility(db);

                int numcnt = _arg.CircleDaysNum + _arg.NearDaysNum;

                //当天的数据算一个
                var dayDataList = await helper.GetDayData(stockId, numcnt, _arg.BaseDate);

                //使用成交量,需要复权
                //复权,会改变dayDataList中的数据
                await Utils.CalcData.FuQuan(db, stockId, dayDataList);

                bool fitFlag = false;

                if (dayDataList.Count == numcnt)
                {
                    for (int j = 0; j < _arg.NearDaysNum; j++)
                    {
                        DayData current = dayDataList[_arg.NearDaysNum - 1 - j];

                        if (current.ZhangDieFu >= _arg.ZhangFu)
                        {
                            float sum = 0;

                            //对数据进行处理,当日的不处理
                            for (int i = 0; i < _arg.CircleDaysNum; i++)
                            {
                                sum += dayDataList[dayDataList.Count - 1 - (i + j)].Volume;
                            }
                            float avrage = sum / _arg.CircleDaysNum;

                            //判断突破的时间

                            if (current.Volume >= avrage * _arg.VolTimesNum)
                            {
                                dayData = current;//满足要求
                                fitFlag = true;

                                break;
                            }
                        }
                    }
                }

                //如果是null,表示不符合筛选条件

                RealTimeData real = null;
                if (fitFlag)
                {
                    real = await helper.ConvertDayToReal(dayData);
                }

                return(real);
            }
        }