コード例 #1
0
ファイル: StockData.cs プロジェクト: giangcoffee/cafef.redis
        private bool UpdateStock(string symbol, List<string> related, ref SqlDb sql)
        {
            var ret = true;
            //log.WriteEntry(symbol + "-1-" + ret, EventLogEntryType.Information);
            try
            {
                var redis = new RedisClient(ConfigRedis.Host, ConfigRedis.Port);
                var key = string.Format(RedisKey.Key, symbol.ToUpper());
                var bExisted = (redis.ContainsKey(key));
                var stock = bExisted ? redis.Get<Stock>(key) : new Stock() { Symbol = symbol };
                #region Update stock from sql
                //stock.Symbol = "AAA";
                //load stock data 

                //profile
                var profile = bExisted ? stock.CompanyProfile : new CompanyProfile { Symbol = stock.Symbol };
                var basicInfo = bExisted ? profile.basicInfos : new BasicInfo() { Symbol = stock.Symbol };
                var basicCommon = bExisted ? profile.basicInfos.basicCommon : new BasicCommon() { Symbol = stock.Symbol };
                var category = bExisted ? profile.basicInfos.category : new CategoryObject();
                var firstInfo = bExisted ? profile.basicInfos.firstInfo : new FirstInfo() { Symbol = stock.Symbol };
                var commonInfo = bExisted ? profile.commonInfos : new CommonInfo() { Symbol = stock.Symbol };
                //basic information
                #region SB
                if (!bExisted || related.Contains("SB"))
                {
                    try
                    {
                        var dt = sql.GetSymbolData(symbol);
                        if (dt.Rows.Count <= 0) return true;

                        var row = dt.Rows[0];

                        #region StockCompactInfo

                        var compactkey = string.Format(RedisKey.KeyCompactStock, symbol.ToUpper());
                        var compact = new StockCompactInfo() { Symbol = symbol.ToUpper(), TradeCenterId = int.Parse(row["TradeCenterId"].ToString()), CompanyName = row["CompanyName"].ToString(), EPS = double.Parse(row["EPS"].ToString()), FolderChart = row["FolderChart"].ToString(), ShowTradeCenter = row["ShowTradeCenter"].ToString().ToUpper() == "TRUE", IsBank = row["IsBank"].ToString().ToUpper() == "TRUE", IsCCQ = row["IsCCQ"].ToString().ToUpper() == "TRUE" };
                        if (redis.ContainsKey(compactkey))
                            redis.Set(compactkey, compact);
                        else
                            redis.Add(compactkey, compact);
                        #endregion

                        stock.Symbol = row["Symbol"].ToString();
                        stock.TradeCenterId = int.Parse(row["TradeCenterId"].ToString());
                        stock.IsDisabled = row["IsDisabled"].ToString() == "TRUE";
                        stock.StatusText = row["StatusText"].ToString();
                        stock.ShowTradeCenter = row["ShowTradeCenter"].ToString().ToUpper() == "TRUE";
                        stock.FolderImage = row["FolderChart"].ToString();
                        stock.IsBank = row["IsBank"].ToString() == "TRUE";
                        stock.IsCCQ = row["IsCCQ"].ToString().ToUpper() == "TRUE";

                        //profile - basicInfo
                        basicInfo.Name = row["CompanyName"].ToString();
                        basicInfo.TradeCenter = stock.TradeCenterId.ToString();

                        //profile - basicInfo - basicCommon
                        /*PE = double.Parse(row["PE"].ToString()),*/
                        basicCommon.AverageVolume = double.Parse(row["AVG10SS"].ToString());
                        basicCommon.Beta = double.Parse(row["Beta"].ToString());
                        basicCommon.EPS = double.Parse(row["EPS"].ToString());
                        basicCommon.TotalValue = double.Parse(row["MarketCap"].ToString());
                        basicCommon.ValuePerStock = double.Parse(row["BookValue"].ToString());
                        basicCommon.VolumeTotal = double.Parse(row["SLCPNY"].ToString());
                        basicCommon.OutstandingVolume = double.Parse(row["TotalShare"].ToString());
                        basicCommon.PE = basicCommon.EPS != 0 ? (double.Parse(row["LastPrice"].ToString()) / basicCommon.EPS) : 0;
                        basicCommon.EPSDate = row["EPSDate"].ToString();
                        basicCommon.CCQv3 = double.Parse(row["CCQv3"].ToString());
                        basicCommon.CCQv6 = double.Parse(row["CCQv6"].ToString());
                        basicCommon.CCQdate = DateTime.ParseExact(row["CCQdate"].ToString(), "yyyy.MM.dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                        basicInfo.basicCommon = basicCommon;

                        //profile - basicInfo - category
                        category.ID = int.Parse(row["CategoryId"].ToString());
                        category.Name = row["CategoryName"].ToString();
                        basicInfo.category = category;

                        //profile - basicInfo - firstInfo
                        firstInfo.FirstPrice = double.Parse(row["FirstPrice"].ToString());
                        firstInfo.FirstTrade = row["FirstTrade"].Equals(DBNull.Value) ? null : ((DateTime?)row["FirstTrade"]);
                        firstInfo.FirstVolume = double.Parse(row["FirstVolume"].ToString());
                        basicInfo.firstInfo = firstInfo;

                        profile.basicInfos = basicInfo;

                        //profile - commonInfo
                        commonInfo.Capital = double.Parse(row["VonDieuLe"].ToString());
                        commonInfo.Category = row["CategoryName"].ToString();
                        commonInfo.Content = row["About"].ToString();
                        commonInfo.OutstandingVolume = double.Parse(row["TotalShare"].ToString());
                        commonInfo.TotalVolume = double.Parse(row["SLCPNY"].ToString());
                        commonInfo.Content += "<p><b>Địa chỉ:</b> " + row["Address"].ToString() + "</p>";
                        commonInfo.Content += "<p><b>Điện thoại:</b> " + row["Phone"].ToString() + "</p>";
                        commonInfo.Content += "<p><b>Người phát ngôn:</b> " + row["Spokenman"].ToString() + "</p>";
                        if (!string.IsNullOrEmpty(row["Email"].ToString())) commonInfo.Content += "<p><b>Email:</b> <a href='mailto:" + row["Email"] + "'>" + row["Email"] + "</a></p>";
                        if (!string.IsNullOrEmpty(row["Website"].ToString())) commonInfo.Content += "<p><b>Website:</b> <a href='" + row["Website"] + "' target='_blank'>" + row["Website"] + "</a></p>";
                        commonInfo.AuditFirmName = row["AuditName"].ToString();
                        commonInfo.AuditFirmSite = row["AuditSite"].ToString().Trim();
                        commonInfo.ConsultantName = row["ConsultantName"].ToString();
                        commonInfo.ConsultantSite = row["ConsultantSite"].ToString();
                        commonInfo.BusinessLicense = row["BusinessLicense"].ToString();
                        commonInfo.ConsultantSymbol = row["ConsultantSymbol"].ToString().Trim().ToUpper();

                        profile.commonInfos = commonInfo;

                        //business plans
                        var plans = new List<BusinessPlan>();
                        if (row["HasPlan"].ToString() == "1")
                        {
                            plans.Add(new BusinessPlan() { Body = row["PlanNote"].ToString(), Date = (DateTime)row["PlanDate"], DividendsMoney = double.Parse(row["Dividend"].ToString()), DividendsStock = double.Parse(row["DivStock"].ToString()), ID = int.Parse(row["PlanId"].ToString()), IncreaseExpected = double.Parse(row["CapitalRaising"].ToString()), ProfitATax = double.Parse(row["NetIncome"].ToString()), ProfitBTax = double.Parse(row["TotalProfit"].ToString()), Revenue = double.Parse(row["TotalIncome"].ToString()), Symbol = stock.Symbol, Year = int.Parse(row["KYear"].ToString()) });
                        }
                        stock.BusinessPlans1 = plans;

                        var fdt = sql.GetPrevTradeInfo(symbol);
                        if (fdt.Rows.Count == 0)
                        {
                            stock.PrevTradeInfo = new List<StockFirstInfo>();
                        }
                        else
                        {
                            var tret = new List<StockFirstInfo>();
                            foreach (DataRow fdr in fdt.Rows)
                            {
                                tret.Add(new StockFirstInfo() { Floor = fdr["Floor"].ToString().ToUpper() == "HASTC" ? "HNX" : fdr["Floor"].ToString(), FirstDate = ((DateTime)fdr["FirstDate"]), FirstVolume = double.Parse(fdr["FirstVolume"].ToString()), FirstPrice = double.Parse(fdr["FirstPrice"].ToString()), EndDate = ((DateTime)fdr["EndDate"]) });
                            }
                            stock.PrevTradeInfo = tret;
                            //log.WriteEntry(symbol + " : BasicInfo : " + fdt.Rows.Count, EventLogEntryType.Error);

                        }
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : BasicInfo : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SS
                //profile - subsidiaries
                if (!bExisted || related.Contains("SS"))
                {
                    try
                    {


                        var subsidiaries = new List<OtherCompany>();
                        var associates = new List<OtherCompany>();
                        var cdt = sql.GetChildrenCompany(stock.Symbol);
                        var i = 0;
                        foreach (DataRow cdr in cdt.Rows)
                        {
                            i++;
                            var child = new OtherCompany() { Name = cdr["CompanyName"].ToString(), Note = cdr["NoteInfo"].ToString(), OwnershipRate = double.Parse(cdr["Rate"].ToString()), Order = i, SharedCapital = double.Parse(cdr["TotalShareValue"].ToString()), Symbol = stock.Symbol, TotalCapital = double.Parse(cdr["CharterCapital"].ToString()) };
                            if (cdr["isCongTyCon"].ToString() == "1") subsidiaries.Add(child);
                            else associates.Add(child);
                        }
                        profile.Subsidiaries = subsidiaries;
                        profile.AssociatedCompanies = associates;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Cty con : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SF
                //profile - financePeriod
                if (!bExisted || related.Contains("SF"))
                {
                    try
                    {
                        var periods = new List<FinancePeriod>();
                        var financeInfo = new List<FinanceInfo>();

                        var fyt = sql.GetFinancePeriod(stock.Symbol);
                        FinancePeriod period = null;
                        var tmp = 0;
                        foreach (DataRow fyr in fyt.Rows)
                        {
                            if (period == null || tmp != int.Parse(fyr["Year"].ToString()) * 10 + int.Parse(fyr["QuarterType"].ToString()))
                            {
                                if (period != null) { period.UpdateTitle(); periods.Add(period); }
                                period = new FinancePeriod() { Quarter = int.Parse(fyr["QuarterType"].ToString()), Year = int.Parse(fyr["Year"].ToString()) };
                            }
                            tmp = int.Parse(fyr["Year"].ToString()) * 10 + int.Parse(fyr["QuarterType"].ToString());
                            switch (fyr["MaChiTieu"].ToString())
                            {
                                case "Audited":
                                    period.SubTitle = fyr["TieuDeNhom"].ToString();
                                    break;
                                case "QuarterModify":
                                    var qrt = fyr["TieuDeNhom"].ToString();
                                    var qrti = 0;
                                    if (qrt.EndsWith("T")) { period.QuarterTitle = qrt.Remove(qrt.Length - 1) + " tháng"; }
                                    else if (int.TryParse(qrt, out qrti) && qrti >= 1 && qrti < 5)
                                    {
                                        period.QuarterTitle = "Quý " + qrti;
                                    }
                                    else period.QuarterTitle = "";
                                    break;
                                case "YearModify":
                                    if (int.TryParse(fyr["TieuDeNhom"].ToString(), out qrti))
                                    {
                                        period.YearTitle = "Năm " + qrti;
                                    }
                                    else period.YearTitle = "";
                                    break;
                                case "FromDate":
                                    qrt = fyr["TieuDeNhom"].ToString();
                                    if (qrt.Contains("/"))
                                    {
                                        var begin = qrt.Substring(0, qrt.LastIndexOf("/"));
                                        if (begin.Contains("/"))
                                        {
                                            begin = begin.Substring(begin.IndexOf("/") + 1) + "/" + begin.Substring(0, begin.IndexOf("/"));
                                        }
                                        period.BeginTitle = begin;
                                    }
                                    break;
                                case "ToDate":
                                    qrt = fyr["TieuDeNhom"].ToString();
                                    if (qrt.Contains("/"))
                                    {
                                        var end = qrt.Substring(0, qrt.LastIndexOf("/"));
                                        if (end.Contains("/"))
                                        {
                                            end = end.Substring(end.IndexOf("/") + 1) + "/" + end.Substring(0, end.IndexOf("/"));
                                        }
                                        period.EndTitle = end;
                                    }

                                    break;
                                default:
                                    break;
                            }
                        }
                        if (period != null) { period.UpdateTitle(); periods.Add(period); }
                        profile.FinancePeriods = periods;

                        //profile - financeInfo

                        var fit = sql.GetChiTieuFinance(stock.Symbol);
                        var fvt = sql.GetFinanceData(stock.Symbol);
                        var groupId = 0;
                        FinanceInfo info = null;
                        foreach (DataRow fir in fit.Rows)
                        {
                            if (info == null || groupId != int.Parse(fir["LoaiChiTieu"].ToString()))
                            {
                                if (info != null) financeInfo.Add(info);
                                info = new FinanceInfo() { NhomChiTieuId = groupId, Symbol = stock.Symbol, TenNhomChiTieu = fir["TenLoaiChiTieu"].ToString() };
                            }
                            groupId = int.Parse(fir["LoaiChiTieu"].ToString());
                            var chiTieu = new FinanceChiTieu() { ChiTieuId = fir["MaChiTieu"].ToString(), TenChiTieu = fir["TieuDeKhac"].ToString() };
                            if (fir["MaChiTieu"].ToString() == "ROA")
                            {
                                int b = 0;
                            }
                            foreach (var financePeriod in periods)
                            {
                                var fvrs = fvt.Select("MaChiTieu = '" + fir["MaChiTieu"] + "' AND Year = " + financePeriod.Year + " AND QuarterType = " + financePeriod.Quarter);
                                if (fvrs.Length > 0)
                                {
                                    chiTieu.Values.Add(new FinanceValue() { Quarter = financePeriod.Quarter, Year = financePeriod.Year, Value = double.Parse(fvrs[0]["FinanceValue"].ToString()) });
                                }
                                else
                                {
                                    chiTieu.Values.Add(new FinanceValue() { Quarter = financePeriod.Quarter, Year = financePeriod.Year, Value = 0 });
                                }
                            }

                            info.ChiTieus.Add(chiTieu);
                        }
                        if (info != null) financeInfo.Add(info);
                        profile.financeInfos = financeInfo;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : FinanceInfo : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SC
                //profile - leader
                if (!bExisted || related.Contains("SC"))
                {
                    try
                    {
                        var leaders = new List<Leader>();
                        var ldt = sql.GetCeos(stock.Symbol);
                        foreach (DataRow ldr in ldt.Rows)
                        {
                            leaders.Add(new Leader() { GroupID = ldr["ParentId"].ToString(), Name = ldr["FullName"].ToString(), Positions = ldr["TenNhom"].ToString() });
                        }
                        profile.Leaders = leaders;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Leaders : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SH
                //profile - owner
                if (!bExisted || related.Contains("SH"))
                {
                    try
                    {
                        var owners = new List<MajorOwner>();
                        var odt = sql.GetShareHolders(stock.Symbol);
                        foreach (DataRow odr in odt.Rows)
                        {
                            owners.Add(new MajorOwner() { Name = odr["FullName"].ToString(), Rate = double.Parse(odr["ShareHoldPct"].ToString()), ToDate = (DateTime)odr["DenNgay"], Volume = double.Parse(odr["SoCoPhieu"].ToString()) });
                        }
                        profile.MajorOwners = owners;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Owners : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SCN
                //profile - CEO
                if (!bExisted || related.Contains("SCN"))
                {
                    try
                    {
                        var ceos = new List<StockCeo>();
                        var cdt = sql.GetCeosNew(stock.Symbol);
                        foreach (DataRow cdr in cdt.Rows)
                        {
                            var ceo = new StockCeo() { CeoId = int.Parse(cdr["CeoId"].ToString()), CeoCode = cdr["CeoCode"].ToString(), GroupID = int.Parse(cdr["PositionType"].ToString()), Name = (cdr["CeoGender"].ToString().ToUpper() == "M" ? "Ông " : (cdr["CeoGender"].ToString().ToUpper() == "F" ? "Bà " : "")) + cdr["CeoName"].ToString(), Positions = cdr["PositionName"].ToString() };
                            ceo.Process = "";
                            //process
                            var process = cdr["CeoProfileShort"].ToString();
                            if (process != "")
                            {
                                var begin = GetCeoDate(process.Substring(0, process.IndexOf("---")));
                                process = process.Substring(process.IndexOf("---") + 3);
                                var end = GetCeoDate(process.Substring(0, process.IndexOf("---")));
                                process = process.Substring(process.IndexOf("---") + 3);
                                var desc = process;
                                process = (begin != "" ? ("Từ " + begin + " ") : "") + (end != "" ? ((begin != "" ? "đến" : "Đến") + " " + end + "") : "");
                                ceo.Process = process + (process == "" ? "" : " : ") + desc;
                                if (ceo.Process.Length > 80)
                                {
                                    ceo.Process = ceo.Process.Substring(0, 80) + "...";
                                }
                            }


                            var birthday = cdr["CeoBirthday"].ToString();
                            if (birthday.Contains("/"))
                            {
                                int year;
                                if (!int.TryParse(birthday.Substring(birthday.LastIndexOf("/") + 1), out year)) year = 0;
                                if (year > 0)
                                {
                                    if (year < 100) year = 1900 + year;
                                    ceo.Age = year;
                                }
                            }
                            ceos.Add(ceo);
                        }
                        profile.AssociatedCeo = ceos;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : CEO New : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                stock.CompanyProfile = profile;
                /*================================*/

                #region SD
                //dividend histories
                if (!bExisted || related.Contains("SD"))
                {
                    try
                    {
                        var divs = new List<DividendHistory>();
                        var ddt = sql.GetDividendHistory(stock.Symbol);
                        foreach (DataRow ddr in ddt.Rows)
                        {
                            divs.Add(new DividendHistory() { DonViDoiTuong = ddr["DonViDoiTuong"].ToString(), NgayGDKHQ = (DateTime)ddr["NgayGDKHQ"], GhiChu = ddr["GhiChu"].ToString(), SuKien = ddr["SuKien"].ToString(), Symbol = stock.Symbol, TiLe = ddr["TiLe"].ToString() });
                        }
                        stock.DividendHistorys = divs;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Dividend : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SA
                //báo cáo phân tích
                if (!bExisted || related.Contains("SA"))
                {
                    try
                    {
                        var reports = new List<Reports>();
                        var rdt = sql.GetAnalysisReports(stock.Symbol);
                        foreach (DataRow rdr in rdt.Rows)
                        {
                            reports.Add(new Reports() { ID = int.Parse(rdr["ID"].ToString()), Title = rdr["title"].ToString(), DateDeploy = (DateTime)rdr["PublishDate"], ResourceCode = rdr["Source"].ToString(), IsHot = rdr["IsHot"].ToString().ToLower() == "true" });
                        }
                        stock.Reports3 = reports;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : AnalyseReport : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SCA
                //công ty cùng ngành
                if (!bExisted || related.Contains("SCA"))
                {
                    try
                    {
                        var samecateCompanies = new List<StockShortInfo>();
                        var scdt = sql.GetSameCateCompanies(stock.Symbol);
                        foreach (DataRow scdr in scdt.Rows)
                        {
                            samecateCompanies.Add(new StockShortInfo() { Symbol = scdr["StockSymbol"].ToString(), TradeCenterId = int.Parse(scdr["TradeCenterId"].ToString()), Name = scdr["FullName"].ToString(), EPS = double.Parse(scdr["EPS"].ToString()) });
                        }
                        stock.SameCategory = samecateCompanies;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : SameCate : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SEPS
                //eps tương đương
                if (!bExisted || related.Contains("SEPS"))
                {
                    try
                    {
                        var sameEPSCompanies = new List<StockShortInfo>();
                        var sedt = sql.GetSameEPSCompanies(stock.Symbol);
                        foreach (DataRow sedr in sedt.Rows)
                        {
                            sameEPSCompanies.Add(new StockShortInfo() { Symbol = sedr["StockSymbol"].ToString(), TradeCenterId = int.Parse(sedr["TradeCenterId"].ToString()), Name = sedr["FullName"].ToString(), EPS = double.Parse(sedr["EPS"].ToString()), MarketValue = double.Parse(sedr["MarketCap"].ToString()) });
                        }
                        stock.SameEPS = sameEPSCompanies;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : SameEPS : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SPE
                //pe tương đương
                if (!bExisted || related.Contains("SPE"))
                {
                    try
                    {
                        var samePECompanies = new List<StockShortInfo>();
                        var spdt = sql.GetSamePECompanies(stock.Symbol);
                        foreach (DataRow spdr in spdt.Rows)
                        {
                            samePECompanies.Add(new StockShortInfo() { Symbol = spdr["StockSymbol"].ToString(), TradeCenterId = int.Parse(spdr["TradeCenterId"].ToString()), Name = spdr["FullName"].ToString(), EPS = double.Parse(spdr["EPS"].ToString()), MarketValue = double.Parse(spdr["MarketCap"].ToString()) });
                        }
                        stock.SamePE = samePECompanies;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : SamePE : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                //stock history
                var history = bExisted ? stock.StockPriceHistory : new StockCompactHistory();

                #region SP
                //stock history - price
                if (!bExisted || related.Contains("SP"))
                {
                    try
                    {
                        var price = new List<PriceCompactHistory>();
                        var pdt = sql.GetPriceHistory(stock.Symbol, 11);
                        foreach (DataRow pdr in pdt.Rows)
                        {
                            price.Add(new PriceCompactHistory() { ClosePrice = double.Parse(pdr["Price"].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()), TradeDate = (DateTime)pdr["TradeDate"], AgreedVolume = double.Parse(pdr["AgreedVolume"].ToString()), AgreedValue = double.Parse(pdr["AgreedValue"].ToString()) });
                        }
                        history.Price = price;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Price : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SO
                //stock history - order
                if (!bExisted || related.Contains("SO"))
                {
                    try
                    {
                        var order = new List<OrderCompactHistory>();
                        var hodt = sql.GetOrderHistory(stock.Symbol, 11);
                        foreach (DataRow hodr in hodt.Rows)
                        {
                            order.Add(new OrderCompactHistory() { AskAverageVolume = double.Parse(hodr["AskAverage"].ToString()), AskVolume = double.Parse(hodr["Offer_Volume"].ToString()), BidAverageVolume = double.Parse(hodr["BidAverage"].ToString()), BidVolume = double.Parse(hodr["Bid_Volume"].ToString()), TradeDate = (DateTime)hodr["Trading_Date"] });
                        }
                        history.Orders = order;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Order : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SFT
                //stock history - foreign
                if (!bExisted || related.Contains("SFT"))
                {
                    try
                    {
                        var foreign = new List<ForeignCompactHistory>();
                        var fdt = sql.GetForeignHistory(stock.Symbol, 11);
                        foreach (DataRow fdr in fdt.Rows)
                        {
                            foreign.Add(new ForeignCompactHistory() { BuyValue = double.Parse(fdr["Buying_Value"].ToString()), SellValue = double.Parse(fdr["Selling_Value"].ToString()), NetVolume = double.Parse(fdr["FNetVolume"].ToString()), NetValue = double.Parse(fdr["FNetValue"].ToString()), TradeDate = (DateTime)fdr["Trading_Date"] });
                        }
                        history.Foreign = foreign;
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : Foreign : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                stock.StockPriceHistory = history;
                /*====================*/

                #region SN
                //tin tức và sự kiện
                if (!bExisted || related.Contains("SN"))
                {
                    try
                    {
                        //var news = new List<StockNews>();
                        //var ndt = sql.GetCompanyNews(stock.Symbol, -1);
                        //foreach (DataRow ndr in ndt.Rows)
                        //{
                        //    news.Add(new StockNews() { DateDeploy = (DateTime)ndr["PostTime"], ID = int.Parse(ndr["Id"].ToString()), Title = ndr["Title"].ToString(), TypeID = ndr["ConfigId"].ToString() });
                        //}
                        //stock.StockNews = news;
                        var keylist = string.Format(RedisKey.KeyCompanyNewsByStock, stock.Symbol, 0); //Tất cả
                        var ls = new List<string>();
                        var pdt = sql.GetCompanyNews(stock.Symbol, -1);

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

                        var cate4 = new List<string>();
                        var cate5 = new List<string>();
                        var stocknews = new List<StockNews>();
                        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, ' ');
                            }

                            if (stocknews.Count < 6) { stocknews.Add(compact); }
                            var newskey = obj.DateDeploy.ToString("yyyyMMddHHmm") + obj.ID;
                            var compactkey = string.Format(RedisKey.KeyCompanyNewsCompact, obj.ID);
                            var detailkey = string.Format(RedisKey.KeyCompanyNewsDetail, obj.ID);
                            if (redis.ContainsKey(compactkey))
                                redis.Set(compactkey, compact);
                            else
                                redis.Add(compactkey, compact);
                            if (redis.ContainsKey(detailkey))
                                redis.Set(detailkey, obj);
                            else
                                redis.Add(detailkey, obj);

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

                        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 + " : News : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #region SL
                //if (false)
                if (!bExisted || related.Contains("SL"))
                {
                    try
                    {
                        var lldt = sql.GetLandProject(symbol);
                        var adt = sql.GetLandProject_Area(symbol);
                        var pdt = sql.GetLandProject_Profit(symbol);
                        foreach (DataRow ldr in lldt.Rows)
                        {
                            var bdskey = string.Format(RedisKey.BDSKey, ldr["MaCK"].ToString(),  ldr["MaTienDo"].ToString());
                            TienDoBDS o;
                            try
                            {
                                o = redis.Get<TienDoBDS>(bdskey) ?? new TienDoBDS();
                            }
                            catch (Exception) { o = new TienDoBDS(); }
                            o.MaCK = ldr["MaCK"].ToString(); o.MaTienDo = ldr["MaTienDo"].ToString(); o.TenDuAn = ldr["TenDuAn"].ToString(); o.HinhThucKinhDoanh = ldr["HinhThucKinhDoanh"].ToString(); o.DiaDiem = ldr["DiaDiem"].ToString(); o.ThanhPho = ldr["ThanhPho"].ToString(); o.TongVon = decimal.Parse(ldr["TongVon"].ToString()); o.Donvi = ldr["Donvi"].ToString(); o.TyLeGhopVon = ldr["TyLeGhopVon"].ToString(); o.TyLeDenBu = ldr["TyLeDenBu"].ToString(); o.GhiChu = ldr["GhiChu"].ToString(); o.MoTa = ldr["Mota"].ToString(); o.URL = ldr["URL"].ToString();
                            o.ID = int.Parse(ldr["ID"].ToString());
                            DateTime d;
                            if (DateTime.TryParse(ldr["ViewDate"].ToString(), out d))
                            {
                                o.ViewDate = d;
                            }
                            var adrs = adt.Select("MaTienDo='" + o.MaTienDo + "'");
                            var als = new List<TienDoBDSDienTich>();
                            foreach (var adr in adrs)
                            {
                                als.Add(new TienDoBDSDienTich() { MaTienDo = o.MaTienDo, DienTich = decimal.Parse(adr["DienTich"].ToString()), LoaiDienTich = adr["LoaiDienTich"].ToString() });
                            }
                            o.DienTichs = als;

                            var pdrs = pdt.Select("MaTienDo='" + o.MaTienDo + "'");
                            var pls = new List<TienDoBDSLoiNhuan>();
                            foreach (var pdr in pdrs)
                            {
                                pls.Add(new TienDoBDSLoiNhuan() { MaTienDo = o.MaTienDo, LoiNhuanDoanhThu = decimal.Parse(pdr["LoiNhuanDoanhThu"].ToString()), LoaiLoiNhuan = pdr["LoaiLoiNhuan"].ToString() });
                            }
                            o.LoiNhuans = pls;

                            if (redis.ContainsKey(bdskey))
                                redis.Set(bdskey, o);
                            else
                                redis.Add(bdskey, o);
                        }
                     
                    }
                    catch (Exception ex)
                    {
                        log.WriteEntry(symbol + " : TienDoBDS : " + ex.ToString(), EventLogEntryType.Error);
                        ret = false;
                    }
                }
                #endregion

                #endregion

                if (redis.ContainsKey(key))
                    redis.Set<Stock>(key, stock);
                else
                    redis.Add<Stock>(key, stock);
            }
            catch (Exception ex)
            {
                log.WriteEntry(symbol + ": " + ex.ToString(), EventLogEntryType.Error);
                ret = false;
            }

            return ret;
        }