• 组合配置草稿


    1.枚举
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace HRAModel.Sys.Enum
    {
        /// <summary>
        /// 解释风险组合类型和RSK_DELTA_POSITION的哪个外键对应
        /// </summary>
        public class RiskGroupTypeExplainAttribute : Attribute
        {
            /// <summary>
            /// 来源表主键
            /// </summary>
            private string _oriPrimarKey;
            /// <summary>
            /// 来源表主键列名称
            /// </summary>
            public string OriPrimaryKey
            {
                get
                {
                    return _oriPrimarKey;
                }
            }
            private string _tableName;
            /// <summary>
            /// 在RSK_DELTA_POSITION中对应的外键
            /// </summary>
            private string _fk;
            /// <summary>
            /// 在RSK_DELTA_POSITION中对应的外键
            /// </summary>
            public string ForeginKey
            {
                get
                {
                    return _fk;
                }
            }
            /// <summary>
            /// 来源表 表明
            /// </summary>
            public string TableName
            {
                get
                {
                    return _tableName;
                }
            }
            private string _name;
            /// <summary>
            /// 来源表文本列
            /// </summary>
            public string Name
            {
                get
                {
                    return _name;
                }
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="foreginKey">外键</param>
            /// <param name="tableName">来源表</param>
            /// <param name="name">来源表文本列</param>
            public RiskGroupTypeExplainAttribute(string foreginKey,string oriPrimaryKey,string tableName,string name)
            {
                this._fk = foreginKey;
                this._tableName = tableName;
                this._name = name;
                this._oriPrimarKey = oriPrimaryKey;
            }
    
        }
        /// <summary>
        /// 风险组合类型
        /// </summary>
        [SysEnumType]
        public enum Risk_Group_Type
        {
            #region 风险组合类型
            /// <summary>
            /// 风险组合类型
            /// </summary>
            [EnumRemark("1116", "风险组合类型", true)]
            Risk_Group_Type = 1116,
    
            /// <summary>
            /// 业务单位
            /// </summary>
            [EnumRemark("111601", "业务单位")]
            [RiskGroupTypeExplain("INT_BUS_UNIT_ID","ID", "BAS_ORGANIZATION_STRUC", "NAME")]
            Risk_Group_Type_Business_Unit = 111601,
    
            /// <summary>
            /// 法人实体
            /// </summary>
            [EnumRemark("111602", "法人实体")]
            [RiskGroupTypeExplain("INT_LEGAL_ENTITY_ID","ID", "BAS_ORGANIZATION_STRUC","NAME")]
            Risk_Group_Type_Legal_Entity = 111602,
    
            /// <summary>
            /// 交易合约
            /// </summary>
            [EnumRemark("111603", "交易合约")]
            Risk_Group_Type_Transaction = 111603,
    
            /// <summary>
            /// 交易员
            /// </summary>
            [EnumRemark("111604", "交易员")]
            [RiskGroupTypeExplain("TRADER_ID", "USER_ID","SYS_USER","NAME")]
            Risk_Group_Type_Trader = 111604,
    
            /// <summary>
            /// 交易对手
            /// </summary>
            [EnumRemark("111605", "交易对手")]
            [RiskGroupTypeExplain("COUNTERPARTY_ID", "COUNTERPARTY_ID", "BAS_COUNTERPARTY", "COUNTERPARTY_NAME")]
            Risk_Group_Type_Counterparty = 111605,
    
            /// <summary>
            /// 金融工具类型
            /// </summary>
            [EnumRemark("111606", "金融工具类型")]
            [RiskGroupTypeExplain("INST_TYPE_ID","ENUM_VALUE","SYS_ENUM_DICT","ENUM_NAME")]
            Risk_Group_Type_Instrument_Type = 111606,
    
            /// <summary>
            /// 金融工具群
            /// </summary>
            [EnumRemark("111607", "金融工具群")]
            Risk_Group_Type_Intrument_Group = 111607,
    
            /// <summary>
            /// 风险因子变动分析
            /// </summary>
            [EnumRemark("111608", "风险因子")]
            [RiskGroupTypeExplain("RISK_FACTOR_ID", "RISK_FACTOR_ID","RSK_FACTOR","RISK_FACTOR_NAME")]
            Risk_Group_Type_Risk_Factor = 111608,
    
            /// <summary>
            /// 商品类型
            /// </summary>
            [EnumRemark("111609", "商品类型")]
            Risk_Group_Type_Commodity = 111609,
    
            /// <summary>
            /// 货币
            /// </summary>
            [EnumRemark("111610", "货币")]
            Risk_Group_Type_Currency = 111610,
    
            /// <summary>
            /// 避险组合
            /// </summary>
            [EnumRemark("111611", "避险组合")]
            [RiskGroupTypeExplain("PORTFOLIO_ID","ID","BAS_ORGANIZATION_STRUC","NAME")]
            Risk_Group_Type_Portfolio = 111611,
    
            /// <summary>
            /// 量衡单位
            /// </summary>
            [EnumRemark("111612", "量衡单位")]
            Risk_Group_Type_Measure_Unit = 111612,
            #endregion
        }
    }
    2.service
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Holworth.RSKInterface;
    using Holworth.Utility;
    using HRAModel;
    using Contract.Domain;
    using Contract.IService;
    using System.Collections;
    using HRAModel.Sys.Enum;
    using BaseService;
    using System.Threading;
    using System.Data;
    using Framework;
    using System.Reflection;

    namespace Holworth.Services.Risk
    {
        public class ValueAtRiskCalculationService : BaseService<BaseChidEntity>, IValueAtRiskCalculationService
        {
            public class tmpTable
            {
                public string Id;
                public string Name;
            }
            /// <summary>
            ///风险计量组合头寸 风险计量组合配置的选择项若是合理则插入到 RSK_BOOK_DELTA_POSITION
            /// </summary>
            /// <param name="computeDate"></param>
            /// <param name="riskBookID"></param>
            public void InsertRiskBookDeltaPosition(DateTime computeDate, string riskBookID)
            {
                FieldInfo field = default(FieldInfo);
                QueryInfo deltaPositionInfo = new QueryInfo();
                deltaPositionInfo.CustomSQL = "select * from rsk_delta_position where as_of_date=:as_of_date";
                deltaPositionInfo.Parameters.Add("as_of_date", computeDate.Date);
                //总头寸
                DataTable deltaPositionDt = Dao.ExecuteDataSet(deltaPositionInfo).Tables[0];
                QueryInfo filterInfo = new QueryInfo("RskBookFilter");
                filterInfo.AddParam("RiskBookId", riskBookID);
                filterInfo.AddParam("SelectedFlag", 1);
                IList<RskBookFilter> filters = Dao.FindList<RskBookFilter>(filterInfo);
                //风险组合类型字典
                var filterRiskGroupTypeDict = filters.OrderBy(x => x.FilteredGroup).ToLookup(x => x.FilteredGroup);
                //定义好风险组合类型的顺序
                var riskGroupTypeOrders = filterRiskGroupTypeDict.Select(x => x.Key).ToArray();
                //风险组合类型数据整合根据风险组合类型定义好的顺序
                List<string> dataList = ReayGenerateGroupTypeData(riskBookID, riskGroupTypeOrders, filterRiskGroupTypeDict, deltaPositionDt);
                var typeColumn = new Dictionary<Risk_Group_Type, string>();
                string key = string.Empty;
                Dictionary<string, DataTable> dts = new Dictionary<string, DataTable>();
                Dictionary<string, Dictionary<string, tmpTable>> dtId2Name = new Dictionary<string, Dictionary<string, tmpTable>>();
                for (int i = 0; i < riskGroupTypeOrders.Length; i++)
                {
                    string column = string.Empty;
                    Risk_Group_Type _value = riskGroupTypeOrders[i];
                    field = typeof(Risk_Group_Type).GetField(_value.ToString());
                    RiskGroupTypeExplainAttribute exp = (field.GetCustomAttributes(typeof(RiskGroupTypeExplainAttribute), false))[0] as RiskGroupTypeExplainAttribute;
                    if (exp == null)
                    {
                        continue;
                    }
                    column = exp.ForeginKey;
                    if (!typeColumn.ContainsKey(_value))
                        typeColumn.Add(_value, column);
                    Framework.QueryInfo dtInfo = new QueryInfo();
                    dtInfo.CustomSQL = "select * from " + exp.TableName;

                    DataTable ds = (DataTable)Dao.GetCache(exp.TableName + "_CACHE");
                    if (ds == null)
                    {
                        ds = Dao.ExecuteDataSet(dtInfo).Tables[0];
                        Dao.AddCache(exp.TableName, ds);
                    }
                    if (!dts.ContainsKey(exp.TableName))
                    {
                        dtId2Name.Add(exp.TableName, ds.AsEnumerable().Select(dr =>
                                                          new tmpTable() { Id = dr[exp.OriPrimaryKey].ToString(), Name = dr[exp.Name].ToString() }).ToDictionary(x => x.Id));
                        dts.Add(exp.TableName, ds);
                    }
                }
                DataTable marketTable = null;
                if (Dao.GetCache("BAS_TRADE_MARKET_CACHE") == null)
                {
                    QueryInfo marketInfo = new QueryInfo();
                    marketInfo.CustomSQL = "select * from BAS_TRADE_MARKET";
                    marketTable = Dao.ExecuteDataSet(marketInfo).Tables[0];
                    Dao.AddCache("BAS_TRADE_MARKET_CACHE", marketTable);
                }
                else
                {
                    marketTable = (DataTable)Dao.GetCache("BAS_TRADE_MARKET_CACHE");
                }
                dts.Add("BAS_TRADE_MARKET", marketTable);
                dtId2Name.Add("BAS_TRADE_MARKET", marketTable.AsEnumerable().Select(dr =>
                                                         new tmpTable() { Id = dr["TRADE_MARKET_ID"].ToString(), Name = dr["TRADE_MARKET_NAME"].ToString() }).ToDictionary(x => x.Id));
                var dtDic = deltaPositionDt.AsEnumerable().Select(x => x).ToLookup(x =>
                {
                    string k = string.Empty;
                    for (int i = 0; i < riskGroupTypeOrders.Length; i++)
                    {
                        if (i != riskGroupTypeOrders.Length - 1)
                        {
                            k = k + x[typeColumn[riskGroupTypeOrders[i]]] + ",";
                        }
                        else
                        {
                            k = k + x[typeColumn[riskGroupTypeOrders[i]]];
                        }

                    }
                    return k;
                });

                //配置在头寸(rsk_delta_position)中存在的线路组合
                List<string> existList = new List<string>();
                //配置在头寸(rsk_delta_position)中不存在的线路组合
                List<string> notexistList = new List<string>();
                bool notExits = false;
                //装载存在和不存在的线路组合
                foreach (string item in dataList)
                {
                    notExits = !dtDic.Contains(item);
                    if (notExits == true)
                    {
                        //不存在的组合
                        notexistList.Add(item);

                    }
                    else
                    {
                        //存在的组合
                        existList.Add(item);
                    }

                }
                Dictionary<Risk_Group_Type, RiskGroupTypeExplainAttribute> attrsDict = new Dictionary<Risk_Group_Type, RiskGroupTypeExplainAttribute>();
                Hashtable errorHt = new Hashtable();
                //局部变量,判断两条线路是否相似,以及负责收集不相似的信息并反馈
                bool _isSame = false;
                string a = string.Empty;
                foreach (var item1 in notexistList)
                {
                    //复位
                    _isSame = false;

                    foreach (var item2 in existList)
                    {
                        _isSame = RiskGroupTypeFolioIsSame(item1, item2);
                        //只要有一次相同就可以了
                        if (_isSame == true)
                        {
                            break;
                        }

                    }
                    if (_isSame == false)
                    {
                       
                        a = string.Empty;
                        for (int i = 0; i < riskGroupTypeOrders.Length; i++)
                        {
                            Risk_Group_Type _value = riskGroupTypeOrders[i];
                            RiskGroupTypeExplainAttribute exp = default(RiskGroupTypeExplainAttribute);
                            if (!attrsDict.ContainsKey(_value))
                            {
                                field = typeof(Risk_Group_Type).GetField(_value.ToString());
                                exp = (field.GetCustomAttributes(typeof(RiskGroupTypeExplainAttribute), false))[0] as RiskGroupTypeExplainAttribute;
                                attrsDict.Add(_value, exp);
                            }
                            else
                            {
                                exp = attrsDict[_value];
                            }
                            if (exp.TableName == "BAS_COUNTERPARTY")
                            {
                                //if (dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item1.Split(',')[i]).Count() != 0)
                                if (dtId2Name[exp.TableName].ContainsKey(item1.Split(',')[i]))
                                {
                                    //a += dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item1.Split(',')[i])[0][exp.Name] + "对应";
                                    a += dtId2Name[exp.TableName][item1.Split(',')[i]].Name + "对应";
                                }
                                else
                                {
                                    //a += dts["BAS_TRADE_MARKET"].Select("TRADE_MARKET_ID=" + item1.Split(',')[i])[0]["Trade_Market_Name"] + "对应";
                                    a += dtId2Name["BAS_TRADE_MARKET"][item1.Split(',')[i]].Name + "对应";
                                }
                            }
                            else
                            {
                                //if (dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item1.Split(',')[i]).Count() != 0)
                                if (dtId2Name[exp.TableName].ContainsKey(item1.Split(',')[i]))
                                {
                                    // a += dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item1.Split(',')[i])[0][exp.Name] + "对应";
                                    a += dtId2Name[exp.TableName][item1.Split(',')[i]].Name + "对应";
                                }
                            }

                        }
                        if (!errorHt.Contains(a))
                            errorHt.Add(a, a);
                        //throw new Exception($"风险计量组合配置中的{a}配置在头寸中无法找到!!");

                    }
                   


                }
                if (errorHt.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in errorHt.Values)
                    {
                        sb.AppendLine(item.ToString());
                    }
                    throw new Exception($"风险计量组合配置中的{sb.ToString()}配置在头寸中无法找到!!");
                }
                return;

            }
            /// <summary>
            /// 比较两条风险计量组合是否相似
            /// </summary>
            /// <param name="target"></param>
            /// <param name="ori"></param>
            /// <returns></returns>
            private bool RiskGroupTypeFolioIsSame(string target, string ori)
            {
                //默认认为不相似
                bool isSame = false;
                string l1 = string.Empty;
                string l2 = string.Empty;
                string[] targetArr = target.Split(',');
                string[] oriArr = ori.Split(',');
                int length = targetArr.Length;
                for (int i = 0; i < length; i++)
                {
                    l1 = targetArr[i];
                    l2 = oriArr[i];
                    if (l1 == l2)
                    {
                        isSame = true;
                        break;
                    }
                }
                return isSame;
            }
            void aa()
            {
                //string a = string.Empty;
                //for (int i = 0; i < riskGroupTypeOrders.Length; i++)
                //{
                //    Risk_Group_Type _value = riskGroupTypeOrders[i];
                //    FieldInfo field = typeof(Risk_Group_Type).GetField(_value.ToString());
                //    RiskGroupTypeExplainAttribute exp = (field.GetCustomAttributes(typeof(RiskGroupTypeExplainAttribute), false))[0] as RiskGroupTypeExplainAttribute;
                //    if (exp.TableName == "BAS_COUNTERPARTY")
                //    {
                //        if (dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item.Split(',')[i]).Count() != 0)
                //        {
                //            a += dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item.Split(',')[i])[0][exp.Name] + "对应";
                //        }
                //        else
                //        {
                //            a += dts["BAS_TRADE_MARKET"].Select("TRADE_MARKET_ID=" + item.Split(',')[i])[0]["Trade_Market_Name"] + "对应";

                //        }
                //    }
                //    else
                //    {
                //        if (dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item.Split(',')[i]).Count() != 0)
                //            a += dts[exp.TableName].Select(exp.OriPrimaryKey + "=" + item.Split(',')[i])[0][exp.Name] + "对应";
                //    }

                //}

                //throw new Exception($"风险计量组合配置中的{a}配置在头寸中无法找到!!");
            }
            /// <summary>
            /// 准备根据风险组合类型Risk_Group_Type指定的顺序生成对比数据
            /// </summary>
            /// <param name="riskGroupTypeOrders">风险组合类型Risk_Group_Type指定的顺序</param>
            /// <param name="filterRiskGroupTypeDict">风险组合类型字典</param>
            /// <param name="deltaPositionDt">头寸RSK_DELTA_POSITION数据表</param>
            /// <returns></returns>
            private List<string> ReayGenerateGroupTypeData(string riskBookId, Risk_Group_Type[] riskGroupTypeOrders, ILookup<Risk_Group_Type, RskBookFilter> filterRiskGroupTypeDict, DataTable deltaPositionDt)
            {
                List<string> dataList = new List<string>();
                foreach (var item in riskGroupTypeOrders)
                {
                    GenerateGroupTypeData(dataList, filterRiskGroupTypeDict[item]);
                }
                return dataList;
            }
            /// <summary>
            /// 据风险组合类型Risk_Group_Type指定的顺序生成对比数据
            /// </summary>
            /// <param name="dataList"></param>
            /// <param name="filters"></param>

            private void GenerateGroupTypeData(List<string> dataList, IEnumerable<RskBookFilter> filters)
            {
                //重复定义的元素
                List<string> dumps = new List<string>();
                List<string> cpyList = new List<string>();
                cpyList.AddRange(dataList);
                string tmp = string.Empty;
                if (dataList.Count > 0)
                {
                    for (int i = 0; i < cpyList.Count; i++)
                    {
                        tmp = dataList[i];
                        dumps.Add(tmp);
                        foreach (RskBookFilter filter in filters)
                        {
                            dataList.Add(tmp + "," + filter.FilteredValue);
                        }
                    }
                }
                else
                {
                    foreach (RskBookFilter filter in filters)
                    {
                        dataList.Add(filter.FilteredValue);
                    }
                }
                foreach (var item in dumps)
                {
                    dataList.Remove(item);

                }

            }

            //public void Compute2(string FormId, System.Collections.Hashtable Parameter)
            //{
            //    IList<TranCashFlow> tranCashFlows = new List<TranCashFlow>();
            //    DateTime computeDate = DateTime.Parse(Parameter["computeDate"].ToString());
            //    int riskBookId = int.Parse(Parameter["riskBookId"].ToString());
            //    var riskGroupType = Risk_Group_Type.Risk_Group_Type;
            //    int timeHorizon = int.Parse(Parameter["timeHorizon"].ToString());
            //    int windowSize = int.Parse(Parameter["windowSize"].ToString());

            //    int simulationNumber = int.Parse(Parameter["simulationNumber"].ToString());

            //    int tickNumber = int.Parse(Parameter["tickNumber"].ToString());
            //    int resultNumber = int.Parse(Parameter["resultNumber"].ToString());
            //    int riskModelTypeID = int.Parse(Parameter["riskModelTypeID"].ToString());
            //    string userId = CurrentUser.UserId;
            //    string CurrentUserName = CurrentUser.UserName;
            //    SaveComputeValueAtRiskByUserId2(computeDate, riskBookId, riskGroupType, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, riskModelTypeID, CurrentUser.UserId, CurrentUser.UserName, tranCashFlows);


            //}
            public void SaveComputeValueAtRiskByUserId2(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int riskModelTypeID, string userId, string CurrentUserName, IList<TranCashFlow> tranCashFlows, List<RskDeltaPosition> rskDeltaPositions, List<RskFactorMapping> rskFactorMappings, List<RskCoreFctSimulatedPrice> rskCoreFactorSimulationPrice)
            {
                var coreCacheKey = typeof(RskCoreFactor).Name + "_CACHE";
                Dao.RemoveCache(coreCacheKey);
                var coreFactorInfo = new Framework.QueryInfo("RskCoreFactor");
                coreFactorInfo.AddParam("ActiveFlag", true);
                var coreFactorList = Dao.FindList(coreFactorInfo);
                Dao.AddCache(coreCacheKey, coreFactorList);
                InsertRiskBookSelection2(computeDate, riskBookID, tranCashFlows);
                //风险计量组合头寸 add by kexb 2017年3月10日16:57:15 预留未实现
                InsertRiskBookDeltaPosition(computeDate, riskBookID.ToString());
                bool isBusinessDate = businessDateService.IsBusinessDate(computeDate);
                //if (isBusinessDate)
                //{

                int[] confidenceLevelID = new int[resultNumber];
                var riskGroupTypeDic = SysEnumHelper.GetChildEnumByParentCode(Risk_Group_Type.Risk_Group_Type.ToString()).Select(x => (Risk_Group_Type)x.Value.EnumValue).ToList();

                var dictList = SysEnumHelper.GetChildEnumByParentCode("Confidence_Level");
                int kk = 0;
                foreach (var item in dictList)
                {
                    Contract.Domain.SysEnumDict dict = item.Value as Contract.Domain.SysEnumDict;
                    //confidenceLevel[kk] = dict.EnumValue.ToString();
                    //confidenceLevel[kk] = dict.EnumName;

                    confidenceLevelID[kk] = (int)dict.EnumValue;

                    kk++;
                }

                //set up 01
                ComputeValueAtRiskForSingleHorizon2(computeDate, riskBookID, Risk_Group_Type.Risk_Group_Type, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskModelTypeID, rskDeltaPositions, rskFactorMappings, rskCoreFactorSimulationPrice);
                for (var i = 0; i < riskGroupTypeDic.Count; i++)
                {
                    ComputeValueAtRiskForSingleHorizon2(computeDate, riskBookID, (riskGroupTypeDic[i]), timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskModelTypeID, rskDeltaPositions, rskFactorMappings, rskCoreFactorSimulationPrice);
                }

                //}

            }
            public void Compute(string FormId, System.Collections.Hashtable Parameter)
            {
                DateTime computeDate = DateTime.Parse(Parameter["computeDate"].ToString());
                int riskBookId = int.Parse(Parameter["riskBookId"].ToString());
                var riskGroupType = Risk_Group_Type.Risk_Group_Type;
                int timeHorizon = int.Parse(Parameter["timeHorizon"].ToString());
                int windowSize = int.Parse(Parameter["windowSize"].ToString());

                int simulationNumber = int.Parse(Parameter["simulationNumber"].ToString());

                int tickNumber = int.Parse(Parameter["tickNumber"].ToString());
                int resultNumber = int.Parse(Parameter["resultNumber"].ToString());
                int riskModelTypeID = int.Parse(Parameter["riskModelTypeID"].ToString());
                string userId = CurrentUser.UserId;
                string CurrentUserName = CurrentUser.UserName;
                SaveComputeValueAtRiskByUserId(computeDate, riskBookId, riskGroupType, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, riskModelTypeID, CurrentUser.UserId, CurrentUser.UserName);


            }


            #region Code Body

            /// <summary>
            /// 2014-06-12
            /// edit daidz
            /// 修改了SimulateChangeInMtMValue 方法调用,改为NewSimulateChangeInMtMValue
            /// 修改了ComputeMonteCarloValueAtRisk 方法
            /// </summary>
            /// <param name="computeDate"></param>
            /// <param name="riskBookID"></param>
            /// <param name="attributeGroupID"></param>
            /// <param name="timeHorizon"></param>
            /// <param name="windowSize"></param>
            /// <param name="simulationNumber"></param>
            /// <param name="tickNumber"></param>
            /// <param name="resultNumber"></param>
            /// <param name="confidenceLevel"></param>
            /// <param name="riskModelTypeID"></param>
            ///

            #region Service Area


            IBasBusinessDateService _businessDateService = null;
            IBasBusinessDateService businessDateService
            {
                get
                {
                    if (_businessDateService == null)
                    {
                        _businessDateService = ctx["BasBusinessDateService"] as IBasBusinessDateService;
                    }
                    return _businessDateService;
                }
            }

            IForwardPriceSimulationService _priceSimulationService = null;
            IForwardPriceSimulationService priceSimulationService
            {
                get
                {
                    if (_priceSimulationService == null)
                    {
                        _priceSimulationService = ctx["ForwardPriceSimulationService"] as IForwardPriceSimulationService;
                    }
                    return _priceSimulationService;
                }
            }

            IRskCoreFactorService _riskCoreFactorService = null;
            IRskCoreFactorService riskCoreFactorService
            {
                get
                {
                    if (_riskCoreFactorService == null)
                    {
                        _riskCoreFactorService = ctx["RskCoreFactorService"] as IRskCoreFactorService;
                    }
                    return _riskCoreFactorService;
                }
            }

            IMktPriceMarketDataService _indexPriceService = null;
            IMktPriceMarketDataService indexPriceService
            {
                get
                {
                    if (_indexPriceService == null)
                    {
                        _indexPriceService = ctx["MktPriceMarketDataService"] as IMktPriceMarketDataService;
                    }
                    return _indexPriceService;
                }
            }

            IRiskBookSelectionService _riskBookSelectionService = null;
            IRiskBookSelectionService riskBookSelectionService
            {
                get
                {
                    if (_riskBookSelectionService == null)
                    {
                        _riskBookSelectionService = ctx["RiskBookSelectionService"] as IRiskBookSelectionService;
                    }
                    return _riskBookSelectionService;
                }
            }


            IRskBookSimulationService _riskBookTranSimulationService = null;
            IRskBookSimulationService riskBookTranSimulationService
            {
                get
                {
                    if (_riskBookTranSimulationService == null)
                    {
                        _riskBookTranSimulationService = ctx["RskBookSimulationService"] as IRskBookSimulationService;
                    }
                    return _riskBookTranSimulationService;
                }
            }

            ITranRiskPositionViewService _riskPositionService = null;
            ITranRiskPositionViewService riskPositionService
            {
                get
                {
                    if (_riskPositionService == null)
                    {
                        _riskPositionService = ctx["TranRiskPositionViewService"] as ITranRiskPositionViewService;
                    }
                    return _riskPositionService;
                }
            }

            ITransactionRiskVolumeViewService _riskVolumeService = null;
            ITransactionRiskVolumeViewService riskVolumeService
            {
                get
                {
                    if (_riskVolumeService == null)
                    {
                        _riskVolumeService = ctx["TransactionRiskVolumeViewService"] as ITransactionRiskVolumeViewService;
                    }
                    return _riskVolumeService;
                }
            }

            IRiskBookAttributeSimulationViewService _riskBookAttributeSimulationService = null;
            IRiskBookAttributeSimulationViewService riskBookAttributeSimulationService
            {
                get
                {
                    if (_riskBookAttributeSimulationService == null)
                    {
                        _riskBookAttributeSimulationService = ctx["RiskBookAttributeSimulationViewService"] as IRiskBookAttributeSimulationViewService;
                    }
                    return _riskBookAttributeSimulationService;
                }
            }

            IRskFactorVolatilityDataService _riskVolatilityService = null;
            IRskFactorVolatilityDataService riskVolatilityService
            {
                get
                {
                    if (_riskVolatilityService == null)
                    {
                        _riskVolatilityService = ctx["RskFactorVolatilityDataService"] as IRskFactorVolatilityDataService;
                    }
                    return _riskVolatilityService;
                }
            }

            IRskFactorCorrelationDataService _riskCorrelationDataService = null;
            IRskFactorCorrelationDataService riskCorrelationDataService
            {
                get
                {
                    if (_riskCorrelationDataService == null)
                    {
                        _riskCorrelationDataService = ctx["RskFactorCorrelationDataService"] as IRskFactorCorrelationDataService;
                    }
                    return _riskCorrelationDataService;
                }
            }

            IGaussianDistributionService _normalDistService = null;
            IGaussianDistributionService normalDistService
            {
                get
                {
                    if (_normalDistService == null)
                    {
                        _normalDistService = ctx["GaussianDistributionService"] as IGaussianDistributionService;
                    }
                    return _normalDistService;
                }
            }

            ITranProfitlossService _transactionProfitLossService = null;
            ITranProfitlossService transactionProfitLossService
            {
                get
                {
                    if (_transactionProfitLossService == null)
                    {
                        _transactionProfitLossService = ctx["TranProfitlossService"] as ITranProfitlossService;
                    }
                    return _transactionProfitLossService;
                }
            }

            IRiskBookAttributeCorePositionViewService _riskBookAttributeCorePositionService = null;
            IRiskBookAttributeCorePositionViewService RiskBookAttributeCorePositionService
            {
                get
                {
                    if (_riskBookAttributeCorePositionService == null)
                    {
                        _riskBookAttributeCorePositionService = ctx["RiskBookAttributeCorePositionViewService"] as IRiskBookAttributeCorePositionViewService;
                    }
                    return _riskBookAttributeCorePositionService;
                }
            }

            IRiskBookAttributeRiskPositionViewService _riskBookAttributeRiskPositionViewService = null;
            IRiskBookAttributeRiskPositionViewService riskBookAttributeRiskPositionViewService
            {
                get
                {
                    if (_riskBookAttributeRiskPositionViewService == null)
                    {
                        _riskBookAttributeRiskPositionViewService = ctx["RiskBookAttributeRiskPositionViewService"] as IRiskBookAttributeRiskPositionViewService;
                    }
                    return _riskBookAttributeRiskPositionViewService;
                }
            }

            //IRskBookAttriResultService _riskBookResultService = null;
            //IRskBookAttriResultService riskBookResultService
            //{
            //    get
            //    {
            //        if (_riskBookResultService == null)
            //        {
            //            _riskBookResultService = ctx["RskBookAttriResultService"] as IRskBookAttriResultService;
            //        }
            //        return _riskBookResultService;
            //    }
            //}

            IRiskBookAttributeProfitLossViewService _riskBookAttributeProfitLossViewService = null;
            IRiskBookAttributeProfitLossViewService riskBookAttributeProfitLossViewService
            {
                get
                {
                    if (_riskBookAttributeProfitLossViewService == null)
                    {
                        _riskBookAttributeProfitLossViewService = ctx["riskBookAttributeProfitLossViewService"] as IRiskBookAttributeProfitLossViewService;
                    }
                    return _riskBookAttributeProfitLossViewService;
                }
            }

            IRskBookAttriHistogramService _riskBookAttributeHistogramService = null;
            IRskBookAttriHistogramService riskBookAttributeHistogramService
            {
                get
                {
                    if (_riskBookAttributeHistogramService == null)
                    {
                        _riskBookAttributeHistogramService = ctx["IRskBookAttriHistogramService"] as IRskBookAttriHistogramService;
                    }
                    return _riskBookAttributeHistogramService;
                }
            }

            IRskBookAttriProfitlossService _riskBookAttributeProfitLossService = null;
            IRskBookAttriProfitlossService riskBookAttributeProfitLossService
            {
                get
                {
                    if (_riskBookAttributeProfitLossService == null)
                    {
                        _riskBookAttributeProfitLossService = ctx["RskBookAttriProfitlossService"] as IRskBookAttriProfitlossService;
                    }
                    return _riskBookAttributeProfitLossService;
                }
            }


            #endregion

            public int CorrelationDataTag = 0;
            public string WcfUsername1 = string.Empty;
            static string _CurrentUserId = string.Empty;
            private static string _CurrentUserName = string.Empty;
            public void InsertRiskBookSelection2(DateTime computeDate, int riskBookID, IList<TranCashFlow> tranCashFlows)
            {
                IList<RskBookSelection> riskBookSelections = new List<RskBookSelection>();

                riskBookSelections = riskBookSelectionService.GetRiskBookSelection2(riskBookID, computeDate, Result_Use_Type.Result_Use_Type_EOD_Process, tranCashFlows);
                foreach (RskBookSelection riskBookSelection in riskBookSelections)
                {
                    riskBookSelection.Id = "";
                    riskBookSelection.State.MarkNew();
                }
                // Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookSelection";
                info.AddParam("AsOfDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                Dao.ExecuteUpdate(info);

                Dao.SaveOrUpdateAll<RskBookSelection>(riskBookSelections);
            }

            public void InsertRiskBookSelection(DateTime computeDate, int riskBookID)
            {
                IList<RskBookSelection> riskBookSelections = new List<RskBookSelection>();
                riskBookSelections = riskBookSelectionService.GetRiskBookSelection(riskBookID, computeDate, Result_Use_Type.Result_Use_Type_EOD_Process);
                foreach (RskBookSelection riskBookSelection in riskBookSelections)
                {
                    riskBookSelection.Id = "";
                    riskBookSelection.State.MarkNew();
                }
                Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookSelection";
                info.AddParam("AsOfDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                Dao.ExecuteUpdate(info);

                Dao.SaveOrUpdateAll<RskBookSelection>(riskBookSelections);
            }
            private Spring.Caching.ICache cache;
            private Spring.Caching.ICache SpringCache
            {
                get
                {
                    if (cache == null)
                        cache = (Spring.Caching.ICache)ctx.GetObject("AspNetCache");
                    return cache;
                }
                set { cache = value; }
            }
            private Contract.Common.UserSession CurrentUser
            {
                get
                {
                    //string t2 = System.Web.Hosting.HostingEnvironment.MapPath("~");
                    //string tempFile = t2 + @"temp" + Thread.CurrentContext.GetHashCode() + DateTime.Today.Date.ToString("yyyyMMdd") + ".txt";
                    //Dictionary<string, string> dic = new Dictionary<string, string>();
                    //dic.Add("UserId", FileReadHelper.ReadLine(tempFile, 1));
                    //dic.Add("UserName", FileReadHelper.ReadLine(tempFile, 2));
                    //dic.Add("OfficeId", FileReadHelper.ReadLine(tempFile, 3));
                    //dic.Add("OfficeName", FileReadHelper.ReadLine(tempFile, 4));
                    //dic.Add("PositionId", FileReadHelper.ReadLine(tempFile, 5));
                    //dic.Add("PositionName", FileReadHelper.ReadLine(tempFile, 6));
                    ////dic.Add("UserId", "1");
                    ////dic.Add("UserName", "admin");
                    ////dic.Add("OfficeId", "1");
                    ////dic.Add("PositionId", "1311");
                    ////dic.Add("PositionName", "测试岗位");
                    //return dic;
                    return Constants.RequestCurrentUserDic[Thread.CurrentContext.GetHashCode().ToString()] as Contract.Common.UserSession;
                }
            }
            public void SaveComputeValueAtRiskByUserId(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int riskModelTypeID, string userId, string CurrentUserName)
            {

                InsertRiskBookSelection(computeDate, riskBookID);

                bool isBusinessDate = businessDateService.IsBusinessDate(computeDate);
                //if (isBusinessDate)
                //{

                int[] confidenceLevelID = new int[resultNumber];
                var riskGroupTypeDic = SysEnumHelper.GetChildEnumByParentCode(Risk_Group_Type.Risk_Group_Type.ToString()).Select(x => (Risk_Group_Type)x.Value.EnumValue).ToList();

                var dictList = SysEnumHelper.GetChildEnumByParentCode("Confidence_Level");
                int kk = 0;
                foreach (var item in dictList)
                {
                    Contract.Domain.SysEnumDict dict = item.Value as Contract.Domain.SysEnumDict;
                    //confidenceLevel[kk] = dict.EnumValue.ToString();
                    //confidenceLevel[kk] = dict.EnumName;

                    confidenceLevelID[kk] = (int)dict.EnumValue;

                    kk++;
                }

                //set up 01
                ComputeValueAtRiskForSingleHorizon(computeDate, riskBookID, Risk_Group_Type.Risk_Group_Type, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskModelTypeID);
                for (var i = 0; i < riskGroupTypeDic.Count; i++)
                {
                    ComputeValueAtRiskForSingleHorizon(computeDate, riskBookID, (riskGroupTypeDic[i]), timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskModelTypeID);
                }

                //}

            }
            private void ComputeValueAtRiskForSingleHorizon2(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon,
                int windowSize, int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, int riskModelTypeID,
                List<RskDeltaPosition> rskDeltaPostions, List<RskFactorMapping> rskFactorMappings, List<RskCoreFctSimulatedPrice> rskCoreFctSimulatedPrice)
            {

                bool incVaRFlag = Constants.INCREMENTAL_RISK_YES;
                double[] valueAtRisk = new double[resultNumber];
                double[] valueAtRiskForIR = new double[resultNumber];
                double[] valueAtRiskForFX = new double[resultNumber];
                double[] valueAtRiskForEQ = new double[resultNumber];
                double[] valueAtRiskForCOM = new double[resultNumber];
                double[] monteCarloIncVaR = new double[resultNumber];
                IList<RskBookResult> riskBookResults = new List<RskBookResult>();
                IList<RskBookResult> riskBookResultsToDelete = new List<RskBookResult>();


                //if (riskModelType == "MONTE CARLO")
                if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Monte_Carlo)
                {
                    ComputeMonteCarloValueAtRisk2(computeDate, riskBookID, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskGroupType, 0, incVaRFlag, ref valueAtRisk, ref monteCarloIncVaR, rskDeltaPostions, rskFactorMappings, rskCoreFctSimulatedPrice);
                }
                //else if (riskModelType == "PARAMETRIC")
                else if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Parametric)
                {

                    //ParametricValueAtRiskComputation a = new ParametricValueAtRiskComputation();
                    //a.ComputeParametricValueAtRisk(riskBookID, computeDate, timeHorizon, windowSize, confidenceLevelID, resultNumber, simulationNumber, ref valueAtRisk, ref valueAtRiskForIR, ref valueAtRiskForFX, ref valueAtRiskForEQ
                    //   , ref valueAtRiskForCOM);
                    ComputeParametricValueAtRisk(WcfUsername1, computeDate, riskBookID, simulationNumber, resultNumber, confidenceLevelID, timeHorizon, windowSize, riskGroupType, 0, false, ref valueAtRisk, ref valueAtRiskForIR, ref valueAtRiskForFX, ref valueAtRiskForEQ, ref valueAtRiskForCOM);
                }
                //else if (riskModelType == "HISTORICAL")
                else if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Historical)
                {
                    int daysBack = 100;
                    ComputeHistoricalValueAtRisk(computeDate, daysBack, riskBookID, tickNumber, resultNumber, confidenceLevelID, timeHorizon, windowSize, riskGroupType, 0, false, ref valueAtRisk);
                }
                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    int[] confidenceLevelLookupID = new int[resultNumber];
                    for (int k = 0; k < resultNumber; k++)
                    {
                        //记录全面风险的地方 重要 kexb 2017年1月5日16:17:45
                        RskBookResult riskBookResult = new RskBookResult();
                        riskBookResult.ComputeDate = computeDate;
                        riskBookResult.RiskBookId = riskBookID;
                        riskBookResult.SimulationNumber = simulationNumber;
                        riskBookResult.ConfidenceLevelId = confidenceLevelID[k];
                        //riskBookResult.ConfidenceLevelName = confidenceLevel[k];
                        riskBookResult.VarResultValue = Math.Round((decimal)valueAtRisk[k], 0);
                        riskBookResult.ValueAtRiskForIR = Math.Round((decimal)valueAtRiskForIR[k], 0);
                        riskBookResult.ValueAtRiskForFX = Math.Round((decimal)valueAtRiskForFX[k], 0);
                        riskBookResult.ValueAtRiskForEQ = Math.Round((decimal)valueAtRiskForEQ[k], 0);
                        riskBookResult.ValueAtRiskForCOM = Math.Round((decimal)valueAtRiskForCOM[k], 0);
                        riskBookResult.CvarResultValue = Math.Round((decimal)valueAtRiskForIR[k], 0);
                        riskBookResult.ExpectedShortfallValue = Math.Round((decimal)valueAtRiskForFX[k], 0);
                        riskBookResult.CreateUid = CurrentUser.UserId;
                        riskBookResult.CreateDate = DateTime.Now;
                        riskBookResult.CreateOid = CurrentUser.OfficeId;
                        riskBookResult.State.MarkNew();
                        riskBookResults.Add(riskBookResult);
                    }
                    Dao.GetCurrentSession().Clear();
                    //delete existing dataset first
                    Framework.QueryInfo info = new Framework.QueryInfo();
                    info.CustomSQL = "delete from RskBookResult";
                    info.AddParam("RiskBookId", riskBookID);
                    info.AddParam("SimulationNumber", simulationNumber);
                    info.AddParam("ComputeDate", computeDate);
                    Dao.ExecuteUpdate(info);

                    // then insert the newly computed dataset

                    Dao.SaveOrUpdateAll<RskBookResult>(riskBookResults);

                }
                else
                {
                    if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Parametric)
                    {
                        ComputeRiskPositionByAttributeLookup(computeDate, riskBookID, riskGroupType);

                        ComputeProfitLossByAttributeLookup(computeDate, riskBookID, riskGroupType);
                    }
                }

            }

            private void ComputeValueAtRiskForSingleHorizon(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, int riskModelTypeID)
            {

                bool incVaRFlag = Constants.INCREMENTAL_RISK_YES;
                double[] valueAtRisk = new double[resultNumber];
                double[] valueAtRiskForIR = new double[resultNumber];
                double[] valueAtRiskForFX = new double[resultNumber];
                double[] valueAtRiskForEQ = new double[resultNumber];
                double[] valueAtRiskForCOM = new double[resultNumber];
                double[] monteCarloIncVaR = new double[resultNumber];
                IList<RskBookResult> riskBookResults = new List<RskBookResult>();
                IList<RskBookResult> riskBookResultsToDelete = new List<RskBookResult>();


                //if (riskModelType == "MONTE CARLO")
                if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Monte_Carlo)
                {
                    ComputeMonteCarloValueAtRisk(computeDate, riskBookID, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevelID, riskGroupType, 0, incVaRFlag, ref valueAtRisk, ref monteCarloIncVaR);
                }
                //else if (riskModelType == "PARAMETRIC")
                else if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Parametric)
                {
                    ComputeParametricValueAtRisk(WcfUsername1, computeDate, riskBookID, simulationNumber, resultNumber, confidenceLevelID, timeHorizon, windowSize, riskGroupType, 0, false, ref valueAtRisk, ref valueAtRiskForIR, ref valueAtRiskForFX, ref valueAtRiskForEQ, ref valueAtRiskForCOM);
                }
                //else if (riskModelType == "HISTORICAL")
                else if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Historical)
                {
                    int daysBack = 100;
                    ComputeHistoricalValueAtRisk(computeDate, daysBack, riskBookID, tickNumber, resultNumber, confidenceLevelID, timeHorizon, windowSize, riskGroupType, 0, false, ref valueAtRisk);
                }
                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    int[] confidenceLevelLookupID = new int[resultNumber];
                    for (int k = 0; k < resultNumber; k++)
                    {
                        RskBookResult riskBookResult = new RskBookResult();
                        riskBookResult.ComputeDate = computeDate;
                        riskBookResult.RiskBookId = riskBookID;
                        riskBookResult.SimulationNumber = simulationNumber;
                        riskBookResult.ConfidenceLevelId = confidenceLevelID[k];
                        //riskBookResult.ConfidenceLevelName = confidenceLevel[k];
                        riskBookResult.VarResultValue = Math.Round((decimal)valueAtRisk[k], 0);
                        riskBookResult.ValueAtRiskForIR = Math.Round((decimal)valueAtRiskForIR[k], 0);
                        riskBookResult.ValueAtRiskForFX = Math.Round((decimal)valueAtRiskForFX[k], 0);
                        riskBookResult.ValueAtRiskForEQ = Math.Round((decimal)valueAtRiskForEQ[k], 0);
                        riskBookResult.ValueAtRiskForCOM = Math.Round((decimal)valueAtRiskForCOM[k], 0);
                        riskBookResult.CvarResultValue = Math.Round((decimal)valueAtRiskForIR[k], 0);
                        riskBookResult.ExpectedShortfallValue = Math.Round((decimal)valueAtRiskForFX[k], 0);
                        riskBookResult.CreateUid = CurrentUser.UserId;
                        riskBookResult.CreateDate = DateTime.Now;
                        riskBookResult.CreateOid = CurrentUser.OfficeId;
                        riskBookResult.State.MarkNew();
                        riskBookResults.Add(riskBookResult);
                    }
                    //delete existing dataset first
                    Dao.GetCurrentSession().Clear();
                    Framework.QueryInfo info = new Framework.QueryInfo();
                    info.CustomSQL = "delete from RskBookResult";
                    info.AddParam("RiskBookId", riskBookID);
                    info.AddParam("SimulationNumber", simulationNumber);
                    info.AddParam("ComputeDate", computeDate);
                    Dao.ExecuteUpdate(info);
                    // then insert the newly computed dataset
                    Dao.SaveOrUpdateAll<RskBookResult>(riskBookResults);

                }
                else
                {
                    if (riskModelTypeID == (int)Risk_Model_Type.Risk_Model_Type_Parametric)
                    {
                        ComputeRiskPositionByAttributeLookup(computeDate, riskBookID, riskGroupType);

                        ComputeProfitLossByAttributeLookup(computeDate, riskBookID, riskGroupType);
                    }
                }

            }


            private void SimulateChangeInMtMValue_New(DateTime computeDate, int riskBookID, int timeHorizon, int simulationNumber)
            {
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.NamedQuery = "P_TRAN_SIMULATION";
                info.Parameters.Add("v_RiskBookID", riskBookID);
                info.Parameters.Add("v_ComputeDate", computeDate);
                info.Parameters.Add("v_UserName", CurrentUser.UserName);
                info.Parameters.Add("v_SimulationNumber", simulationNumber);
                info.Parameters.Add("v_timeHorizon", timeHorizon - 1);
                info.Parameters.Add("v_fixed_or_float", Fixed_Or_Float.Fixed_Or_Float.GetEnumName());
                info.Parameters.Add("v_result_use_type", Result_Use_Type.Result_Use_Type_EOD_Process.GetEnumName());
                Dao.ExecuteNonQuery(info);
                Dao.Flush();
            }

            private void SimulateChangeInMtMValue_New2(DateTime computeDate, int riskBookID, int timeHorizon, int simulationNumber, List<RskDeltaPosition> rskDeltaPostions, List<RskFactorMapping> rskFactorMappings, List<RskCoreFctSimulatedPrice> rskCoreFctSimulatedPrice, ref List<RskBookTranSimulation> rskBookTranSimulations)
            {
                Dao.GetCurrentSession().Clear();
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookTranSimulation a where a.ComputeDate=:ComputeDate and a.RiskBookId=:RiskBookId and a.SimulationNumber=:SimulationNumber";
                info.Parameters.Add("ComputeDate", computeDate.Date);
                info.Parameters.Add("RiskBookId", riskBookID);
                info.Parameters.Add("SimulationNumber", simulationNumber);
                Dao.ExecuteUpdate(info);
                Framework.QueryInfo rskBookTranSimulationTInfo = new Framework.QueryInfo();
                rskBookTranSimulationTInfo.CustomSQL = "select * from rsk_book_tran_simulation where 1!=1";
                System.Data.DataTable rskBookTranSimulationT = Dao.ExecuteDataSet(rskBookTranSimulationTInfo).Tables[0];
                System.Data.DataRow newRow;
                //rskDeltaPostions = Dao.FindList<RskDeltaPosition>(new Framework.QueryInfo("RskDeltaPosition")).ToList();
                //暂时这样
                rskCoreFctSimulatedPrice = Dao.FindList<RskCoreFctSimulatedPrice>(new Framework.QueryInfo("RskCoreFctSimulatedPrice")).ToList();
                int? horiId = timeHorizon - 1;
                var list = (from rdp in rskDeltaPostions
                            join rfm in rskFactorMappings
                            on rdp.RiskFactorId
                            equals
                            rfm.RiskFactorId
                            join rcfsp in rskCoreFctSimulatedPrice
                            on rfm.RiskCoreFactorId
                            equals rcfsp.RiskCoreFactorId
                            where rdp.AsOfDate == computeDate.Date
                                  && rcfsp.SimulationNumber == simulationNumber
                                  && rcfsp.HorizonId == horiId
                            select
                            new
                            {
                                rdp.AsOfDate,
                                rdp.TransactionId,
                                rdp.TransactionLegId,
                                rdp.RiskFactorId,
                                rfm.RiskCoreFactorId,
                                rdp.DeltaVolume,
                                rdp.IndexPriceRate,
                                rdp.ResetPriceRate,
                                rcfsp.SimulationId,
                                rcfsp.SimulatedForwardPrice,
                                rcfsp.CurrentPrice,
                                rcfsp.SimulationNumber,
                                rcfsp.HorizonId,


                            }

                            ).GroupBy(x => new { x.AsOfDate, x.TransactionId, x.SimulationNumber, x.SimulationId })


                            .Select(x => new RskBookTranSimulation
                            {

                                RiskBookId = riskBookID,
                                TransactionId = x.Key.TransactionId,
                                ComputeDate = computeDate.Date,
                                SimulationNumber = simulationNumber,
                                SimulationId = x.Key.SimulationId,
                                ChangeInmtmValue = (x.Sum(x2 => (x2.SimulatedForwardPrice - x2.CurrentPrice) * x2.DeltaVolume)),
                                CreateUname = CurrentUser.UserName,
                                CreateDate = computeDate.Date,
                                LastModUname = CurrentUser.UserName,
                                LastModDatetime = DateTime.Now.Date
                            }).ToList();


                rskBookTranSimulations = list;
                #region list保存改为Bulkcopy保存
                //list.ForEach(obj =>
                //{
                //    obj.State.MarkNew();
                //});
                ////这里也得改kexb 20160520
                //Dao.SaveOrUpdateAll<RskBookTranSimulation>(list.ToArray());


                foreach (RskBookTranSimulation r in rskBookTranSimulations)
                {
                    newRow = rskBookTranSimulationT.NewRow();
                    newRow["RISK_BOOK_ID"] = r.RiskBookId;
                    newRow["TRANSACTION_ID"] = r.TransactionId;
                    newRow["COMPUTE_DATE"] = r.ComputeDate;
                    newRow["SIMULATION_NUMBER"] = r.SimulationNumber;
                    newRow["SIMULATION_ID"] = r.SimulationId;
                    newRow["CHANGE_IN_MTM_VALUE"] = r.ChangeInmtmValue;
                    newRow["CREATE_UNAME"] = r.CreateUname;
                    newRow["CREATE_DATE"] = r.CreateDate;
                    newRow["LAST_MOD_UNAME"] = r.LastModUname;
                    newRow["LAST_MOD_DATETIME"] = r.LastModDatetime;
                    rskBookTranSimulationT.Rows.Add(newRow);

                }
                Holworth.Utility.HraUtility.DataTableWriteToServer(rskBookTranSimulationT, "rsk_book_tran_simulation", "RISK_BOOK_TRAN_SIM_ID", true);
                #endregion


            }


            private void ComputeMonteCarloValueAtRisk2(DateTime computeDate, int riskBookID, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, Risk_Group_Type riskGroupType, int attributeID, bool incVaRFlag, ref double[] monteCarloVaR, ref double[] monteCarloIncVaR, List<RskDeltaPosition> rskDeltaPositions, List<RskFactorMapping> rskFactorMappings, List<RskCoreFctSimulatedPrice> rskCoreFactorSimulationPrice)
            {
                double[] changeInMtMValue = new double[simulationNumber];
                double[] tickValue = new double[tickNumber + 1];
                double[] frequencyValue = new double[tickNumber + 1];
                double[] newMonteCarloVaR = new double[resultNumber];

                incVaRFlag = false;

                int i = 0;

                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    //    IRskBookSimulationService riskBookSimulationService = (IRiskBookSimulationService)ServiceLocator.Get("riskBookSimulationService");
                    List<RskBookTranSimulation> rskBookTranSimulations = new List<RskBookTranSimulation>();
                    IList<RskBookSimulation> riskBookSimulations = new List<RskBookSimulation>();
                    //set up 03
                    SimulateChangeInMtMValue_New2(computeDate, riskBookID, timeHorizon, simulationNumber, rskDeltaPositions, rskFactorMappings, rskCoreFactorSimulationPrice, ref rskBookTranSimulations);

                    //快没用了之后注释
                    //Framework.QueryInfo info = new Framework.QueryInfo();
                    //info.Parameters.Add("compute_date", computeDate);
                    //info.Parameters.Add("risk_book_id", riskBookID);
                    //info.Parameters.Add("simulation_number", simulationNumber);
                    //riskBookSimulations = Holworth.Utility.HraUtility.EntityRowMapper.ExcuteRowMapperT<RskBookSimulation>("ValueAtRiskCalculationService", info);
                    //快没用了之后注释


                    riskBookSimulations = rskBookTranSimulations.Where(x => x.ComputeDate == computeDate.Date
                                           && x.RiskBookId == riskBookID
                                           && x.SimulationNumber == simulationNumber)
                                           .GroupBy(x => new { x.ComputeDate, x.RiskBookId, x.SimulationNumber, x.SimulationId })
                                            .Select(x => new RskBookSimulation()
                                            {
                                                Id = "0",
                                                ComputeDate = x.Key.ComputeDate,
                                                RiskBookId = x.Key.RiskBookId,
                                                SimulationNumber = x.Key.SimulationNumber,
                                                SimulationId = x.Key.SimulationId,
                                                ChangeInmtmValue = x.Sum(x2 => x2.ChangeInmtmValue),
                                                //什么东西,我也是从sql.xml ValueAtRiskCalculationService抄的
                                                CreateUid = x.Max(x2 => x2.CreateUid)
                                            }).OrderBy(x => x.ChangeInmtmValue).ToList();

                    for (var k = 0; k < riskBookSimulations.Count; k++)
                    {
                        var riskSimulation = riskBookSimulations[k];
                        changeInMtMValue[k] = (double)riskSimulation.ChangeInmtmValue;
                        i++;
                    }
                    ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref monteCarloVaR);
                }
                else
                {
                    // to be reopened
                    //ComputeMonteCarloValueAtRiskByAttributeLookup(computeDate, riskBookID, riskGroupType, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevel, incVaRFlag);
                }



                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    SaveOrUpdateRiskBookBaseHistogram(computeDate, riskBookID, simulationNumber, tickNumber, tickValue, frequencyValue);
                }
                else
                {
                    //SaveOrUpdateRiskBookAttributeHistogram(computeDate, riskBookID, simulationNumber, tickNumber, attributeID, riskGroupType, tickValue, frequencyValue);
                }

                if (incVaRFlag)
                {


                    IList<RiskBookAttributeSimulationView> riskBookAttributeSimulations = new List<RiskBookAttributeSimulationView>();

                    if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByPortfolioIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByInstrumentTypeIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByCounterpartyIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Commodity)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByCommodityIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Trader)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByTraderIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }

                    i = 0;

                    foreach (RiskBookAttributeSimulationView riskSimulation in riskBookAttributeSimulations)
                    {
                        changeInMtMValue[i] = (double)riskSimulation.SumOfChangeInMtMValue;
                        i++;
                    }
                    ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref newMonteCarloVaR);

                    for (int k = 0; k < resultNumber; k++)
                    {
                        monteCarloIncVaR[k] = newMonteCarloVaR[k] - monteCarloVaR[k];
                    }
                }
            }
            private void ComputeMonteCarloValueAtRisk(DateTime computeDate, int riskBookID, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, Risk_Group_Type riskGroupType, int attributeID, bool incVaRFlag, ref double[] monteCarloVaR, ref double[] monteCarloIncVaR)
            {
                double[] changeInMtMValue = new double[simulationNumber];
                double[] tickValue = new double[tickNumber + 1];
                double[] frequencyValue = new double[tickNumber + 1];
                double[] newMonteCarloVaR = new double[resultNumber];

                incVaRFlag = false;

                int i = 0;

                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    //    IRskBookSimulationService riskBookSimulationService = (IRiskBookSimulationService)ServiceLocator.Get("riskBookSimulationService");

                    IList<RskBookSimulation> riskBookSimulations = new List<RskBookSimulation>();
                    //set up 03
                    SimulateChangeInMtMValue_New(computeDate, riskBookID, timeHorizon, simulationNumber);
                    Framework.QueryInfo info = new Framework.QueryInfo();
                    info.Parameters.Add("compute_date", computeDate);
                    info.Parameters.Add("risk_book_id", riskBookID);
                    info.Parameters.Add("simulation_number", simulationNumber);
                    riskBookSimulations = Holworth.Utility.HraUtility.EntityRowMapper.ExcuteRowMapperT<RskBookSimulation>("ValueAtRiskCalculationService", info);

                    for (var k = 0; k < riskBookSimulations.Count; k++)
                    {
                        var riskSimulation = riskBookSimulations[k];
                        changeInMtMValue[k] = (double)riskSimulation.ChangeInmtmValue;
                        i++;
                    }
                    ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref monteCarloVaR);
                }
                else
                {
                    // to be reopened
                    //ComputeMonteCarloValueAtRiskByAttributeLookup(computeDate, riskBookID, riskGroupType, timeHorizon, windowSize, simulationNumber, tickNumber, resultNumber, confidenceLevel, incVaRFlag);
                }



                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    SaveOrUpdateRiskBookBaseHistogram(computeDate, riskBookID, simulationNumber, tickNumber, tickValue, frequencyValue);
                }
                else
                {
                    //SaveOrUpdateRiskBookAttributeHistogram(computeDate, riskBookID, simulationNumber, tickNumber, attributeID, riskGroupType, tickValue, frequencyValue);
                }

                if (incVaRFlag)
                {


                    IList<RiskBookAttributeSimulationView> riskBookAttributeSimulations = new List<RiskBookAttributeSimulationView>();

                    if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByPortfolioIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByInstrumentTypeIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByCounterpartyIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Commodity)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByCommodityIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }
                    else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Trader)
                    {
                        riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListNotByTraderIDWithSpringDao(riskBookID, computeDate, attributeID, simulationNumber);
                    }

                    i = 0;

                    foreach (RiskBookAttributeSimulationView riskSimulation in riskBookAttributeSimulations)
                    {
                        changeInMtMValue[i] = (double)riskSimulation.SumOfChangeInMtMValue;
                        i++;
                    }
                    ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref newMonteCarloVaR);

                    for (int k = 0; k < resultNumber; k++)
                    {
                        monteCarloIncVaR[k] = newMonteCarloVaR[k] - monteCarloVaR[k];
                    }
                }
            }

            private void ComputeValueAtRiskWithSimulationResults(int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, double[] changeInMtMValue, ref double[] tickValue, ref double[] frequencyValue, ref double[] valueAtRisk)
            {
                double stepLength = (changeInMtMValue[simulationNumber - 1] - changeInMtMValue[0]) / tickNumber;
                tickValue[0] = changeInMtMValue[0];
                frequencyValue[0] = 0.0;
                double sumValue = 0.0;
                double avgValue = 0.0;
                int k = 0;
                for (k = 1; k <= tickNumber; k++)
                {
                    tickValue[k] = tickValue[k - 1] + stepLength;
                    frequencyValue[k] = 0.0;
                }
                for (int i = 0; i < simulationNumber; i++)
                {
                    sumValue += changeInMtMValue[i];

                    for (k = 0; k < tickNumber; k++)
                    {
                        if (tickValue[k] <= changeInMtMValue[i] && changeInMtMValue[i] < tickValue[k + 1])
                        {
                            break;
                        }
                    }
                    frequencyValue[k] += 1;
                }
                avgValue = sumValue / simulationNumber;
                double confidenceLevelValue = 0.99;
                int levelIndex = 0;
                for (int i = 0; i < resultNumber; i++)
                {
                    confidenceLevelValue = GetConfidenceLevelValue((Confidence_Level)confidenceLevelID[i]);
                    levelIndex = Convert.ToInt32((1.0 - confidenceLevelValue) * simulationNumber);

                    if (levelIndex > 0)
                    {
                        valueAtRisk[i] = Math.Round(changeInMtMValue[levelIndex - 1] - avgValue, 5);
                    }
                    else
                    {
                        valueAtRisk[i] = -999.999;
                    }
                }
            }

            private double GetConfidenceLevelValue(Confidence_Level confidenceLevelID)
            {
                return double.Parse(confidenceLevelID.GetEnumDefaultValue());
            }
            /// <summary>
            ///
            /// </summary>
            /// <param name="computeDate"></param>
            /// <param name="daysBack"></param>
            /// <param name="riskBookID"></param>
            /// <param name="tickNumber"></param>
            /// <param name="resultNumber"></param>
            /// <param name="confidenceLevelID"></param>
            /// <param name="timeHorizon"></param>
            /// <param name="windowSize"></param>
            /// <param name="attributeGroupID"></param>
            /// <param name="attributeID"></param>
            /// <param name="incVaRFlag"></param>
            /// <param name="valueAtRisk"></param>
            private void ComputeHistoricalValueAtRisk(DateTime computeDate, int daysBack, int riskBookID, int tickNumber, int resultNumber, int[] confidenceLevelID, int timeHorizon, int windowSize, Risk_Group_Type riskGroupType, int attributeID, bool incVaRFlag, ref double[] valueAtRisk)
            {


                //  IRiskFactorService riskFactorService = (IRiskFactorService)ServiceLocator.Get("riskFactorService");

                IList<RskCoreFactor> riskCoreFactors = riskCoreFactorService.GetActiveListByIDWithSpringDao(Constants.ACTIVE);

                int riskCoreFactorNumber = riskCoreFactors.Count;
                int numberOfDays = 0;

                //kexb 2016.2.16 修改注释无用的变量
                //int[] riskFactorID = new int[riskCoreFactorNumber];
                int[] riskCoreFactorID = new int[riskCoreFactorNumber];
                double[] riskPosition = new double[riskCoreFactorNumber];
                //kexb 2016.2.16 修改注释无用的变量
                //double[] riskExposure = new double[riskCoreFactorNumber];
                double[] currentPrice = new double[riskCoreFactorNumber];
                //kexb 2016.2.16 修改注释无用的变量
                //double[] riskVolatility = new double[riskCoreFactorNumber];

                DateTime startDate = computeDate.AddDays(-daysBack);
                DateTime endDate = computeDate;

                double[,] indexPriceDataMatrix = new double[riskCoreFactorNumber, daysBack];
                double[] changeInMtMValue = new double[daysBack - timeHorizon];
                //double[] valueAtRisk = new double[resultNumber];


                int i = 0;
                int j = 0;

                for (j = 0; j < daysBack - timeHorizon; j++)
                {
                    changeInMtMValue[j] = 0.0;
                }


                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    //   ITransactionCurveRiskPositionViewService riskPositionService = (ITransactionCurveRiskPositionViewService)ServiceLocator.Get("transactionCurveRiskPositionViewService");
                    IList<TranRiskPositionView> riskFactorPositions = new List<TranRiskPositionView>();

                    riskFactorPositions = riskPositionService.GetListByDateWithSpringDao(computeDate, windowSize);
                    //riskFactorPositions = riskPositionService.GetListByDateWithSpringDao(computeDate);

                    IList<MktPriceMarketData> indexPriceDataList = new List<MktPriceMarketData>();
                    IList<RskBookSimulation> riskBookSimulationList = new List<RskBookSimulation>();
                    Framework.QueryInfo info = new Framework.QueryInfo();
                    info.QueryObject = "MktPriceMarketData";
                    info.AddParam("CloseDate", computeDate);
                    foreach (TranRiskPositionView riskFactorPosition in riskFactorPositions)
                    {
                        riskCoreFactorID[i] = riskFactorPosition.RiskCoreFactorID;
                        // riskPosition[i] = (double)riskFactorPosition.RiskPosition;
                    }
                    info.AddParam("IndexPriceFactorId", riskCoreFactorID, " and IndexPriceFactorId in(:IndexPriceFactorId)");
                    var currentList = Holworth.Utility.HraUtility.ListToT<MktPriceMarketData>(Dao.FindList(info));
                    info = new Framework.QueryInfo();
                    info.QueryObject = "MktPriceMarketData";
                    info.AddParam("CloseDate", startDate, " and CloseDate between :CloseDate and :endDate");
                    info.Parameters.Add("endDate", endDate);
                    info.AddParam("IndexPriceFactorId", riskCoreFactorID, " and IndexPriceFactorId in(:IndexPriceFactorId)");
                    var indexPriceAll = Holworth.Utility.HraUtility.ListToT<MktPriceMarketData>(Dao.FindList(info));
                    foreach (TranRiskPositionView riskFactorPosition in riskFactorPositions)
                    {
                        riskCoreFactorID[i] = riskFactorPosition.RiskCoreFactorID;
                        riskPosition[i] = (double)riskFactorPosition.RiskPosition;
                        var tmp = (from m in currentList
                                   where m.IndexPriceFactor.Id == riskCoreFactorID[i].ToString()
                                   select m).ToList();
                        indexPriceDataList = (from m in indexPriceAll
                                              where m.IndexPriceFactor.Id == riskCoreFactorID[i].ToString()
                                              select m).ToList();
                        if (tmp.Count == 1)
                        {
                            if (tmp[0].MiddlePriceValue < 0)
                            {
                                currentPrice[i] = 0.0001;
                            }
                            else
                            {
                                currentPrice[i] = System.Convert.ToDouble(tmp[0].MiddlePriceValue);
                            }
                        }
                        else
                        {
                            currentPrice[i] = 0.0001;
                        }
                        //here assume riskcorefactorid = riskfactorid = indexpricefactorid, need to refine
                        // currentPrice[i] = (double)indexPriceService.GetIndexPriceValueByDateIDWithSpringDao(computeDate, riskCoreFactorID[i]);

                        // indexPriceDataList = indexPriceService.GetListByStartDateFactorIDWithSpringDao(startDate, endDate, riskCoreFactorID[i]);

                        j = 0;
                        if (indexPriceDataList != null && indexPriceDataList.Count > 0)
                        {
                            foreach (MktPriceMarketData indexPriceMarketData in indexPriceDataList)
                            {
                                indexPriceDataMatrix[i, j] = (double)indexPriceMarketData.MiddlePriceValue;
                                j++;
                            }
                        }
                        numberOfDays = Math.Max(numberOfDays, j);
                        i++;
                    }
                    int k = 0;
                    for (j = timeHorizon; j < numberOfDays; j++)
                    {
                        k = j - timeHorizon;

                        for (i = 0; i < riskCoreFactorNumber; i++)
                        {
                            if (indexPriceDataMatrix[i, k] > 0.0)
                            {
                                changeInMtMValue[k] += (indexPriceDataMatrix[i, j] - indexPriceDataMatrix[i, k]) / indexPriceDataMatrix[i, k] * riskPosition[i];
                            }
                        }
                    }
                    int simulationNumber = numberOfDays - timeHorizon;
                    double[] tickValue = new double[tickNumber + 1];
                    double[] frequencyValue = new double[tickNumber + 1];
                    for (k = 0; k < simulationNumber; k++)
                    {
                        RskBookSimulation riskBookSimulation = new RskBookSimulation();
                        riskBookSimulation.ComputeDate = computeDate;
                        riskBookSimulation.RiskBookId = riskBookID;
                        riskBookSimulation.SimulationNumber = simulationNumber;
                        riskBookSimulation.SimulationId = k + 1;
                        riskBookSimulation.ChangeInmtmValue = (decimal)changeInMtMValue[k];
                        riskBookSimulation.CreateUname = CurrentUser.UserName;
                        riskBookSimulation.CreateUid = CurrentUser.UserId;
                        riskBookSimulation.CreateDate = DateTime.Now;
                        riskBookSimulation.State.MarkNew();
                        riskBookSimulationList.Add(riskBookSimulation);
                    }
                    //kexb 2016.2.16 修改注释无用的变量
                    //IList<RskBookSimulation> riskBookSimulationsToDelete = new List<RskBookSimulation>();
                    // IRskBookSimulationService riskBookSimulationService = (IRiskBookSimulationService)ServiceLocator.Get("riskBookSimulationService");
                    Dao.GetCurrentSession().Clear();
                    info = new Framework.QueryInfo();
                    info.CustomSQL = "delete from RskBookSimulation";
                    info.AddParam("ComputeDate", computeDate);
                    info.AddParam("SimulationNumber", simulationNumber);
                    Dao.ExecuteUpdate(info);
                    Dao.SaveOrUpdateAll<RskBookSimulation>(riskBookSimulationList);

                    ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref valueAtRisk);
                    SaveOrUpdateRiskBookBaseHistogram(computeDate, riskBookID, simulationNumber, tickNumber, tickValue, frequencyValue);
                }
            }

            private decimal GetValueByDateFactorIDSize(DateTime computeDate, int riskFactorID, int windowSize, IList<RskFactorVolatilityData> list)
            {
                decimal riskVolatilityValue = new decimal();
                IList<RskFactorVolatilityData> indexPriceMarketDataList = list.Where(m => m.RiskFactorId == riskFactorID).ToList();
                if (indexPriceMarketDataList.Count == 1)
                {
                    for (var i = 0; i < indexPriceMarketDataList.Count; i++)
                    {
                        var riskVolatility = indexPriceMarketDataList[i];
                        riskVolatilityValue = riskVolatility.VolatilityValue;
                        if (riskVolatilityValue < 0)
                            riskVolatilityValue = 0.0001m;
                    }
                }
                else
                    riskVolatilityValue = 0.0001m;

                return riskVolatilityValue;
            }

            private void ComputeParametricValueAtRisk(string WcfUsername,
                                                      DateTime computeDate,
                                                      int riskBookID,
                                                      int simulationNumber,
                                                      int resultNumber,
                                                      int[] confidenceLevelID,
                                                      int timeHorizon,
                                                      int windowSize,
                                                      Risk_Group_Type riskGroupType,
                                                      int attributeID,
                                                      bool incVaRFlag,
                                                      ref double[] valueAtRisk,
                                                      ref double[] valueAtRiskForIR,
                                                      ref double[] valueAtRiskForFX,
                                                      ref double[] valueAtRiskForEQ,
                                                      ref double[] valueAtRiskForCOM)
            {


                //  IRiskFactorService riskFactorService = (IRiskFactorService)ServiceLocator.Get("riskFactorService");
                //IRiskCoreFactorService riskCoreFactorService = (IRiskCoreFactorService)ServiceLocator.Get("riskCoreFactorService");
                IList<RskCoreFactor> riskCoreFactors = riskCoreFactorService.GetActiveListByIDWithSpringDao(Constants.ACTIVE);

                int riskCoreFactorNumber = riskCoreFactors.Count;
                //    IIndexPriceMarketDataService indexPriceService = (IIndexPriceMarketDataService)ServiceLocator.Get("indexPriceMarketDataService");
                //    IRiskFactorVolatilityDataService riskVolatilityService = (IRiskFactorVolatilityDataService)ServiceLocator.Get("riskFactorVolatilityDataService");

                //ITransactionCurveRiskPositionViewService riskPositionService = (ITransactionCurveRiskPositionViewService)ServiceLocator.Get("transactionCurveRiskPositionViewService");
                //IList<TransactionCurveRiskPositionView> riskFactorPositions = new List<TransactionCurveRiskPositionView>();

                //kexb 2016.2.16 修改注释无用的变量
                //double[,] marginalVaR = new double[resultNumber, riskCoreFactorNumber];
                //kexb 2016.2.16 修改注释无用的变量
                //double[,] componentVaR = new double[resultNumber, riskCoreFactorNumber];


                int[] riskFactorID = new int[riskCoreFactorNumber];
                int[] riskCoreFactorID = new int[riskCoreFactorNumber];
                double[] riskPosition = new double[riskCoreFactorNumber];
                double[] riskExposure = new double[riskCoreFactorNumber];
                double[] riskPositionForIR = new double[riskCoreFactorNumber];
                double[] riskExposureForIR = new double[riskCoreFactorNumber];
                double[] riskPositionForFX = new double[riskCoreFactorNumber];
                double[] riskExposureForFX = new double[riskCoreFactorNumber];
                double[] riskPositionForEQ = new double[riskCoreFactorNumber];
                double[] riskExposureForEQ = new double[riskCoreFactorNumber];
                double[] riskPositionForCOM = new double[riskCoreFactorNumber];
                double[] riskExposureForCOM = new double[riskCoreFactorNumber];
                double[] currentPrice = new double[riskCoreFactorNumber];
                double[] riskVolatility = new double[riskCoreFactorNumber];

                double sumOfPortfolioVariance = 1.0;
                double[] varDelta = new double[riskCoreFactorNumber];


                int i = 0;
                int j = 0;

                if (riskGroupType == Risk_Group_Type.Risk_Group_Type)
                {
                    //  ITransactionCurveRiskPositionViewService riskPositionService = (ITransactionCurveRiskPositionViewService)ServiceLocator.Get("transactionCurveRiskPositionViewService");
                    IList<TranRiskPositionView> riskFactorPositions = new List<TranRiskPositionView>();
                    riskFactorPositions = riskPositionService.GetListByDateWithSpringDao(computeDate, windowSize);
                    //riskFactorPositions = riskPositionService.GetListByDateWithSpringDao(computeDate);
                    System.Collections.ArrayList list = new System.Collections.ArrayList();
                    for (var ii = 0; ii < riskFactorPositions.Count; ii++)
                    {
                        var riskFactorPosition = riskFactorPositions[ii];
                        list.Add(riskFactorPosition.RiskFactorID.ToString());
                    }
                    if (list.Count > 0)
                    {
                        Framework.QueryInfo info = new Framework.QueryInfo();
                        info.QueryObject = "RskFactorVolatilityData";
                        info.AddParam("ComputeDate", computeDate);
                        string[] aa = list.ToArray(typeof(string)) as string[];
                        info.AddParam("RiskFactorId", aa, " and RiskFactorId in(:RiskFactorId)");
                        IList<RskFactorVolatilityData> RiskFactorVolatilityDataList = Holworth.Utility.HraUtility.ListToT<RskFactorVolatilityData>(Dao.FindList(info));
                        for (i = 0; i < riskFactorPositions.Count; i++)
                        {
                            var riskFactorPosition = riskFactorPositions[i];
                            riskFactorID[i] = riskFactorPosition.RiskFactorID;
                            riskCoreFactorID[i] = riskFactorPosition.RiskCoreFactorID;
                            riskPosition[i] = (double)riskFactorPosition.RiskPosition;
                            riskExposure[i] = (double)riskFactorPosition.RiskExposure;
                            riskPositionForIR[i] = (double)riskFactorPosition.RiskPositionForIR;
                            riskExposureForIR[i] = (double)riskFactorPosition.RiskExposureForIR;
                            riskPositionForFX[i] = (double)riskFactorPosition.RiskPositionForFX;
                            riskExposureForFX[i] = (double)riskFactorPosition.RiskExposureForFX;
                            riskPositionForEQ[i] = (double)riskFactorPosition.RiskPositionForEQ;
                            riskExposureForEQ[i] = (double)riskFactorPosition.RiskExposureForEQ;
                            riskPositionForCOM[i] = (double)riskFactorPosition.RiskPositionForCOM;
                            riskExposureForCOM[i] = (double)riskFactorPosition.RiskExposureForCOM;
                            riskVolatility[i] = (double)GetValueByDateFactorIDSize(computeDate, riskFactorID[i], windowSize, RiskFactorVolatilityDataList);

                            //riskExposure[i] = riskPosition[i] * riskVolatility[i];

                        }
                    }
                    riskCoreFactorNumber = i;
                    try
                    {
                        ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposure, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRisk);
                    }
                    catch (Exception e)
                    {

                        throw e;
                    }
                    if (CorrelationDataTag == 1)
                    {
                        CorrelationDataTag = 0;
                        return;
                    }
                    try
                    {
                        ComputeMarginalValueAtRisk(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, sumOfPortfolioVariance, varDelta, riskPosition, riskVolatility, timeHorizon, resultNumber, confidenceLevelID);

                    }
                    catch (Exception e)
                    {

                        throw e;
                    }
                    try
                    {
                        ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForIR, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForIR);
                        ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForFX, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForFX);
                        ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForEQ, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForEQ);
                        ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForCOM, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForCOM);
                    }
                    catch (Exception e)
                    {

                        throw e;
                    }
                    try
                    {
                        //comment out for testing
                        ComputeValueAtRiskBacktest(WcfUsername1, computeDate, riskBookID, simulationNumber, timeHorizon, resultNumber, confidenceLevelID);
                    }
                    catch (Exception e)
                    {

                        throw e;
                    }

                }
                else
                {
                    ComputeParametricValueAtRiskByAttributeLookup(computeDate, riskBookID, riskGroupType, timeHorizon, windowSize, resultNumber, confidenceLevelID, incVaRFlag, WcfUsername);

                }
            }

            private void ComputeValueAtRiskWithRiskExposure(DateTime computeDate, int riskBookID, int riskCoreFactorNumber, int[] riskCoreFactorID,
                double[] riskExposure, int timeHorizon, int resultNumber, int[] confidenceLevelID, ref double sumOfPortfolioVariance, ref double[] varDelta, ref double[] parametricVaR)
            {
                int riskCorrelationID = new int();
                double correlationValue = new double();
                double[,] marginalVaR = new double[resultNumber, riskCoreFactorNumber];
                double[,] componentVaR = new double[resultNumber, riskCoreFactorNumber];
                double sumOfDiagonalElement = 0;
                double sumOfNonDiagonalElement = 0;
                double sumProduct = 0;
                int i = 0;
                int j = 0;
                //Dao.GetCurrentSession().Clear();
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.QueryObject = "RskFactorCorrelationData";//  "select * from Rsk_Factor_Correlation_Data where compute_date=:computedate"; //
                info.AddParam("ComputeDate", computeDate);
                IList<RskFactorCorrelationData> allRskFactorCorrelationDataList = null;
                string key = "RskFactorCorrelationData_Cache";
                var cacheList = Dao.GetCache(key);
                if (cacheList == null)
                {
                    Dao.GetCurrentSession().Clear();
                    allRskFactorCorrelationDataList = Dao.FindList<RskFactorCorrelationData>(info);

                    Dao.AddCache(key, allRskFactorCorrelationDataList);
                }
                else
                {
                    allRskFactorCorrelationDataList = (IList<RskFactorCorrelationData>)cacheList;
                }
                var allRskFactorCorrelationDict = allRskFactorCorrelationDataList.ToLookup(x => x.RiskCoreFactorId1 + "," + x.RiskCoreFactorId2);
                //allRskFactorCorrelationDataList =Dao.FindList<RskFactorCorrelationData>(info);//Holworth.Utility.HraUtility.ListToT<RskFactorCorrelationData>(Dao.FindList(info));
                for (i = 0; i < riskCoreFactorNumber; i++)
                {
                    if (riskExposure[i] != 0)
                    {
                        sumProduct = 0.0;
                        for (j = 0; j < riskCoreFactorNumber; j++)
                        {
                            if (riskCoreFactorID[i] != 0 && riskCoreFactorID[j] != 0 && riskCoreFactorID[j] != riskCoreFactorID[i])
                            {
                                if (riskCoreFactorID[j] > riskCoreFactorID[i])
                                {
                                    var tmpList = allRskFactorCorrelationDict[riskCoreFactorID[i] + "," + riskCoreFactorID[j]];
                                    //var tmpList = (from m in allRskFactorCorrelationDataList
                                    //               where m.RiskCoreFactorId1 == riskCoreFactorID[i].ToString() && m.RiskCoreFactorId2 == riskCoreFactorID[j].ToString()
                                    //               select m).ToList();
                                    if (tmpList.LongCount() > 0)
                                    {
                                        correlationValue = System.Convert.ToDouble(tmpList.FirstOrDefault().CorrelationValue.Value);
                                    }
                                }
                                else // risk factor ID for j is less than risk factor ID for i, make reverse search for correlation ID
                                {
                                    var tmpList = allRskFactorCorrelationDict[riskCoreFactorID[j] + "," + riskCoreFactorID[i]];
                                    //var tmpList = (from m in allRskFactorCorrelationDataList
                                    //               where m.RiskCoreFactorId1 == riskCoreFactorID[j].ToString() && m.RiskCoreFactorId2 == riskCoreFactorID[i].ToString()
                                    //               select m).ToList();
                                    if (tmpList.LongCount() > 0)
                                    {
                                        correlationValue = System.Convert.ToDouble(tmpList.FirstOrDefault().CorrelationValue.Value);
                                    }
                                }
                                sumOfNonDiagonalElement += riskExposure[i] * correlationValue * riskExposure[j];
                            }
                            else
                            {
                                if (riskCoreFactorID[i] == 0)
                                {
                                    //LOG.Warn("Zero risk factor ID is found for " + riskCoreFactorID[i].ToString());
                                }
                                else if (riskCoreFactorID[j] == 0)
                                {
                                    //  LOG.Warn("Zero risk factor ID is found for " + riskCoreFactorID[j].ToString());
                                }
                                else // in diagonal case of risk factor ID for j is equal to risk factor ID for i, correlation value is 1.0
                                {
                                    correlationValue = 1.0;
                                    sumOfDiagonalElement += riskExposure[i] * correlationValue * riskExposure[j];
                                }

                            }
                            sumProduct += correlationValue * riskExposure[j];
                        }
                        varDelta[i] = sumProduct;
                    }
                }

                //sumOfPortfolioVariance = sumOfDiagonalElement + 2 * sumOfNonDiagonalElement;
                sumOfPortfolioVariance = sumOfDiagonalElement + sumOfNonDiagonalElement;
                double alphaValue = 0;
                double confidenceLevelValue = 0.99;
                for (int k = 0; k < resultNumber; k++)
                {
                    confidenceLevelValue = GetConfidenceLevelValue((Confidence_Level)confidenceLevelID[k]);
                    alphaValue = normalDistService.GetInverseCumulativeVariate(confidenceLevelValue);
                    if (sumOfPortfolioVariance > 0)
                    {
                        parametricVaR[k] = alphaValue * Math.Sqrt(sumOfPortfolioVariance * timeHorizon);
                    }
                    else
                    {
                        parametricVaR[k] = -999.99;
                    }




                }

            }


            private void ComputeMarginalValueAtRisk(DateTime computeDate, int riskBookID, int riskCoreFactorNumber, int[] riskCoreFactorID, double sumOfPortfolioVariance, double[] varDelta, double[] riskPosition, double[] riskVolatility, int timeHorizon, int resultNumber, int[] confidenceLevelID)
            {
                double[,] marginalVaR = new double[resultNumber, riskCoreFactorNumber];
                double[,] componentVaR = new double[resultNumber, riskCoreFactorNumber];
                // IGaussianDistributionService normalDistService = (IGaussianDistributionService)ServiceLocator.Get("gaussianDistributionService");

                double alphaValue = 0;
                double confidenceLevelValue = 0.99;

                for (int k = 0; k < resultNumber; k++)
                {
                    confidenceLevelValue = GetConfidenceLevelValue((Confidence_Level)confidenceLevelID[k]);

                    alphaValue = normalDistService.GetInverseCumulativeVariate(confidenceLevelValue);

                    for (int i = 0; i < riskCoreFactorNumber; i++)
                    {
                        if (sumOfPortfolioVariance != 0)
                        {
                            marginalVaR[k, i] = alphaValue * varDelta[i] * Math.Sqrt(timeHorizon) * riskVolatility[i] / Math.Sqrt(sumOfPortfolioVariance);
                        }
                        else
                        {
                            marginalVaR[k, i] = 0.0;
                        }
                        //componentVaR[k, i] = marginalVaR[k, i] * riskPosition[i] * currentPrice[i];
                        componentVaR[k, i] = marginalVaR[k, i] * riskPosition[i];
                    }

                }

                IList<RskBookMarginalResult> riskBookMarginalResults = new List<RskBookMarginalResult>();
                //kexb 2016.2.16 修改注释无用的变量
                IList<RskBookMarginalResult> riskBookMarginalResultsToDelete = new List<RskBookMarginalResult>();


                for (int k = 0; k < resultNumber; k++)
                {
                    for (int i = 0; i < riskCoreFactorNumber; i++)
                    {
                        RskBookMarginalResult riskBookMarginalResult = new RskBookMarginalResult();

                        riskBookMarginalResult.ComputeDate = computeDate;
                        riskBookMarginalResult.RiskBookId = riskBookID;
                        riskBookMarginalResult.RiskCoreFactorId = riskCoreFactorID[i];
                        riskBookMarginalResult.ConfidenceLevelId = confidenceLevelID[k];
                        riskBookMarginalResult.VarDeltaValue = Math.Round((decimal)marginalVaR[k, i], 4);
                        riskBookMarginalResult.MarginalVarValue = Math.Round((decimal)marginalVaR[k, i], 4);
                        riskBookMarginalResult.ComponentVarValue = Math.Round((decimal)componentVaR[k, i], 4);

                        //需要修改的地方
                        riskBookMarginalResult.CreateUname = CurrentUser.UserName;
                        riskBookMarginalResult.CreateDate = DateTime.Now;
                        riskBookMarginalResult.State.MarkNew();
                        riskBookMarginalResults.Add(riskBookMarginalResult);
                    }
                }
                Dao.GetCurrentSession().Clear();
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookMarginalResult";
                info.AddParam("ComputeDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                Dao.ExecuteUpdate(info);
                Dao.SaveOrUpdateAll<RskBookMarginalResult>(riskBookMarginalResults);
            }

            private void ComputeValueAtRiskBacktest(string WcfUserName, DateTime computeDate, int riskBookID, int simulationNumber, int timeHorizon, int resultNumber, int[] confidenceLevelID)
            {

                //string[] confidenceLevelLookupID = new string[resultNumber];
                //confidenceLevel[0] = Constants.CONFIDENCE_LEVEL99_NAME;
                //confidenceLevel[1] = Constants.CONFIDENCE_LEVEL975_NAME;
                //confidenceLevel[2] = Constants.CONFIDENCE_LEVEL95_NAME;
                //confidenceLevel[3] = Constants.CONFIDENCE_LEVEL90_NAME;
                //confidenceLevel[4] = Constants.CONFIDENCE_LEVEL50_NAME;

                // IRskBookBacktestService riskBookBacktestService = (IRiskBookBacktestService)ServiceLocator.Get("riskBookBacktestService");
                //  ITransactionProfitLossService transactionProfitLossService = (ITransactionProfitLossService)ServiceLocator.Get("transactionProfitLossService");

                IList<RskBookBacktest> riskBookBacktests = new List<RskBookBacktest>();
                IList<RskBookBacktest> riskBookBacktestsToDelete = new List<RskBookBacktest>();

                //IBasDailyProfitLossViewService dailyProfitLossService = (IBaseDailyProfitLossViewService)ServiceLocator.Get("baseDailyProfitLossViewService");

                double changeInMtMValue = 0.0;
                double valueAtRisk = 0.0;

                double upperBoundValue = 0.0;
                double lowerBoundValue = 0.0;
                double upperOutlierValue = 0.0;
                double lowerOutlierValue = 0.0;

                //IBusinessDateService businessDateService = (IBusinessDateService)ServiceLocator.Get("businessDateService");

                DateTime endDate = computeDate;

                DateTime startDate = computeDate;

                for (int i = 0; i < timeHorizon; i++)
                {
                    startDate = startDate.AddDays(-1);

                    if (!businessDateService.IsBusinessDate(startDate))
                    {
                        startDate = businessDateService.GetBestPriorBusinessDate(startDate, Constants.DAYS_BACK_FOR_BUSINESS_DATE);
                    }
                }
                IList<ValueSumVO> ValueSumList = new List<ValueSumVO>();
                ValueSumList = transactionProfitLossService.GetSumListByDatesUseTypeIDWithSpringDao(riskBookID, startDate, endDate, Result_Use_Type.Result_Use_Type_EOD_Process);

                if (ValueSumList != null && ValueSumList.Count > 0)
                {

                    foreach (ValueSumVO valueSum in ValueSumList)
                    {
                        changeInMtMValue = (double)valueSum.SumValue;
                    }
                }

                for (int i = 0; i < resultNumber; i++)
                {
                    RskBookBacktest riskBookBacktest = new RskBookBacktest();

                    //confidenceLevelLookupID[i] = confidenceLevel[i];

                    IList<ValueVaRVO> ValueVaRList = new List<ValueVaRVO>();

                    ValueVaRList = transactionProfitLossService.GetVaRListByDateIDNumberWithSpringDao(startDate, riskBookID, simulationNumber, confidenceLevelID[i]);

                    if (ValueVaRList != null && ValueVaRList.Count > 0)
                    {

                        foreach (ValueVaRVO valueVaR in ValueVaRList)
                        {
                            valueAtRisk = (double)valueVaR.VaRValue;
                        }
                    }

                    upperBoundValue = valueAtRisk;
                    lowerBoundValue = -valueAtRisk;

                    if (changeInMtMValue > 0.0 && changeInMtMValue > upperBoundValue)
                    {
                        upperOutlierValue = changeInMtMValue - upperBoundValue;
                    }

                    if (changeInMtMValue < 0.0 && changeInMtMValue < lowerBoundValue)
                    {
                        lowerOutlierValue = changeInMtMValue - lowerBoundValue;
                    }


                    riskBookBacktest.ComputeDate = startDate;
                    riskBookBacktest.RiskBookId = riskBookID;
                    riskBookBacktest.SimulationNumber = simulationNumber;
                    riskBookBacktest.ConfidenceLevelId = (Confidence_Level)confidenceLevelID[i];
                    riskBookBacktest.ChangeInmtmValue = (decimal)changeInMtMValue;
                    riskBookBacktest.UpperBoundValue = (decimal)upperBoundValue;
                    riskBookBacktest.LowerBoundValue = (decimal)lowerBoundValue;
                    riskBookBacktest.UpperOutlierValue = (decimal)upperOutlierValue;
                    riskBookBacktest.LowerOutlierValue = (decimal)lowerOutlierValue;
                    riskBookBacktest.CreateUname = _CurrentUserName; ;
                    riskBookBacktest.CreateDate = DateTime.Now;
                    riskBookBacktest.State.MarkNew();
                    riskBookBacktests.Add(riskBookBacktest);

                }
                Dao.GetCurrentSession().Clear();
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookBacktest";
                info.AddParam("ComputeDate", startDate);
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("SimulationNumber", simulationNumber);
                Dao.ExecuteUpdate(info);
                Dao.SaveOrUpdateAll<RskBookBacktest>(riskBookBacktests);
            }

            private void ComputeParametricValueAtRiskByAttributeLookup(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon, int windowSize, int resultNumber, int[] confidenceLevelID, bool incVaRFlag, string WcfUserName)
            {


                IList<RskCoreFactor> riskCoreFactors = riskCoreFactorService.GetActiveListByIDWithSpringDao(Constants.ACTIVE);

                int riskCoreFactorNumber = riskCoreFactors.Count;

                int attributeID = 0;
                string attributeName = null;
                string attribute = null;

                int[] riskFactorID = new int[riskCoreFactorNumber];
                int[] riskCoreFactorID = new int[riskCoreFactorNumber];
                double[] riskPosition = new double[riskCoreFactorNumber];
                double[] riskExposure = new double[riskCoreFactorNumber];
                double[] riskPositionForIR = new double[riskCoreFactorNumber];
                double[] riskExposureForIR = new double[riskCoreFactorNumber];
                double[] riskPositionForFX = new double[riskCoreFactorNumber];
                double[] riskExposureForFX = new double[riskCoreFactorNumber];
                double[] riskPositionForEQ = new double[riskCoreFactorNumber];
                double[] riskExposureForEQ = new double[riskCoreFactorNumber];
                double[] riskPositionForCOM = new double[riskCoreFactorNumber];
                double[] riskExposureForCOM = new double[riskCoreFactorNumber];
                //kexb 2016.2.16 修改注释无用的变量
                //double[] currentPrice = new double[riskCoreFactorNumber];
                double[] riskVolatility = new double[riskCoreFactorNumber];

                //string[] confidenceLevelLookupID = new string[resultNumber];
                //confidenceLevel[0] = Constants.CONFIDENCE_LEVEL99_NAME;
                //confidenceLevel[1] = Constants.CONFIDENCE_LEVEL975_NAME;
                //confidenceLevel[2] = Constants.CONFIDENCE_LEVEL95_NAME;
                //confidenceLevel[3] = Constants.CONFIDENCE_LEVEL90_NAME;
                //confidenceLevel[4] = Constants.CONFIDENCE_LEVEL50_NAME;

                double[] valueAtRisk = new double[resultNumber];
                double[] valueAtRiskForIR = new double[resultNumber];
                double[] valueAtRiskForFX = new double[resultNumber];
                double[] valueAtRiskForEQ = new double[resultNumber];
                double[] valueAtRiskForCOM = new double[resultNumber];
                double sumOfPortfolioVariance = 0.0;
                double[] varDelta = new double[riskCoreFactorNumber];
                // IRiskBookAttributeCurveRiskPositionViewService riskBookAttributeCurveRiskPositionService = (IRiskBookAttributeCurveRiskPositionViewService)ServiceLocator.Get("riskBookAttributeCurveRiskPositionViewService");
                IList<RiskBookAttributeCorePositionView> riskBookAttributePositions = new List<RiskBookAttributeCorePositionView>();
                //tomorrow continue
                if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                {
                    //attribute = SysEnum.Attribute_Portfolio.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForPortfolioWithSpringDao(riskBookID, computeDate);

                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Legal_Entity)
                {
                    //attribute = SysEnum.Attribute_Legal_Entity.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForLegalEntityWithSpringDao(riskBookID, computeDate);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Business_Unit)
                {
                    //attribute = SysEnum.Attribute_Business_Unit.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForBusinessUnitWithSpringDao(riskBookID, computeDate);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                {
                    //attribute = Risk_Group_Type.Risk_Group_Type_Instrument_Type.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForInstrumentTypeWithSpringDao(riskBookID, computeDate);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                {
                    //attribute = SysEnum.Attribute_Counterparty.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForCounterpartyWithSpringDao(riskBookID, computeDate);
                }
                //else if (attributeGroupID == (int)SysEnum.Attribute_Commodity)
                //{
                //    attribute = SysEnum.Attribute_Commodity.GetEnumName();
                //    riskBookAttributePositions = riskBookAttributeCorePositionService.GetListForCommodityWithSpringDao(riskBookID, computeDate);
                //}
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Trader)
                {
                    //attribute = SysEnum.Attribute_Trader.GetEnumName();
                    riskBookAttributePositions = RiskBookAttributeCorePositionService.GetListForTraderWithSpringDao(riskBookID, computeDate);
                }


                if (riskBookAttributePositions != null && riskBookAttributePositions.Count > 0)
                {
                    int k = 0;
                    int activeAttributeID = -999;
                    bool isNotFirstAttributeID = false;

                    #region For Risk Book Attribute Result


                    IList<RskBookAttriResult> riskBookResults = new List<RskBookAttriResult>();
                    IList<RskBookAttriResult> riskBookResultsToDelete = new List<RskBookAttriResult>();

                    int iCount = 0;
                    Framework.QueryInfo info = new Framework.QueryInfo();
                    info.QueryObject = "RskFactorVolatilityData";
                    info.AddParam("ComputeDate", computeDate);
                    info.AddParam("WindowSize", windowSize);
                    var allAttributeList = Holworth.Utility.HraUtility.ListToT<RskFactorVolatilityData>(Dao.FindList(info));
                    foreach (RiskBookAttributeCorePositionView riskBookAttributePosition in riskBookAttributePositions)
                    {

                        attributeID = riskBookAttributePosition.AttributeID;
                        attributeName = riskBookAttributePosition.AttributeName;

                        //changeInMtMValue[i] = (double)riskSimulation.ChangeInMtMValue;
                        //riskFactorID[i] = riskFactorService.GetRiskFactorIDByFactorID(riskFactorPosition.IndexPriceFactorID);
                        riskCoreFactorID[iCount] = riskBookAttributePosition.RiskCoreFactorID;
                        riskPosition[iCount] = (double)riskBookAttributePosition.RiskPosition;
                        riskPositionForIR[iCount] = (double)riskBookAttributePosition.RiskPositionForIR;
                        riskPositionForFX[iCount] = (double)riskBookAttributePosition.RiskPositionForFX;
                        riskPositionForEQ[iCount] = (double)riskBookAttributePosition.RiskPositionForEQ;
                        riskPositionForCOM[iCount] = (double)riskBookAttributePosition.RiskPositionForCOM;
                        var tmpList = (from m in allAttributeList
                                       where m.RiskFactorId == riskCoreFactorID[iCount]
                                       select m).ToList();
                        if (tmpList.Count == 1)
                        {
                            var a = tmpList[0];
                            decimal riskVolatilityValue = a.VolatilityValue;
                            if (riskVolatilityValue < 0)
                                riskVolatilityValue = 0.0001m;
                            riskVolatility[iCount] = System.Convert.ToDouble(riskVolatilityValue);
                        }
                        else
                        {
                            riskVolatility[iCount] = 0.0001;
                        }
                        //  riskVolatility[iCount] = (double)riskVolatilityService.GetValueByDateFactorIDSize(computeDate, riskCoreFactorID[iCount], windowSize);
                        //riskExposure[i] = riskPosition[i] * currentPrice[i] * riskVolatility[i];
                        riskExposure[iCount] = riskPosition[iCount] * riskVolatility[iCount];
                        riskExposureForIR[iCount] = riskPosition[iCount] * riskVolatility[iCount];
                        riskExposureForFX[iCount] = riskPosition[iCount] * riskVolatility[iCount];
                        riskExposureForEQ[iCount] = riskPosition[iCount] * riskVolatility[iCount];
                        riskExposureForCOM[iCount] = riskPosition[iCount] * riskVolatility[iCount];

                        iCount++;

                        if (attributeID != activeAttributeID)
                        {
                            k = 0;

                            if (isNotFirstAttributeID)
                            {
                                riskCoreFactorNumber = iCount;
                                iCount = 0;
                                ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposure, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRisk);
                                ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForIR, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForIR);
                                ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForFX, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForFX);
                                ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForEQ, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForEQ);
                                ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposureForCOM, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRiskForCOM);
                                for (int i = 0; i < resultNumber; i++)
                                {
                                    RskBookAttriResult riskBookResult = new RskBookAttriResult();

                                    //confidenceLevelLookupID[i] = confidenceLevel[i];

                                    riskBookResult.ComputeDate = computeDate;
                                    riskBookResult.RiskBookId = riskBookID;
                                    riskBookResult.RiskGroupType = riskGroupType;
                                    riskBookResult.AttributeId = activeAttributeID;
                                    riskBookResult.SimulationNumber = 0;
                                    riskBookResult.ConfidenceLevelId = confidenceLevelID[i];
                                    riskBookResult.RiskExposure = (decimal)valueAtRisk[i];
                                    riskBookResult.VolatilityRiskExposure = (decimal)valueAtRisk[i];
                                    riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                                    riskBookResult.FxRateRiskExposure = (decimal)valueAtRisk[i];
                                    riskBookResult.Valueatrisk = (decimal)valueAtRisk[i];
                                    riskBookResult.VolatilityRiskExposure = (decimal)valueAtRisk[i];
                                    riskBookResult.InterestRateValueatrisk = (decimal)valueAtRiskForIR[i];
                                    riskBookResult.FxRateRiskExposure = (decimal)valueAtRiskForFX[i];
                                    riskBookResult.IncrementalValueatrisk = (decimal)valueAtRisk[i];
                                    riskBookResult.MarginalValueatrisk = (decimal)valueAtRisk[i];
                                    riskBookResult.ComponentValueatrisk = (decimal)valueAtRisk[i];
                                    riskBookResult.VarLimitLevel = 0;
                                    riskBookResult.VarBreachLevel = 0;
                                    riskBookResult.BreachSeverityLevel = 0;
                                    riskBookResult.MarkToMarketValue = 0;
                                    riskBookResult.ProfitlossValue = 0;
                                    riskBookResult.CreateUname = CurrentUser.UserName;
                                    riskBookResult.CreateDate = DateTime.Now;
                                    riskBookResult.State.MarkNew();
                                    riskBookResults.Add(riskBookResult);
                                }

                            }
                        }

                        activeAttributeID = attributeID;
                        isNotFirstAttributeID = true;

                    }


                    # region For last loop -- to be figured out if it is needed.

                    ComputeValueAtRiskWithRiskExposure(computeDate, riskBookID, riskCoreFactorNumber, riskCoreFactorID, riskExposure, timeHorizon, resultNumber, confidenceLevelID, ref sumOfPortfolioVariance, ref varDelta, ref valueAtRisk);


                    for (int i = 0; i < resultNumber; i++)
                    {
                        RskBookAttriResult riskBookResult = new RskBookAttriResult();

                        //confidenceLevelLookupID[i] = confidenceLevel[i];

                        riskBookResult.ComputeDate = computeDate;
                        riskBookResult.RiskBookId = riskBookID;
                        riskBookResult.RiskGroupType = riskGroupType;
                        riskBookResult.AttributeId = activeAttributeID;
                        riskBookResult.SimulationNumber = 0;
                        riskBookResult.ConfidenceLevelId = confidenceLevelID[i];
                        riskBookResult.RiskExposure = (decimal)valueAtRisk[i];
                        riskBookResult.VolatilityRiskExposure = (decimal)valueAtRisk[i];
                        riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                        riskBookResult.FxRateRiskExposure = (decimal)valueAtRisk[i];
                        riskBookResult.Valueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.VolatilityValueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                        riskBookResult.FxRateValueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.IncrementalValueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.MarginalValueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.ComponentValueatrisk = (decimal)valueAtRisk[i];
                        riskBookResult.VarLimitLevel = 0;
                        riskBookResult.VarBreachLevel = 0;
                        riskBookResult.BreachSeverityLevel = 0;
                        riskBookResult.MarkToMarketValue = 0;
                        riskBookResult.ProfitlossValue = 0;
                        //set up !!!
                        riskBookResult.CreateUname = CurrentUser.UserName;
                        riskBookResult.CreateDate = DateTime.Now;
                        riskBookResult.State.MarkNew();
                        riskBookResults.Add(riskBookResult);
                    }


                    #endregion
                    Dao.GetCurrentSession().Clear();
                    info = new Framework.QueryInfo();
                    info.CustomSQL = "delete from RskBookAttriResult";
                    info.AddParam("ComputeDate", computeDate);
                    info.AddParam("RiskBookId", riskBookID);
                    info.AddParam("SimulationNumber", 0);
                    info.AddParam("RiskGroupType", riskGroupType);
                    Dao.ExecuteUpdate(info);
                    Dao.SaveOrUpdateAll<RskBookAttriResult>(riskBookResults);


                }



                #endregion


            }

            private void ComputeMonteCarloValueAtRiskByAttributeLookup(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType, int timeHorizon, int windowSize, int simulationNumber, int tickNumber, int resultNumber, int[] confidenceLevelID, bool incVaRFlag)
            {




                int attributeID = 0;
                //Risk_Group_Type riskGroupType  = 0;

                //string[] confidenceLevelLookupID = new string[resultNumber];
                //var ConfidenceDic= SysEnumHelper.GetChildEnumByParentCode(Confidence_Level.Confidence_Level.ToString()).Select(x => x.Value.EnumValue).OrderBy(x => x.Value.ToString()).ToList();
                //int j = 0;
                //ConfidenceDic.ForEach(a=> {
                //    confidenceLevel[j++] = a.ToString();
                //});
                //confidenceLevel[0] = ((int)Confidence_Level.Confidence_Level_99_Percent).ToString();
                //confidenceLevel[1] = ((int)Confidence_Level.Confidence_Level_975_Percent).ToString();
                //confidenceLevel[2] = ((int)Confidence_Level.Confidence_Level_95_Percent).ToString();
                //confidenceLevel[3] = ((int)Confidence_Level.Confidence_Level_90_Percent).ToString();
                //confidenceLevel[4] = ((int)Confidence_Level.Confidence_Level_50_Percent).ToString();

                double[] changeInMtMValue = new double[simulationNumber];
                double[] tickValue = new double[tickNumber + 1];
                double[] frequencyValue = new double[tickNumber + 1];
                double[] monteCarloVaR = new double[resultNumber];
                double[] newMonteCarloVaR = new double[resultNumber];
                double[] valueAtRisk = new double[resultNumber];
                double[] incValueAtRisk = new double[resultNumber];

                //  IRiskBookAttributeSimulationViewService riskBookAttributeSimulationService = (IRiskBookAttributeSimulationViewService)ServiceLocator.Get("riskBookAttributeSimulationViewService");

                IList<RiskBookAttributeSimulationView> riskBookAttributeSimulations = new List<RiskBookAttributeSimulationView>();


                if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                {
                    riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListForPortfolioWithSpringDao(riskBookID, computeDate, simulationNumber);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                {
                    riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListForInstrumentTypeWithSpringDao(riskBookID, computeDate, simulationNumber);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                {
                    riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListForCounterpartyWithSpringDao(riskBookID, computeDate, simulationNumber);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Commodity)
                {
                    riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListForCommodityWithSpringDao(riskBookID, computeDate, simulationNumber);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Trader)
                {
                    riskBookAttributeSimulations = riskBookAttributeSimulationService.GetListForTraderWithSpringDao(riskBookID, computeDate, simulationNumber);
                }

                int k = 0;
                int activeAttributeID = -999;
                bool isNotFirstAttributeID = false;

                #region For Risk Book Attribute Result

                //   IRiskBookAttributeResultService riskBookResultService = (IRiskBookAttributeResultService)ServiceLocator.Get("riskBookAttributeResultService");
                IList<RskBookAttriResult> riskBookResults = new List<RskBookAttriResult>();
                IList<RskBookAttriResult> riskBookResultsToDelete = new List<RskBookAttriResult>();

                foreach (RiskBookAttributeSimulationView riskBookAttributeSimulation in riskBookAttributeSimulations)
                {

                    attributeID = riskBookAttributeSimulation.AttributeID;

                    if (attributeID != activeAttributeID)
                    {
                        k = 0;

                        if (isNotFirstAttributeID)
                        {
                            //if (riskModelTypeID == (int)SysEnum.Risk_Model_Type_Monte_Carlo)
                            //{
                            ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref valueAtRisk);
                            //}
                            //else if (riskModelTypeID == (int)SysEnum.Risk_Model_Type_Parametric)
                            //{
                            //  simulationNumber = 0;

                            //  ComputeParametricValueAtRisk(computeDate, riskBookID, resultNumber, confidenceLevel, timeHorizon, windowSize, attributeLookup, attributeID, false, ref valueAtRisk);
                            //}

                            for (int i = 0; i < resultNumber; i++)
                            {
                                RskBookAttriResult riskBookResult = new RskBookAttriResult();

                                //confidenceLevelLookupID[i] = confidenceLevel[i];

                                //confidenceLevelLookupID[i] = confidenceLevel[i];

                                riskBookResult.ComputeDate = computeDate;
                                riskBookResult.RiskBookId = riskBookID;
                                // riskBookResult.attributeGroupID = attributeGroupID;
                                riskBookResult.AttributeId = activeAttributeID;
                                riskBookResult.SimulationNumber = 0;
                                riskBookResult.ConfidenceLevelId = confidenceLevelID[i];
                                riskBookResult.RiskExposure = (decimal)valueAtRisk[i];
                                riskBookResult.VolatilityRiskExposure = (decimal)valueAtRisk[i];
                                riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                                riskBookResult.FxRateRiskExposure = (decimal)valueAtRisk[i];
                                riskBookResult.Valueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.VolatilityValueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                                riskBookResult.FxRateValueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.IncrementalValueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.MarginalValueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.ComponentValueatrisk = (decimal)valueAtRisk[i];
                                riskBookResult.VarLimitLevel = 0;
                                riskBookResult.VarBreachLevel = 0;
                                riskBookResult.BreachSeverityLevel = 0;
                                riskBookResult.MarkToMarketValue = 0;
                                riskBookResult.ProfitlossValue = 0;
                                //set up !!!
                                riskBookResult.CreateUname = CurrentUser.UserName;
                                riskBookResult.CreateDate = DateTime.Now;
                                riskBookResult.State.MarkNew();
                                riskBookResults.Add(riskBookResult);
                            }

                            SaveOrUpdateRiskBookAttributeHistogram(computeDate, riskBookID, simulationNumber, tickNumber, activeAttributeID, riskGroupType, tickValue, frequencyValue);
                        }
                    }

                    activeAttributeID = attributeID;
                    isNotFirstAttributeID = true;

                    //if (riskModelTypeID == (int)(int)SysEnum.Risk_Model_Type_Monte_Carlo)
                    //{

                    changeInMtMValue[k] = (double)riskBookAttributeSimulation.SumOfChangeInMtMValue;
                    k++;

                    //}
                }


                # region For last loop -- to be figured out if it is needed.

                //if (riskModelTypeID == (int)(int)SysEnum.Risk_Model_Type_Monte_Carlo)
                //{
                ComputeValueAtRiskWithSimulationResults(simulationNumber, tickNumber, resultNumber, confidenceLevelID, changeInMtMValue, ref tickValue, ref frequencyValue, ref valueAtRisk);
                //}
                //else if (riskModelTypeID == (int)SysEnum.Risk_Model_Type_Parametric)
                //{
                //  simulationNumber = 0;

                //  ComputeParametricValueAtRisk(computeDate, riskBookID, resultNumber, confidenceLevel, timeHorizon, windowSize, attributeLookup, attributeID, false, ref valueAtRisk);
                //}

                for (int i = 0; i < resultNumber; i++)
                {
                    RskBookAttriResult riskBookResult = new RskBookAttriResult();

                    //confidenceLevelLookupID[i] = confidenceLevel[i];

                    riskBookResult.ComputeDate = computeDate;
                    riskBookResult.RiskBookId = riskBookID;
                    // riskBookResult.attributeGroupID = attributeGroupID;
                    riskBookResult.AttributeId = activeAttributeID;
                    riskBookResult.SimulationNumber = 0;
                    riskBookResult.ConfidenceLevelId = confidenceLevelID[i];
                    riskBookResult.RiskExposure = (decimal)valueAtRisk[i];
                    riskBookResult.VolatilityRiskExposure = (decimal)valueAtRisk[i];
                    riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                    riskBookResult.FxRateRiskExposure = (decimal)valueAtRisk[i];
                    riskBookResult.Valueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.VolatilityValueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.InterestRateRiskExposure = (decimal)valueAtRisk[i];
                    riskBookResult.FxRateValueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.IncrementalValueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.MarginalValueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.ComponentValueatrisk = (decimal)valueAtRisk[i];
                    riskBookResult.VarLimitLevel = 0;
                    riskBookResult.VarBreachLevel = 0;
                    riskBookResult.BreachSeverityLevel = 0;
                    riskBookResult.MarkToMarketValue = 0;
                    riskBookResult.ProfitlossValue = 0;
                    //set up !!!
                    riskBookResult.CreateUname = CurrentUser.UserName;
                    riskBookResult.CreateDate = DateTime.Now;
                    riskBookResult.State.MarkNew();
                    riskBookResults.Add(riskBookResult);
                }

                SaveOrUpdateRiskBookAttributeHistogram(computeDate, riskBookID, simulationNumber, tickNumber, activeAttributeID, riskGroupType, tickValue, frequencyValue);

                #endregion
                Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookAttriResult";
                info.AddParam("ComputeDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("SimulationNumber", 0);
                info.AddParam("AttributeId", riskGroupType);
                Dao.ExecuteUpdate(info);
                Dao.SaveOrUpdateAll<RskBookAttriResult>(riskBookResults);

                ////delete existing dataset first
                //riskBookResultsToDelete = riskBookResultService.GetListByDateNumber(computeDate, riskBookID, riskGroupType, simulationNumber);
                //if (riskBookResultsToDelete != null && riskBookResultsToDelete.Count > 0)
                //{
                //    riskBookResultService.Save(riskBookResultsToDelete, new List<RiskBookAttributeResult>(), new List<RiskBookAttributeResult>());
                //}
                ////then insert the newly computed dataset
                //riskBookResultService.Save(new List<RiskBookAttributeResult>(), new List<RiskBookAttributeResult>(), riskBookResults);

                #endregion


            }

            private void ComputeRiskPositionByAttributeLookup(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType)
            {

                IList<RskBookAttriPosition> riskBookAttributeRiskPositions = new List<RskBookAttriPosition>();
                IList<RiskBookAttributeRiskPositionView> riskBookAttributeRiskPositionsView = new List<RiskBookAttributeRiskPositionView>();





                if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                {
                    riskBookAttributeRiskPositionsView = riskBookAttributeRiskPositionViewService.GetListForPortfolioWithSpringDao(riskBookID, computeDate, riskGroupType);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                {
                    riskBookAttributeRiskPositionsView = riskBookAttributeRiskPositionViewService.GetListForInstrumentTypeWithSpringDao(riskBookID, computeDate, riskGroupType);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                {
                    riskBookAttributeRiskPositionsView = riskBookAttributeRiskPositionViewService.GetListForCounterpartyWithSpringDao(riskBookID, computeDate, riskGroupType);
                }
                //else if (attributeGroupID == (int)SysEnum.Attribute_Commodity)
                //{
                //    attribute = SysEnum.Attribute_Commodity.GetEnumName();
                //    riskBookAttributeRiskPositionsView = riskBookAttributeRiskPositionViewService.GetListForCommodityWithSpringDao(riskBookID, computeDate, riskGroupType);
                //}
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Trader)
                {
                    riskBookAttributeRiskPositionsView = riskBookAttributeRiskPositionViewService.GetListForTraderWithSpringDao(riskBookID, computeDate, riskGroupType);
                }


                #region For Risk Book Attribute Risk Position

                foreach (RiskBookAttributeRiskPositionView riskBookAttributeRiskPositionView in riskBookAttributeRiskPositionsView)
                {
                    RskBookAttriPosition riskBookAttributeRiskPosition = new RskBookAttriPosition();
                    riskBookAttributeRiskPosition.RiskGroupType = riskGroupType;
                    riskBookAttributeRiskPosition.AsOfDate = computeDate;
                    riskBookAttributeRiskPosition.RiskBookId = riskBookID;
                    // riskBookAttributeRiskPosition.attributeGroupID = attributeGroupID;
                    riskBookAttributeRiskPosition.AttributeId = riskBookAttributeRiskPositionView.AttributeID;
                    riskBookAttributeRiskPosition.RiskCoreFactorId = riskBookAttributeRiskPositionView.RiskCoreFactorID;
                    riskBookAttributeRiskPosition.RiskFactorId = riskBookAttributeRiskPositionView.RiskFactorID;
                    riskBookAttributeRiskPosition.IndexPriceFactorId = riskBookAttributeRiskPositionView.IndexPriceFactorID;
                    riskBookAttributeRiskPosition.IndexPriceCurveId = riskBookAttributeRiskPositionView.IndexPriceCurveID;
                    riskBookAttributeRiskPosition.TraderId = riskBookAttributeRiskPositionView.TraderID;
                    riskBookAttributeRiskPosition.WindowSize = riskBookAttributeRiskPositionView.WindowSize;
                    riskBookAttributeRiskPosition.UnitsPerContract = riskBookAttributeRiskPositionView.UnitsPerContract;
                    riskBookAttributeRiskPosition.IndexPriceRateValue = riskBookAttributeRiskPositionView.IndexPriceRateValue;
                    riskBookAttributeRiskPosition.VolatilityValue = riskBookAttributeRiskPositionView.VolatilityValue;
                    riskBookAttributeRiskPosition.DiscountedCashflow = riskBookAttributeRiskPositionView.DiscountedCashflow;
                    riskBookAttributeRiskPosition.RiskPosition = riskBookAttributeRiskPositionView.RiskPosition;
                    riskBookAttributeRiskPosition.VolatilityRiskPosition = riskBookAttributeRiskPositionView.VolRiskPosition;
                    riskBookAttributeRiskPosition.InterestRateRiskPosition = riskBookAttributeRiskPositionView.RiskPositionForIR;
                    riskBookAttributeRiskPosition.FxRateRiskPosition = riskBookAttributeRiskPositionView.RiskPositionForFX;
                    riskBookAttributeRiskPosition.RiskExposure = riskBookAttributeRiskPositionView.RiskExposure;
                    riskBookAttributeRiskPosition.VolatilityRiskExposure = riskBookAttributeRiskPositionView.VolRiskExposure;
                    riskBookAttributeRiskPosition.InterestRateRiskExposure = riskBookAttributeRiskPositionView.RiskExposureForIR;
                    riskBookAttributeRiskPosition.FxRateRiskExposure = riskBookAttributeRiskPositionView.RiskExposureForFX;

                    riskBookAttributeRiskPosition.CreateUname = CurrentUser.UserName;
                    riskBookAttributeRiskPosition.CreateDate = DateTime.Now;
                    riskBookAttributeRiskPosition.State.MarkNew();
                    riskBookAttributeRiskPositions.Add(riskBookAttributeRiskPosition);
                }
                Dao.GetCurrentSession().Clear();
                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookAttriPosition";
                info.AddParam("AsOfDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("RiskGroupType", (int)riskGroupType);
                Dao.ExecuteUpdate(info);
                Dao.SaveOrUpdateAll<RskBookAttriPosition>(riskBookAttributeRiskPositions);



                #endregion


            }

            private void ComputeProfitLossByAttributeLookup(DateTime computeDate, int riskBookID, Risk_Group_Type riskGroupType)
            {

                IList<RskBookAttriProfitloss> riskBookAttributeProfitLossList = new List<RskBookAttriProfitloss>();
                IList<RiskBookAttributeProfitLossView> riskBookAttributeProfitLossesView = new List<RiskBookAttributeProfitLossView>();


                if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Portfolio)
                {
                    riskBookAttributeProfitLossesView = riskBookAttributeProfitLossViewService.GetListForPortfolioWithSpringDao(riskBookID, computeDate);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Instrument_Type)
                {
                    riskBookAttributeProfitLossesView = riskBookAttributeProfitLossViewService.GetListForInstrumentTypeWithSpringDao(riskBookID, computeDate);
                }
                else if (riskGroupType == Risk_Group_Type.Risk_Group_Type_Counterparty)
                {
                    riskBookAttributeProfitLossesView = riskBookAttributeProfitLossViewService.GetListForCounterpartyWithSpringDao(riskBookID, computeDate);
                }
                //else if (attributeGroupID == (int)SysEnum.Attribute_Commodity)
                //{
                //    attribute = SysEnum.Attribute_Commodity.GetEnumName();
                //    riskBookAttributeProfitLossesView = riskBookAttributeProfitLossViewService.GetListForCommodityWithSpringDao(riskBookID, computeDate, riskGroupType);
                //}
                //else if (attributeGroupID == (int)SysEnum.Attribute_Trader)
                //{
                //    attribute = SysEnum.Attribute_Trader.GetEnumName();
                //    riskBookAttributeProfitLossesView = riskBookAttributeProfitLossViewService.GetListForTraderWithSpringDao(riskBookID, computeDate, riskGroupType);
                //}


                #region For Risk Book Attribute Risk Position

                foreach (RiskBookAttributeProfitLossView riskBookAttributeProfitLossView in riskBookAttributeProfitLossesView)
                {
                    RskBookAttriProfitloss riskBookAttributeProfitLoss = new RskBookAttriProfitloss();

                    riskBookAttributeProfitLoss.AsOfDate = computeDate;
                    riskBookAttributeProfitLoss.RiskBookId = riskBookID;
                    riskBookAttributeProfitLoss.RiskGroupType = riskGroupType;
                    // riskBookAttributeProfitLoss.attributeGroupID = attributeGroupID;
                    riskBookAttributeProfitLoss.AttributeId = riskBookAttributeProfitLossView.AttributeID;
                    //riskBookAttributeProfitLoss.TraderId = riskBookAttributeProfitLossView.TraderID;
                    riskBookAttributeProfitLoss.RealizedProfitlossValue = riskBookAttributeProfitLossView.RealizedProfitLossValue; ;
                    riskBookAttributeProfitLoss.UnrealizedProfitlossValue = riskBookAttributeProfitLossView.UnrealizedProfitLossValue;//
                    riskBookAttributeProfitLoss.ProfitlossValue = riskBookAttributeProfitLossView.ProfitLossValue;
                    riskBookAttributeProfitLoss.MarkToMarketValue = riskBookAttributeProfitLossView.MarkToMarketValue;

                    riskBookAttributeProfitLoss.CreateUname = CurrentUser.UserName;
                    riskBookAttributeProfitLoss.CreateDate = DateTime.Now;
                    riskBookAttributeProfitLoss.State.MarkNew();
                    riskBookAttributeProfitLossList.Add(riskBookAttributeProfitLoss);
                }
                Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookAttriProfitloss";
                info.AddParam("AsOfDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("RiskGroupType", (int)riskGroupType);
                Dao.ExecuteUpdate(info);

                Dao.SaveOrUpdateAll(riskBookAttributeProfitLossList);



                #endregion


            }

            private void SaveOrUpdateRiskBookAttributeHistogram(DateTime computeDate, int riskBookID, int simulationNumber, int tickNumber, int attributeID, Risk_Group_Type riskGroupType, double[] tickValue, double[] frequencyValue)
            {
                // IRiskBookAttributeHistogramService riskBookAttributeHistogramService = (IRiskBookAttributeHistogramService)ServiceLocator.Get("riskBookAttributeHistogramService");
                IList<RskBookAttriHistogram> riskBookAttributeHistograms = new List<RskBookAttriHistogram>();
                IList<RskBookAttriHistogram> riskBookAttributeHistogramsToDelete = new List<RskBookAttriHistogram>();

                for (int k = 0; k < tickNumber; k++)
                {
                    RskBookAttriHistogram riskBookAttributeHistogram = new RskBookAttriHistogram();

                    riskBookAttributeHistogram.ComputeDate = computeDate;
                    riskBookAttributeHistogram.RiskBookId = riskBookID;
                    // riskBookAttributeHistogram.attributeGroupID = attributeGroupID;
                    riskBookAttributeHistogram.AttributeId = attributeID;
                    riskBookAttributeHistogram.SimulationNumber = simulationNumber;
                    riskBookAttributeHistogram.TickNumber = tickNumber;
                    riskBookAttributeHistogram.TickId = k;
                    riskBookAttributeHistogram.TickValue = (decimal)tickValue[k];
                    riskBookAttributeHistogram.FrequencyValue = (decimal)frequencyValue[k];
                    riskBookAttributeHistogram.CreateUname = CurrentUser.UserName;
                    riskBookAttributeHistogram.CreateDate = DateTime.Now;
                    riskBookAttributeHistogram.State.MarkNew();
                    riskBookAttributeHistograms.Add(riskBookAttributeHistogram);
                }
                Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = " delete from RskBookAttriHistogram ";
                info.AddParam("ComputeDate", computeDate);
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("AttributeId", attributeID);
                info.AddParam("SimulationNumber", simulationNumber);
                info.AddParam("TickNumber", tickNumber);
                Dao.ExecuteUpdate(info);
                Dao.SaveOrUpdateAll<RskBookAttriHistogram>(riskBookAttributeHistograms);


            }

            private void SaveOrUpdateRiskBookBaseHistogram(DateTime computeDate, int riskBookID, int simulationNumber, int tickNumber, double[] tickValue, double[] frequencyValue)
            {
                //   IRiskBookHistogramService riskBookHistogramService = (IRiskBookHistogramService)ServiceLocator.Get("riskBookHistogramService");
                IList<RskBookHistogram> riskBookHistograms = new List<RskBookHistogram>();
                IList<RskBookHistogram> riskBookHistogramsToDelete = new List<RskBookHistogram>();

                for (int k = 0; k < tickNumber; k++)
                {
                    RskBookHistogram riskBookHistogram = new RskBookHistogram();

                    riskBookHistogram.ComputeDate = computeDate;
                    riskBookHistogram.RiskBookId = riskBookID;
                    riskBookHistogram.SimulationNumber = simulationNumber;
                    riskBookHistogram.TickNumber = tickNumber;
                    riskBookHistogram.TickId = k;
                    riskBookHistogram.TickValue = (decimal)tickValue[k];
                    riskBookHistogram.FrequencyValue = (decimal)frequencyValue[k];
                    riskBookHistogram.CreateUname = CurrentUser.UserName;
                    riskBookHistogram.CreateDate = DateTime.Now;
                    riskBookHistogram.State.MarkNew();
                    riskBookHistograms.Add(riskBookHistogram);
                }
                //delete existing dataset first
                Dao.GetCurrentSession().Clear();

                Framework.QueryInfo info = new Framework.QueryInfo();
                info.CustomSQL = "delete from RskBookHistogram";
                info.AddParam("RiskBookId", riskBookID);
                info.AddParam("SimulationNumber", simulationNumber);
                info.AddParam("ComputeDate", computeDate);
                Dao.ExecuteUpdate(info);
                //then insert the newly computed dataset
                Dao.SaveOrUpdateAll<RskBookHistogram>(riskBookHistograms);
            }

            #endregion

            #region IRiskCalculationEODService Members








            #endregion

        }
    }

  • 相关阅读:
    KVM虚拟机高级设置——09 设置KVM虚拟机开机自动启动
    KVM虚拟机高级设置——08 管理远程虚拟机
    搭建KVM环境——07 带GUI的Linux上安装KVM图形界面管理工具
    搭建KVM环境——06 创建虚拟机
    TightVNC安装
    数据库设计
    Free lunch is over
    【问题】使用XShell连接Debian,没有语法高亮
    【Intel 汇编】ELF文件
    【问题】No manual entry for pthread_create in section 3
  • 原文地址:https://www.cnblogs.com/kexb/p/6533557.html
Copyright © 2020-2023  润新知