Пример #1
0
        private bool UpdateList(string updateKey, string related, string updateType, ref SqlDb sql)
        {
            var ret = true;
            try
            {

                var redis = new RedisClient(ConfigRedis.Host, ConfigRedis.Port);

                var symbol = updateKey;
                var date = "";
                if (updateKey.Contains("."))
                {
                    symbol = updateKey.Substring(0, updateKey.IndexOf("."));
                    date = updateKey.Substring(updateKey.IndexOf(".") + 1);
                }
                switch (related)
                {
                    case "FP":
                        #region FP
                        try
                        {
                            var keylist = string.Format(RedisKey.PriceHistoryKeys, symbol);
                            var ls = redis.ContainsKey(keylist) ? redis.Get<List<String>>(keylist) : new List<string>();
                            //log.WriteEntry(symbol + "-price-" + DateTime.Now, EventLogEntryType.Information);
                            var pdt = (date == "" || ls.Count == 0) ? sql.GetPriceHistory(symbol, -1) : sql.GetPriceHistory(symbol, date);
                            //log.WriteEntry(symbol + "-price-" + DateTime.Now, EventLogEntryType.Information);
                            foreach (DataRow pdr in pdt.Rows)
                            {
                                var key = string.Format(RedisKey.PriceHistory, symbol, ((DateTime)pdr["TradeDate"]).ToString("yyyyMMdd"));

                                var price = new StockHistory() { TradeDate = (DateTime)pdr["TradeDate"], ClosePrice = double.Parse(pdr["ClosePrice"].ToString()), AveragePrice = double.Parse(pdr["AveragePrice"].ToString()), BasicPrice = double.Parse(pdr["BasicPrice"].ToString()), Ceiling = double.Parse(pdr["Ceiling"].ToString()), Floor = double.Parse(pdr["Floor"].ToString()), Volume = double.Parse(pdr["Volume"].ToString()), TotalValue = double.Parse(pdr["TotalValue"].ToString()), AgreedValue = double.Parse(pdr["AgreedValue"].ToString()), AgreedVolume = double.Parse(pdr["AgreedVolume"].ToString()), Symbol = symbol, KLGDDot1 = double.Parse(pdr["VolumePhase1"].ToString()), KLGDDot2 = double.Parse(pdr["VolumePhase2"].ToString()), KLGDDot3 = double.Parse(pdr["VolumePhase3"].ToString()), OpenPrice = double.Parse(pdr["OpenPrice"].ToString()), HighPrice = double.Parse(pdr["HighPrice"].ToString()), LowPrice = double.Parse(pdr["LowPrice"].ToString()) };
                                if (redis.ContainsKey(key))
                                    redis.Set<StockHistory>(key, price);
                                else
                                    redis.Add<StockHistory>(key, price);

                                if (!ls.Contains(key)) ls.Add(key);
                            }
                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set<List<string>>(keylist, ls);
                            else
                                redis.Add<List<string>>(keylist, ls);
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FP : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        //var test = redis.Get<List<string>>(keylist);
                        #endregion
                        break;
                    case "FO":
                        #region FO
                        try
                        {
                            var keylist = string.Format(RedisKey.OrderHistoryKeys, symbol);
                            var ls = redis.ContainsKey(keylist) ? redis.Get<List<String>>(keylist) : new List<string>();

                            var pdt = (date == "" || ls.Count == 0) ? sql.GetOrderHistory(symbol, 1000) : sql.GetOrderHistory(symbol, date);
                            foreach (DataRow pdr in pdt.Rows)
                            {
                                var key = string.Format(RedisKey.OrderHistory, symbol, ((DateTime)pdr["Trading_Date"]).ToString("yyyyMMdd"));

                                var order = new OrderHistory() { TradeDate = (DateTime)pdr["Trading_Date"], BuyOrderCount = double.Parse(pdr["Bid_Order"].ToString()), BuyVolume = double.Parse(pdr["Bid_Volume"].ToString()), SellOrderCount = double.Parse(pdr["Offer_Order"].ToString()), SellVolume = double.Parse(pdr["Offer_Volume"].ToString()), Symbol = symbol }; //Volume = double.Parse(pdr["Volume"].ToString()), Price = double.Parse(pdr["Price"].ToString()), BasicPrice = double.Parse(pdr["BasicPrice"].ToString()), Ceiling = double.Parse(pdr["Ceiling"].ToString()), Floor = double.Parse(pdr["Floor"].ToString()), 
                                if (redis.ContainsKey(key))
                                    redis.Set<OrderHistory>(key, order);
                                else
                                    redis.Add<OrderHistory>(key, order);

                                if (!ls.Contains(key)) ls.Add(key);
                            }
                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set<List<string>>(keylist, ls);
                            else
                                redis.Add<List<string>>(keylist, ls);
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FO : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FIT":
                        #region FIT
                        try
                        {
                            var keylist = string.Format(RedisKey.InternalHistoryKeys, symbol);
                            var ls = new List<string>(); //redis.ContainsKey(keylist) ? redis.Get<List<String>>(keylist) : new List<string>();
                            
                            var pdt = sql.GetInternalHistory(symbol, -1);
                            
                            foreach (DataRow pdr in pdt.Rows)
                            {
                                var key = string.Format(RedisKey.InternalHistory, symbol, (((DateTime?)pdr["NgayThongBao"]) ?? DateTime.Now).ToString("yyyyMMdd"), pdr["ID"], pdr["ShareHolder_ID"] + ":" + pdr["ShareHolderCode"]);
                                var order = new InternalHistory() { Stock = symbol, RelatedMan = pdr["NguoiLienQuan"].ToString(), RelatedManPosition = pdr["ChucVuNguoiLienQuan"].ToString(), VolumeBeforeTransaction = double.Parse(pdr["SLCPTruocGD"].ToString()), PlanBuyVolume = double.Parse(pdr["DangKy_Mua"].ToString()), PlanSellVolume = double.Parse(pdr["DangKy_Ban"].ToString()), PlanBeginDate = pdr["DangKy_TuNgay"].Equals(DBNull.Value) ? null : (DateTime?)pdr["DangKy_TuNgay"], PlanEndDate = pdr["DangKy_DenNgay"].Equals(DBNull.Value) ? null : (DateTime?)pdr["DangKy_DenNgay"], RealBuyVolume = double.Parse(pdr["ThucHien_Mua"].ToString()), RealSellVolume = double.Parse(pdr["ThucHien_Ban"].ToString()), RealEndDate = pdr["ThucHien_NgayKetThuc"].Equals(DBNull.Value) ? null : (DateTime?)pdr["ThucHien_NgayKetThuc"], PublishedDate = pdr["NgayThongBao"].Equals(DBNull.Value) ? null : (DateTime?)pdr["NgayThongBao"], VolumeAfterTransaction = double.Parse(pdr["SLCPSauGD"].ToString()), TransactionNote = pdr["GhiChu"].ToString(), HolderID = pdr["ShareHolder_ID"].ToString(), ShareHolderCode = pdr["ShareHolderCode"].ToString() }; //TransactionMan = pdr["FullName"].ToString(), TransactionManPosition = pdr["ChucVu"].ToString(), 
                                var tochuc = pdr["ToChuc"].ToString();
                                order.TransactionMan = tochuc.IndexOf("--") > 0 ? tochuc.Substring(0, tochuc.IndexOf("--")) : tochuc;
                                order.TransactionManPosition = tochuc.IndexOf("--") > 0 && tochuc.IndexOf("--") < tochuc.Length - 2 ? tochuc.Substring(tochuc.IndexOf("--") + 2) : "";

                                if (redis.ContainsKey(key))
                                    redis.Set<InternalHistory>(key, order);
                                else
                                    redis.Add<InternalHistory>(key, order);

                                if (!ls.Contains(key)) ls.Add(key);
                            }
                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set<List<string>>(keylist, ls);
                            else
                                redis.Add<List<string>>(keylist, ls);
                            var internalkeys = redis.SearchKeys(string.Format(RedisKey.InternalHistory, symbol, "*", "*", "*")) ?? new List<string>();
                            foreach (var internalkey in internalkeys)
                            {
                                if(!ls.Contains(internalkey)) redis.Remove(internalkey);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FIT : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FFT":
                        #region FFT
                        try
                        {
                            var keylist = string.Format(RedisKey.ForeignHistoryKeys, symbol);
                            var ls = redis.ContainsKey(keylist) ? redis.Get<List<String>>(keylist) : new List<string>();

                            var pdt = (date == "" || ls.Count == 0) ? sql.GetForeignHistory(symbol, -1) : sql.GetForeignHistory(symbol, date);
                            foreach (DataRow pdr in pdt.Rows)
                            {
                                var key = string.Format(RedisKey.ForeignHistory, symbol, ((DateTime)pdr["Trading_Date"]).ToString("yyyyMMdd"));

                                var order = new ForeignHistory() { TradeDate = (DateTime)pdr["Trading_Date"], BuyVolume = double.Parse(pdr["Buying_Volume"].ToString()), BuyValue = double.Parse(pdr["Buying_Value"].ToString()), SellVolume = double.Parse(pdr["Selling_Volume"].ToString()), SellValue = double.Parse(pdr["Selling_Value"].ToString()), Room = double.Parse(pdr["CurrentRoom"].ToString()), TotalRoom = double.Parse(pdr["TotalRoom"].ToString()), Percent = double.Parse(pdr["SoHuu"].ToString()), Symbol = symbol }; //, BasicPrice = double.Parse(pdr["BasicPrice"].ToString()), ClosePrice = double.Parse(pdr["ClosePrice"].ToString()), AveragePrice = double.Parse(pdr["AveragePrice"].ToString()) 
                                if (redis.ContainsKey(key))
                                    redis.Set<ForeignHistory>(key, order);
                                else
                                    redis.Add<ForeignHistory>(key, order);

                                if (!ls.Contains(key)) ls.Add(key);
                            }
                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set<List<string>>(keylist, ls);
                            else
                                redis.Add<List<string>>(keylist, ls);
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FFT : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FS":
                        #region FS
                        try
                        {
                            var skey = RedisKey.KeyStockList;
                            var sdt = sql.GetSymbolList(-1);
                            var sls = new List<StockCompact>();
                            var hnx = new List<StockCompact>();
                            var hsx = new List<StockCompact>();
                            var upc = new List<StockCompact>();
                            foreach (DataRow sdr in sdt.Rows)
                            {
                                var stock = new StockCompact() { Symbol = sdr["Symbol"].ToString(), CategoryId = int.Parse(sdr["StockIndustryId"].ToString()), TradeCenterId = int.Parse(sdr["TradeCenterId"].ToString()) };
                                sls.Add(stock);
                                switch (stock.TradeCenterId)
                                {
                                    case 1: hsx.Add(stock); break;
                                    case 2: hnx.Add(stock); break;
                                    case 9: upc.Add(stock); break;
                                }
                            }
                            if (redis.ContainsKey(skey))
                                redis.Set(skey, sls);
                            else
                                redis.Add(skey, sls);
                            skey = string.Format(RedisKey.KeyStockListByCenter, "1");
                            if (redis.ContainsKey(skey))
                                redis.Set(skey, hsx);
                            else
                                redis.Add(skey, hsx);
                            skey = string.Format(RedisKey.KeyStockListByCenter, "2");
                            if (redis.ContainsKey(skey))
                                redis.Set(skey, hnx);
                            else
                                redis.Add(skey, hnx);
                            skey = string.Format(RedisKey.KeyStockListByCenter, "9");
                            if (redis.ContainsKey(skey))
                                redis.Set(skey, upc);
                            else
                                redis.Add(skey, upc);
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FS : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FA":
                        #region FA
                        try
                        {
                            var keylist = RedisKey.KeyAnalysisReport;
                            var ls = (redis.ContainsKey(keylist)) ? redis.Get<List<string>>(keylist) : new List<string>();
                            var pdt = (date == "" || ls.Count == 0) ? sql.GetAnalysisReports("A", 2000) : sql.GetAnalysisReports("A", date);
                            var rs = new List<string>();
                            if (ls.Count > 0 && date != "")
                            {
                                //remove reports by date
                                var d = date.Replace(".", "");
                                rs = ls.FindAll(s => s.Substring(0, 8) == d);
                                foreach (var r in rs)
                                {
                                    ls.Remove(r);

                                }
                            }
                            foreach (DataRow rdr in pdt.Rows)
                            {

                                var key = string.Format(RedisKey.KeyAnalysisReportDetail, rdr["ID"]);
                                var obj = new Reports() { ID = int.Parse(rdr["ID"].ToString()), Body = rdr["Des"].ToString(), DateDeploy = (DateTime)rdr["PublishDate"], file = new FileObject() { FileName = rdr["FileName"].ToString(), FileUrl = "http://images1.cafef.vn/Images/Uploaded/DuLieuDownload/PhanTichBaoCao/" + rdr["FileName"] }, IsHot = (rdr["IsHot"].ToString().ToLower() == "true"), ResourceCode = rdr["Source"].ToString(), Symbol = rdr["Symbol"].ToString(), Title = rdr["title"].ToString(), SourceID = int.Parse(rdr["SourceId"].ToString()), ResourceName = rdr["SourceFullName"].ToString(), ResourceLink = rdr["SourceUrl"].ToString() };
                                var id = obj.DateDeploy.ToString("yyyyMMdd") + obj.ID;
                                if (redis.ContainsKey(key))
                                    redis.Set(key, obj);
                                else
                                    redis.Add(key, obj);
                                if (!ls.Contains(id)) ls.Add(id);
                            }
                            foreach (var r in rs)
                            {
                                if (ls.Contains(r)) continue;
                                var id = r.Substring(8);
                                var key = string.Format(RedisKey.KeyAnalysisReportDetail, id);
                                if (redis.ContainsKey(key))
                                    redis.Remove(key);
                            }
                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set(keylist, ls);
                            else
                                redis.Add(keylist, ls);

                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FA : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FT":
                        #region FT
                        try
                        {
                            var fdt = sql.GetTopStock();

                            UpdateTopStock(RedisKey.KeyTopStockCenter.All, RedisKey.KeyTopStockType.EPS, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ho, RedisKey.KeyTopStockType.EPS, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ha, RedisKey.KeyTopStockType.EPS, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.All, RedisKey.KeyTopStockType.MarketCap, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ho, RedisKey.KeyTopStockType.MarketCap, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ha, RedisKey.KeyTopStockType.MarketCap, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.All, RedisKey.KeyTopStockType.PE, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ho, RedisKey.KeyTopStockType.PE, ref redis, ref fdt);
                            UpdateTopStock(RedisKey.KeyTopStockCenter.Ha, RedisKey.KeyTopStockType.PE, ref redis, ref fdt);
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FT : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        break;
                    case "FN":
                        #region FN
                        try
                        {
                            var keylist = string.Format(RedisKey.KeyCompanyNewsByCate, 0); //Tất cả
                            var ls = (redis.ContainsKey(keylist)) ? redis.Get<List<string>>(keylist) : new List<string>();
                            var pdt = (date == "" || ls.Count == 0) ? sql.GetCompanyNews("A", 1000) : sql.GetCompanyNews("A", date);

                            var key1 = string.Format(RedisKey.KeyCompanyNewsByCate, 1); //Tình hình SXKD & Phân tích khác
                            var key2 = string.Format(RedisKey.KeyCompanyNewsByCate, 2); // Cổ tức - Chốt quyền
                            var key3 = string.Format(RedisKey.KeyCompanyNewsByCate, 3); // Thay đổi nhân sự
                            var key4 = string.Format(RedisKey.KeyCompanyNewsByCate, 4); // Tăng vốn - Cổ phiếu quỹ
                            var key5 = string.Format(RedisKey.KeyCompanyNewsByCate, 5); // GD cđ lớn & cđ nội bộ
                            var cate1 = (redis.ContainsKey(key1)) ? redis.Get<List<string>>(key1) : new List<string>();

                            var cate2 = (redis.ContainsKey(key2)) ? redis.Get<List<string>>(key2) : new List<string>();
                            var cate3 = (redis.ContainsKey(key3)) ? redis.Get<List<string>>(key3) : new List<string>();

                            var cate4 = (redis.ContainsKey(key4)) ? redis.Get<List<string>>(key4) : new List<string>();
                            var cate5 = (redis.ContainsKey(key5)) ? redis.Get<List<string>>(key5) : new List<string>();

                            //remove bài trong ngày (dùng để xóa các tin thừa)
                            var rm = (date != "") ? ls.FindAll(key => key.StartsWith((date.Replace(".", "")))) : new List<string>();
                            foreach (var item in rm)
                            {
                                if (ls.Contains(item)) ls.Remove(item);
                                if (cate1.Contains(item)) cate1.Remove(item);
                                if (cate2.Contains(item)) cate2.Remove(item);
                                if (cate3.Contains(item)) cate3.Remove(item);
                                if (cate4.Contains(item)) cate4.Remove(item);
                                if (cate5.Contains(item)) cate5.Remove(item);
                            }

                            foreach (DataRow rdr in pdt.Rows)
                            {
                                var compact = new StockNews() { ID = int.Parse(rdr["ID"].ToString()), Body = "", DateDeploy = (DateTime)rdr["PostTime"], Image = "", Title = rdr["title"].ToString(), Sapo = "", TypeID = rdr["ConfigId"].ToString(), Symbol = rdr["StockSymbols"].ToString() };
                                var obj = new StockNews() { ID = int.Parse(rdr["ID"].ToString()), Body = rdr["Content"].ToString(), DateDeploy = (DateTime)rdr["PostTime"], Image = rdr["ImagePath"].ToString(), Title = rdr["title"].ToString(), Sapo = rdr["SubContent"].ToString(), TypeID = rdr["ConfigId"].ToString(), Symbol = rdr["StockSymbols"].ToString() };
                                for (int i = 0xD800; i <= 0xDFFF; i++)
                                {
                                    obj.Body = obj.Body.Replace((char)i, ' ');
                                }
                                var key = obj.DateDeploy.ToString("yyyyMMddHHmm") + obj.ID;
                                var compactkey = string.Format(RedisKey.KeyCompanyNewsCompact, obj.ID);
                                if (redis.ContainsKey(compactkey))
                                    redis.Set(compactkey, compact);
                                else
                                    redis.Add(compactkey, compact);
                                var detailkey = string.Format(RedisKey.KeyCompanyNewsDetail, obj.ID);
                                if (redis.ContainsKey(detailkey))
                                    redis.Set(detailkey, obj);
                                else
                                    redis.Add(detailkey, obj);

                                if (!ls.Contains(key)) ls.Add(key);
                                #region Update category list
                                if (obj.TypeID.Contains("1"))
                                {
                                    if (!cate1.Contains(key)) cate1.Add(key);
                                }
                                else
                                {
                                    if (cate1.Contains(key)) cate1.Remove(key);
                                }
                                if (obj.TypeID.Contains("2"))
                                {
                                    if (!cate2.Contains(key)) cate2.Add(key);
                                }
                                else
                                {
                                    if (cate2.Contains(key)) cate2.Remove(key);
                                }
                                if (obj.TypeID.Contains("3"))
                                {
                                    if (!cate3.Contains(key)) cate3.Add(key);
                                }
                                else
                                {
                                    if (cate3.Contains(key)) cate3.Remove(key);
                                }
                                if (obj.TypeID.Contains("4"))
                                {
                                    if (!cate4.Contains(key)) cate4.Add(key);
                                }
                                else
                                {
                                    if (cate4.Contains(key)) cate4.Remove(key);
                                }
                                if (obj.TypeID.Contains("5"))
                                {
                                    if (!cate5.Contains(key)) cate5.Add(key);
                                }
                                else
                                {
                                    if (cate5.Contains(key)) cate5.Remove(key);
                                }
                                #endregion
                            }

                            //if (date != "")
                            //{
                            //remove bài trong ngày (dùng để xóa các tin thừa)
                            foreach (var item in rm)
                            {
                                if (ls.Contains(item)) continue;
                                var id = item.Substring(12);
                                var compactkey = string.Format(RedisKey.KeyCompanyNewsCompact, id);
                                if (redis.ContainsKey(compactkey))
                                    redis.Remove(compactkey);
                                var detailkey = string.Format(RedisKey.KeyCompanyNewsDetail, id);
                                if (redis.ContainsKey(detailkey))
                                    redis.Remove(detailkey);
                            }
                            //}

                            ls.Sort();
                            ls.Reverse();
                            if (redis.ContainsKey(keylist))
                                redis.Set(keylist, ls);
                            else
                                redis.Add(keylist, ls);
                            #region Update category list
                            cate1.Sort();
                            cate1.Reverse();
                            if (redis.ContainsKey(key1))
                                redis.Set(key1, cate1);
                            else
                                redis.Add(key1, cate1);
                            cate2.Sort();
                            cate2.Reverse();
                            if (redis.ContainsKey(key2))
                                redis.Set(key2, cate2);
                            else
                                redis.Add(key2, cate2);
                            cate3.Sort();
                            cate3.Reverse();
                            if (redis.ContainsKey(key3))
                                redis.Set(key3, cate3);
                            else
                                redis.Add(key3, cate3);
                            cate4.Sort();
                            cate4.Reverse();
                            if (redis.ContainsKey(key4))
                                redis.Set(key4, cate4);
                            else
                                redis.Add(key4, cate4);
                            cate5.Sort();
                            cate5.Reverse();
                            if (redis.ContainsKey(key5))
                                redis.Set(key5, cate5);
                            else
                                redis.Add(key5, cate5);
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            log.WriteEntry(symbol + " : FN : " + ex.ToString(), EventLogEntryType.Error);
                            ret = false;
                        }
                        #endregion
                        #region Update top 100 news
                        var topkey = RedisKey.KeyTop20News;
                        var ndt = sql.GetCompanyNews("A", 100);
                        var topls = new List<StockNews>();
                        foreach (DataRow ndr in ndt.Rows)
                        {
                            var da = (DateTime)ndr["PostTime"];
                            topls.Add(new StockNews() { ID = int.Parse(ndr["ID"].ToString()), Body = "", DateDeploy = (DateTime)ndr["PostTime"], Image = "", Title = ndr["title"].ToString(), Sapo = "", TypeID = ndr["ConfigId"].ToString(), Symbol = ndr["StockSymbols"].ToString() });
                        }
                        if (redis.ContainsKey(topkey))
                            redis.Set(topkey, topls);
                        else
                            redis.Add(topkey, topls);
                        #endregion
                        break;
                    case "FND":
                        #region "Fund Transaction"
                        var fndkeylist = string.Format(RedisKey.FundHistoryKeys, symbol);
                        //var fndls = redis.ContainsKey(fndkeylist) ? redis.Get<List<String>>(fndkeylist) : new List<string>();
                        var fndls = new List<string>();
                        var fndt = sql.GetFundHistory(symbol, -1);
                        foreach (DataRow fndr in fndt.Rows)
                        {
                            var key = string.Format(RedisKey.FundHistory, symbol, ((DateTime)fndr["TradingDate"]).ToString("yyyyMMdd"));

                            var order = new FundHistory() { Symbol = symbol, TradeDate = (DateTime)fndr["TradingDate"], TransactionType = fndr["Buy_Sale"].ToString() == "s" ? "Bán" : "Mua", PlanVolume = double.Parse(fndr["RegisteredVol"].ToString()), TodayVolume = double.Parse(fndr["TodayTradingVol"].ToString()), AccumulateVolume = double.Parse(fndr["AccumVol"].ToString()), ExpiredDate = (DateTime)fndr["ExpireDate"] };
                            if (redis.ContainsKey(key))
                                redis.Set<FundHistory>(key, order);
                            else
                                redis.Add<FundHistory>(key, order);

                            if (!fndls.Contains(key)) fndls.Add(key);
                        }
                        fndls.Sort();
                        fndls.Reverse();
                        if (redis.ContainsKey(fndkeylist))
                            redis.Set<List<string>>(fndkeylist, fndls);
                        else
                            redis.Add<List<string>>(fndkeylist, fndls);
                        break;
                        #endregion
                    case "CI":

                        break;
                    case "CN":
                        #region CEO

                        var ceokey = string.Format(RedisKey.CeoKey, symbol);
                        var cdt = sql.GetCeosNew_Profile(symbol);
                        if (cdt.Rows.Count == 0)
                        {
                            if (redis.ContainsKey(ceokey)) redis.Remove(ceokey);
                        }
                        else
                        {
                            var ceo = new Ceo();
                            if (redis.ContainsKey(ceokey))
                            {
                                ceo = redis.Get<Ceo>(ceokey) ?? new Ceo();
                            }
                            ceo.CeoName = cdt.Rows[0]["CeoName"].ToString(); ceo.CeoBirthday = cdt.Rows[0]["CeoBirthday"].ToString(); ceo.CeoIdNo = cdt.Rows[0]["CeoIdNo"].ToString(); ceo.CeoAchievements = cdt.Rows[0]["CeoAchievements"].ToString(); ceo.CeoHomeTown = cdt.Rows[0]["CeoHomeTown"].ToString(); ceo.CeoSchoolDegree = cdt.Rows[0]["CeoLevel"].ToString();
                            ceo.CeoCode = cdt.Rows[0]["CeoCode"].ToString();

                            if (ceo.CeoBirthday.Contains("/"))
                            {
                                ceo.CeoBirthday = ceo.CeoBirthday.Substring(ceo.CeoBirthday.LastIndexOf("/") + 1);
                            }

                            try
                            {
                                //school title
                                var css = new List<CeoSchool>();
                                var sdt = sql.GetCeosNew_School(symbol);
                                foreach (DataRow sdr in sdt.Rows)
                                {
                                    css.Add(new CeoSchool() { CeoTitle = sdr["CeoTitle"].ToString(), SchoolTitle = sdr["SchoolTitle"].ToString(), SchoolYear = sdr["SchoolYear"].ToString() });
                                }
                                ceo.CeoSchool = css;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO School : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            try
                            {
                                //ceo position
                                var cps = new List<CeoPosition>();
                                var pdt = sql.GetCeosNew_Position(symbol);
                                foreach (DataRow pdr in pdt.Rows)
                                {
                                    var cp = new CeoPosition() { PositionTitle = pdr["PositionTitle"].ToString(), PositionCompany = pdr["PositionCompany"].ToString(), CeoSymbol = pdr["Symbol"].ToString(), CeoSymbolCenterId = int.Parse(pdr["TradeCenterId"].ToString()) };
                                    if (string.IsNullOrEmpty(cp.PositionTitle)) cp.PositionTitle = pdr["PositionName"].ToString();
                                    if (string.IsNullOrEmpty(cp.PositionCompany)) cp.PositionCompany = pdr["FullName"].ToString();

                                    //__/01/2007
                                    string cpd = pdr["CeoPosDate"].ToString();
                                    if (cpd.Contains("/"))
                                    {
                                        int day, month, year;
                                        if (!int.TryParse(cpd.Substring(0, cpd.IndexOf("/")), out day)) day = 0;
                                        cpd = cpd.Substring(cpd.IndexOf("/") + 1);
                                        if (!int.TryParse(cpd.Substring(0, cpd.IndexOf("/")), out month)) month = 0;
                                        cpd = cpd.Substring(cpd.IndexOf("/") + 1);
                                        if (!int.TryParse(cpd, out year)) year = 0;
                                        if (year == 0)
                                        {
                                            cp.CeoPosDate = "";
                                        }
                                        else if (day == 0 && month == 0)
                                        {
                                            cp.CeoPosDate = "" + year;
                                        }
                                        else if (month > 0 && day == 0)
                                        {
                                            cp.CeoPosDate = month + "/" + year;
                                        }
                                        else if (day > 0 && month > 0)
                                        {
                                            cp.CeoPosDate = day + "/" + month + "/" + year;
                                        }
                                        else
                                        {
                                            cp.CeoPosDate = "";
                                        }
                                    }

                                    cps.Add(cp);
                                }
                                ceo.CeoPosition = cps;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO Position : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            try
                            {
                                //asset
                                var cas = new List<CeoAsset>();
                                var adt = sql.GetCeosNew_Asset(symbol);
                                foreach (DataRow adr in adt.Rows)
                                {
                                    cas.Add(new CeoAsset() { Symbol = adr["Symbol"].ToString(), AssetVolume = double.Parse(adr["AssetVolume"].ToString()).ToString("#,##0"), UpdatedDate = ((DateTime)adr["UpdatedDate"]).ToString("dd/MM/yyyy") });
                                }
                                ceo.CeoAsset = cas;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO Asset : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            try
                            {
                                //relation
                                var crs = new List<CeoRelation>();
                                var rdt = sql.GetCeosNew_Relation(symbol);
                                foreach (DataRow rdr in rdt.Rows)
                                {
                                    crs.Add(new CeoRelation() { Symbol = rdr["Symbol"].ToString(), AssetVolume = double.Parse(rdr["AssetVolume"].ToString()).ToString("#,##0"), UpdatedDate = ((DateTime)rdr["UpdatedDate"]).ToString("dd/MM/yyyy"), Name = rdr["CeoName"].ToString(), CeoCode = rdr["CeoCode"].ToString(), RelationTitle = rdr["RelationTitle"].ToString() });
                                }
                                ceo.CeoRelation = crs;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO Relation : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            try
                            {
                                //process
                                var cos = new List<CeoProcess>();
                                var odt = sql.GetCeosNew_Process(symbol);
                                foreach (DataRow odr in odt.Rows)
                                {
                                    var begin = GetCeoDate(odr["ProcessBegin"].ToString());
                                    var end = GetCeoDate(odr["ProcessEnd"].ToString());
                                    var process = (begin != "" ? ("Từ " + begin + " ") : "") + (end != "" ? ((begin != "" ? "đến" : "Đến") + " " + end + "") : "");
                                    cos.Add(new CeoProcess() { ProcessBegin = odr["ProcessBegin"].ToString(), ProcessEnd = odr["ProcessEnd"].ToString(), ProcessDesc = process + (process == "" ? "" : " : ") + odr["ProcessDesc"].ToString(), Symbol = odr["Symbol"].ToString()});
                                }
                                ceo.CeoProcess = cos;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO Process : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            try
                            {
                                //news
                                var cns = new List<CeoNews>();
                                var wdt = sql.GetCeosNew_News(symbol);
                                var ids = "";
                                foreach (DataRow ndr in wdt.Rows)
                                {
                                    ids += "," + ndr["NewsId"];
                                }
                                if (ids != "")
                                {
                                    var wdt2 = sql.GetCeosNew_NewsDetail(ids);
                                    foreach (DataRow ndr in wdt2.Rows)
                                    {
                                        cns.Add(new CeoNews() { Title = ndr["News_Title"].ToString(), PublishDate = (DateTime)ndr["News_PublishDate"], NewsLink = string.Format("/{0}CA{1}/{2}.chn", ndr["News_Id"], ndr["Cat_ID"], CafeF.Redis.BL.Utils.UnicodeToKoDauAndGach(ndr["News_Title"].ToString())) });
                                    }
                                }
                                ceo.CeoNews = cns;
                            }
                            catch (Exception ex)
                            {
                                log.WriteEntry(symbol + " : CEO News : " + ex.ToString(), EventLogEntryType.Error);
                                ret = false;
                            }
                            if (redis.ContainsKey(ceokey))
                            {
                                redis.Set(ceokey, ceo);
                            }
                            else
                            {
                                redis.Add(ceokey, ceo);
                            }
                        }
                        #endregion
                        break;
                    case "FC":
                        #region Lịch sự kiện 
                        var lskdt = sql.GetLichSuKien(date);
                        var keys = redis.ContainsKey(RedisKey.KeyLichSuKien) ? redis.Get<List<string>>(RedisKey.KeyLichSuKien) : new List<string>();
                        var removals = keys.FindAll(s => s.Substring(0,8) == date.Replace(".", ""));
                        foreach(var removal in removals)
                        {
                            var key = string.Format(RedisKey.KeyLichSuKienObject, removal.Substring(removal.LastIndexOf(":") + 1));
                            if (redis.ContainsKey(key)) redis.Remove(key);
                            keys.Remove(removal);
                        }
                        foreach (DataRow ldr in lskdt.Rows)
                        {
                            var o = new LichSuKien() { ID = int.Parse(ldr["ID"].ToString()), LoaiSuKien = ldr["EventType_List"].ToString(), MaCK = ldr["StockSymbols"].ToString(), MaSan = 0, News_ID = ldr["News_ID"].ToString(), Title = ldr["EventTitle"].ToString(), NgayBatDau = ldr["NgayBatDau"].ToString(), NgayKetThuc = ldr["NgayKetThuc"].ToString(), NgayThucHien = ldr["NgayThucHien"].ToString(), TenCty = "", TomTat = "", PostDate = (DateTime)ldr["PostDate"] };
                            try
                            {
                                o.EventDate = (DateTime)ldr["EventDate"];
                            }
                            catch (Exception)
                            {
                                o.EventDate = DateTime.Parse("2000-01-01");
                            }
                            var key = string.Format(RedisKey.KeyLichSuKienObject, o.ID);
                            if (redis.ContainsKey(key))
                                redis.Set(key, o);
                            else
                                redis.Add(key, o);
                            key = string.Format(RedisKey.KeyLichSuKienObjectInList, o.EventDate.ToString("yyyyMMdd"), string.IsNullOrEmpty(o.LoaiSuKien.Trim()) ? "_" : o.LoaiSuKien, o.ID);
                            if (!keys.Contains(key)) keys.Add(key);
                        }
                        if (redis.ContainsKey(RedisKey.KeyLichSuKien))
                            redis.Set(RedisKey.KeyLichSuKien, keys);
                        else
                            redis.Add(RedisKey.KeyLichSuKien, keys);
                        #endregion
                        #region Lịch sự kiện tóm tắt
                        lskdt = sql.GetLichSuKienTomTat();
                        var lls = new List<LichSuKien>();
                        foreach (DataRow ldr in lskdt.Rows)
                        {
                            var o = new LichSuKien() { ID = int.Parse(ldr["ID"].ToString()), LoaiSuKien = ldr["EventType_List"].ToString(), MaCK = ldr["StockSymbols"].ToString(), MaSan = 0, News_ID = ldr["News_ID"].ToString(), Title = ldr["EventTitle"].ToString(), NgayBatDau = ldr["NgayBatDau"].ToString(), NgayKetThuc = ldr["NgayKetThuc"].ToString(), NgayThucHien = ldr["NgayThucHien"].ToString(), TenCty = "", TomTat = "", PostDate = (DateTime)ldr["PostDate"] };
                            try
                            {
                                o.EventDate = (DateTime)ldr["EventDate"];
                            }
                            catch (Exception)
                            {
                                o.EventDate = DateTime.Parse("2000-01-01");
                            }
                            lls.Add(o);
                        }
                        if (redis.ContainsKey(RedisKey.KeyLichSuKienTomTat))
                            redis.Set(RedisKey.KeyLichSuKienTomTat, lls);
                        else
                            redis.Add(RedisKey.KeyLichSuKienTomTat, lls);
                        #endregion
                        break;
                    case "FB":
                        #region Bond
                        var countries = SqlDb.GetBondCountry(symbol);
                        var types = new List<string>() { "1", "3", "5", "10" };
                        var bondkeys = new List<string>();
                        var cs = new List<string>();
                        foreach (DataRow dr in countries.Rows)
                        {
                            var country = dr["CountryName"].ToString();
                            if (!cs.Contains(country)) cs.Add(country);
                            foreach (var type in types)
                            {
                                var dt = SqlDb.GetBondValue(country, type);
                                if (dt.Rows.Count == 0) continue;
                                var o = new Bond() { BondCode = dt.Rows[0]["BondCode"].ToString(), BondCountry = dt.Rows[0]["CountryName"].ToString(), BondType = dt.Rows[0]["BondType"].ToString(), BondEnName = dt.Rows[0]["ENName"].ToString(), BondVnName = dt.Rows[0]["VNName"].ToString() };
                                var values = new List<BondValue>();
                                foreach (DataRow value in dt.Rows)
                                {
                                    values.Add(new BondValue() { TradeDate = (DateTime)value["TradeDate"], ClosePrice = double.Parse(value["ClosePrice"].ToString()) });
                                }
                                o.BondValues = values;
                                var key = string.Format(RedisKey.BondKey, country, type);
                                if (!bondkeys.Contains(key)) bondkeys.Add(key);
                                if (redis.ContainsKey(key))
                                    redis.Set(key, o);
                                else
                                    redis.Add(key, o);
                            }
                        }
                        foreach(var c in cs)
                        {
                            var existed = redis.SearchKeys(string.Format(RedisKey.BondKey, c, "*"));
                            foreach(var key in existed)
                            {
                                if (bondkeys.Contains(key)) continue;
                                if (redis.ContainsKey(key)) redis.Remove(key);
                            }
                        }
                        

                        #endregion
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                log.WriteEntry(updateKey + " : UpdateList : " + ex.ToString(), EventLogEntryType.Error);
                ret = false;
            }
            return ret;
        }
Пример #2
0
        private void button4_Click(object sender, EventArgs e)
        {
            var symbol = "VNINDEX";

            var redis = new RedisClient(ConfigRedis.Host, ConfigRedis.Port);
            var keylist = string.Format(RedisKey.OrderHistoryKeys, symbol);
            var ls = redis.ContainsKey(keylist) ? redis.Get<List<String>>(keylist) : new List<string>();

            var pdt = SqlDb.GetOrderHistory(symbol, -1);
            foreach (DataRow pdr in pdt.Rows)
            {
                var key = string.Format(RedisKey.OrderHistory, symbol, ((DateTime)pdr["Trading_Date"]).ToString("yyyyMMdd"));

                var order = new OrderHistory() { TradeDate = (DateTime)pdr["Trading_Date"], BuyOrderCount = double.Parse(pdr["Bid_Order"].ToString()), BuyVolume = double.Parse(pdr["Bid_Volume"].ToString()), SellOrderCount = double.Parse(pdr["Offer_Order"].ToString()), SellVolume = double.Parse(pdr["Offer_Volume"].ToString()), Volume = double.Parse(pdr["Volume"].ToString()), Price = double.Parse(pdr["Price"].ToString()), BasicPrice = double.Parse(pdr["BasicPrice"].ToString()), Ceiling = double.Parse(pdr["Ceiling"].ToString()), Floor = double.Parse(pdr["Floor"].ToString()), Symbol = symbol };
                if (redis.ContainsKey(key))
                    redis.Set<OrderHistory>(key, order);
                else
                    redis.Add<OrderHistory>(key, order);

                if (!ls.Contains(key)) ls.Add(key);
            }
            ls.Sort();
            ls.Reverse();
            if (redis.ContainsKey(keylist))
                redis.Set<List<string>>(keylist, ls);
            else
                redis.Add<List<string>>(keylist, ls);

            var test = redis.Get<List<string>>(keylist);
        }
 private string[] compareCurrent_PreviousTrading(OrderHistory currentRow, OrderHistory previousRow)
 {
     string[] comparedResults = new string[4];
     double changePercent;
     // BID_ORDER
     changePercent =(previousRow.BuyOrderCount == 0? 100: 100 * ((currentRow.BuyOrderCount - previousRow.BuyOrderCount) /previousRow.BuyOrderCount));
     changePercent = Math.Round(changePercent, 2);
     if (changePercent > 0) comparedResults[0] = "(<img src='http://cafef3.vcmedia.vn/images/btup.gif'>" + changePercent + "% so với phiên trước)";
     if (changePercent == 0) comparedResults[0] = "(<img src='http://cafef3.vcmedia.vn/images/no_change.jpg'>" + changePercent + "% so với phiên trước)";
     if (changePercent < 0) comparedResults[0] = "(<img src='http://cafef3.vcmedia.vn/images/btdown.gif'>" + changePercent + "% so với phiên trước)";
     // BID_VOLUME
     changePercent = (previousRow.BuyVolume ==0? 100: 100 * ((currentRow.BuyVolume - previousRow.BuyVolume) / previousRow.BuyVolume));
     changePercent = Math.Round(changePercent, 2);
     if (changePercent > 0) comparedResults[1] = "(<img src='http://cafef3.vcmedia.vn/images/btup.gif'>" + changePercent + "% so với phiên trước)";
     if (changePercent == 0) comparedResults[1] = "(<img src='http://cafef3.vcmedia.vn/images/no_change.jpg'>" + changePercent + "% so với phiên trước)";
     if (changePercent < 0) comparedResults[1] = "(<img src='http://cafef3.vcmedia.vn/images/btdown.gif'>" + changePercent + "% so với phiên trước)";
     // OFFER_ORDER
     changePercent = (previousRow.SellOrderCount == 0? 100: 100 * ((currentRow.SellOrderCount - previousRow.SellOrderCount) / previousRow.SellOrderCount));
     changePercent = Math.Round(changePercent, 2);
     if (changePercent > 0) comparedResults[2] = "(<img src='http://cafef3.vcmedia.vn/images/btup.gif'>" + changePercent + "% so với phiên trước)";
     if (changePercent == 0) comparedResults[2] = "(<img src='http://cafef3.vcmedia.vn/images/no_change.jpg'>" + changePercent + "% so với phiên trước)";
     if (changePercent < 0) comparedResults[2] = "(<img src='http://cafef3.vcmedia.vn/images/btdown.gif'>" + changePercent + "% so với phiên trước)";
     // OFFER_VOLUME
     changePercent = (previousRow.SellVolume ==0?100: 100 * ((currentRow.SellVolume - previousRow.SellVolume) / previousRow.SellVolume));
     changePercent = Math.Round(changePercent, 2);
     if (changePercent > 0) comparedResults[3] = "(<img src='http://cafef3.vcmedia.vn/images/btup.gif'>" + changePercent + "% so với phiên trước)";
     if (changePercent == 0) comparedResults[3] = "(<img src='http://cafef3.vcmedia.vn/images/no_change.jpg'>" + changePercent + "% so với phiên trước)";
     if (changePercent < 0) comparedResults[3] = "(<img src='http://cafef3.vcmedia.vn/images/btdown.gif'>" + changePercent + "% so với phiên trước)";
     return comparedResults;
 }