public static double GetPremiumImpl( ILogger logger, ICoreCache cache, String nameSpace, SwapLegParametersRange payLegParametersRange, SwapLegParametersRange receiveLegParametersRange, SwaptionParametersRange swaptionTermsRange, ValuationRange valuationRange) { InterestRateStream payStream = null; InterestRateStream receiveStream = null; UpdateCashflowsWithAmounts(logger, cache, nameSpace, payStream, payLegParametersRange, valuationRange); UpdateCashflowsWithAmounts(logger, cache, nameSpace, receiveStream, receiveLegParametersRange, valuationRange); Money fv = CashflowsHelper.GetForecastValue(payStream.cashflows); Money pv = CashflowsHelper.GetPresentValue(payStream.cashflows); double tillExpiry = (swaptionTermsRange.ExpirationDate - valuationRange.ValuationDate).TotalDays / 365.0; //Debug.Print("Future value :{0}", fv.amount); //Debug.Print("Present value :{0}", pv.amount); // get swaption price // double pricePerDollar = BlackModel.GetSwaptionValue((double)payLegParametersRange.CouponOrLastResetRate, (double)swaptionTermsRange.StrikeRate, (double)swaptionTermsRange.Volatility, tillExpiry); double premium = System.Math.Abs((double)payLegParametersRange.NotionalAmount * pricePerDollar); return(premium); }
public void TestGetCapPremiumAUD_6M100M_5YExpiry05Vol20Pct() { var valuationDate = new DateTime(1994, 12, 14); var curveId = BuildAndCacheRateCurve(valuationDate); CapFloorLegParametersRange_Old capLeg = GetCapFloorInputParameters(valuationDate, valuationDate.AddMonths(6), valuationDate.AddYears(5), CapFloorType.Cap, "Standard", curveId, curveId); InterestRateStream floatStream = InterestRateStreamParametricDefinitionGenerator.GenerateStreamDefinition(capLeg); floatStream.cashflows = FixedAndFloatingRateStreamCashflowGenerator.GetCashflows(floatStream, FixingCalendar, PaymentCalendar); double sumOfCapletPremiums = 0; var rateCurve = (RateCurve)Engine.GetCurve(curveId, false); foreach (PaymentCalculationPeriod paymentCalculationPeriod in floatStream.cashflows.paymentCalculationPeriod) { DateTime startDate = PaymentCalculationPeriodHelper.GetCalculationPeriodStartDate(paymentCalculationPeriod); DateTime endDate = PaymentCalculationPeriodHelper.GetCalculationPeriodEndDate(paymentCalculationPeriod); double accrualFactor = (endDate - startDate).TotalDays / 365.0; var discountFactor = (double)paymentCalculationPeriod.discountFactor; var rate = (double)PaymentCalculationPeriodHelper.GetRate(paymentCalculationPeriod); double rate2 = rateCurve.GetForwardRate(startDate, endDate, "ACT/365.FIXED"); double diff = rate - rate2; Debug.Print("Diff in forward rate: {0}", diff); var strikeRate = (double)capLeg.StrikeRate; //fixed - replace with a schedule const double volatility = 0.2; //fixed - replace with a schedule double timeToExpiry = (startDate - valuationDate).TotalDays / 365.0; double optionValue = accrualFactor * BlackModel.GetSwaptionValue(rate, strikeRate, volatility, timeToExpiry) * discountFactor; Debug.Print("Expiry:\t{0},\tPremium:\t{1}'", timeToExpiry, optionValue); sumOfCapletPremiums += optionValue; } Debug.Print("Premium : '{0}'", sumOfCapletPremiums * (double)capLeg.NotionalAmount); }
public CardViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) { this.regionManager = regionManager; this.receive_Aggregator = eventAggregator; this.send_Aggregator = eventAggregator; _achieveModel = AchieveModel.CreateNewModel(); _friendModel = FriendModel.CreateNewModel(); _familyModel = FamilyModel.CreateNewModel(); _blackModel = BlackModel.CreateNewModel(); _resultModel = ResultModel.CreateNewModel(); _msgModel = MsgModel.CreateNewModel(); //获取日志记录实例 this.ilogger = ILogger.GetInstance(); //实例化 achieveList = new List <AchieveViewModel>(); //实例化 msgList = new List <MsgViewModel>(); ChangePage(1, Paging.ACH, this._pagingAchieve); ChangePage(1, Paging.MSG, this._pagingMsg); RequestEvent(); //订阅接收信息事件 }
private static double AdjustCapletImpliedVol(int expiry, double volatility, QuarterlyDiscounts discount, QuarterlyShifts shift) { double strike = RateAnalytics.CashForwardRate(expiry, discount); double capletPrice = BlackModel.GetValue(expiry / 4.0, strike, strike, volatility, PayStyle.Call); double result = BlackModel.GetImpliedVolatility(expiry / 4.0, strike + shift.Get(expiry), strike + shift.Get(expiry), capletPrice, volatility, PayStyle.Call); return(result); }
private static double AdjustSwaptionImpliedVol(int expiry, int tenor, double volatility, QuarterlyDiscounts discount, QuarterlyShifts shift) { double strike = RateAnalytics.SwapRate(expiry, tenor, discount); double swapShift = RateAnalytics.SwapShift(expiry, tenor, discount, shift); double swaptionPrice = BlackModel.GetValue(expiry / 4.0, strike, strike, volatility, PayStyle.Call); double result = BlackModel.GetImpliedVolatility(expiry / 4.0, strike + swapShift, strike + swapShift, swaptionPrice, volatility, PayStyle.Call); return(result); }
/// <summary> /// Constructor for the Cox-Ingersoll-Ross Calibration Problem based on caps matrices, /// using an <see cref="InterestRateMarketData"/> to derive the required data. /// </summary> /// <param name="irmd"> /// An <see cref="InterestRateMarketData"/> containing the /// required information for the optimization problem. /// </param> public CapCIROptimizationProblem(InterestRateMarketData irmd) { this.capMaturity = irmd.CapMaturity; this.capRate = irmd.CapRate; this.tau = irmd.CapTenor; PFunction zr = new PFunction(null); zr.m_Function.iType = DVPLUtils.EInterpolationType.LINEAR; double[,] zrval = (double[, ])ArrayHelper.Concat(irmd.ZRMarketDates.ToArray(), irmd.ZRMarket.ToArray()); zr.Expr = zrval; this.r0 = zr.Evaluate(0.0); BlackModel bm = new BlackModel(zr); this.blackCaps = new Matrix(this.capMaturity.Length, this.capRate.Length); for (int i = 0; i < this.capMaturity.Length; i++) { for (int j = 0; j < this.capRate.Length; j++) { if (irmd.CapVolatility[i, j] == 0) { this.blackCaps[i, j] = 0; } else { this.blackCaps[i, j] = bm.Cap(this.capRate[j], irmd.CapVolatility[i, j], this.tau, this.capMaturity[i]); } if (double.IsNaN(this.blackCaps[i, j])) { throw new Exception("Error on cap market price calculation"); } } } }
///<summary> /// Gets the caplet value. ///</summary> ///<param name="floatRate">The floating rate.</param> ///<param name="strikeRate">The strike rate.</param> ///<param name="volatility">The lognormal volatility.</param> ///<param name="timeToExpiry">The time to expiry.</param> ///<returns>The caplet value using BSM.</returns> public double GetCapletValue(double floatRate, double strikeRate, double volatility, double timeToExpiry) { return(BlackModel.GetCapletValue(floatRate, strikeRate, volatility, timeToExpiry)); }
/// <summary> /// Attempts a calibration through <see cref="CapsHW1OptimizationProblem"/> /// using caps matrices. /// </summary> /// <param name="data">The data to be used in order to perform the calibration.</param> /// <param name="settings">The parameter is not used.</param> /// <param name="controller">The controller which may be used to cancel the process.</param> /// <returns>The results of the calibration.</returns> public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null) { InterestRateMarketData dataset = data[0] as InterestRateMarketData; PFunction zr = new PFunction(null); zr.VarName = "zr"; var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering; // Loads ZR double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray()); zr.Expr = zrvalue; BlackModel bm = new BlackModel(zr); double deltak = dataset.CapTenor; if (dataset.CapVolatility == null) return new EstimationResult("Cap not available at requested date"); Matrix capVolatility = dataset.CapVolatility; Vector capMaturity = dataset.CapMaturity; Vector capRate = dataset.CapRate; double a = 0.1; double sigma = 0.1; // Matrix calculated with Black. Matrix blackCaps = new Matrix(capMaturity.Length, capRate.Length); Matrix logic = new Matrix(capMaturity.Length, capRate.Length); for (int m = 0; m < capMaturity.Length; m++) { for (int s = 0; s < capRate.Length; s++) { blackCaps[m, s] = bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]); if (double.IsNaN(blackCaps[m, s])) { bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]); throw new Exception("Malformed black caps"); } if (blackCaps[m, s] == 0.0) { logic[m, s] = 0.0; } else { logic[m, s] = 1.0; } //filter if (preferences != null) { if (capRate[s] < preferences.MinCapRate || capRate[s] > preferences.MaxCapRate || capMaturity[m]<preferences.MinCapMaturity|| capMaturity[m]>preferences.MaxCapMaturity) {logic[m, s] = 0; blackCaps[m, s] = 0;} } } } DateTime t0 = DateTime.Now; CapHW1 hw1Caps = new CapHW1(zr); Matrix caps = hw1Caps.HWMatrixCaps(capMaturity, capRate, a, sigma, deltak); for (int m = 0; m < capMaturity.Length; m++) { for (int s = 0; s < capRate.Length; s++) { caps[m, s] = logic[m, s] * caps[m, s]; } } CapsHW1OptimizationProblem problem = new CapsHW1OptimizationProblem(hw1Caps, blackCaps, capMaturity, capRate, deltak); Vector provaparam = new Vector(2); var solver = new QADE(); IOptimizationAlgorithm solver2 = new SteepestDescent(); DESettings o = new DESettings(); o.NP = 20; o.MaxIter = 10; o.Verbosity = 1; o.Parallel = false; SolutionInfo solution = null; Vector x0 = new Vector(new double[] { 0.05, 0.01 }); o.controller = controller; solution = solver.Minimize(problem, o, x0); o.epsilon = 10e-8; o.h = 10e-8; o.MaxIter = 100; solution = solver2.Minimize(problem, o, solution.x); if (solution.errors) return new EstimationResult(solution.message); Console.WriteLine("Solution:"); Console.WriteLine(solution); string[] names = new string[] { "Alpha", "Sigma" }; //solution.x[0] *= 3; EstimationResult result = new EstimationResult(names, solution.x); result.ZRX = (double[])dataset.ZRMarketDates.ToArray(); result.ZRY = (double[])dataset.ZRMarket.ToArray(); return result; }
/// <summary> /// Attempts a calibration through <see cref="CapsHW1OptimizationProblem"/> /// using caps matrices. /// </summary> /// <param name="data">The data to be used in order to perform the calibration.</param> /// <param name="settings">The parameter is not used.</param> /// <param name="controller">The controller which may be used to cancel the process.</param> /// <returns>The results of the calibration.</returns> public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null) { InterestRateMarketData dataset = data[0] as InterestRateMarketData; PFunction zr = new PFunction(null); zr.VarName = "zr"; var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering; // Loads ZR double[,] zrvalue = (double[, ])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray()); zr.Expr = zrvalue; BlackModel bm = new BlackModel(zr); double deltak = dataset.CapTenor; if (dataset.CapVolatility == null) { return(new EstimationResult("Cap not available at requested date")); } Matrix capVolatility = dataset.CapVolatility; Vector capMaturity = dataset.CapMaturity; Vector capRate = dataset.CapRate; double a = 0.1; double sigma = 0.1; // Matrix calculated with Black. Matrix blackCaps = new Matrix(capMaturity.Length, capRate.Length); Matrix logic = new Matrix(capMaturity.Length, capRate.Length); for (int m = 0; m < capMaturity.Length; m++) { for (int s = 0; s < capRate.Length; s++) { blackCaps[m, s] = bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]); if (double.IsNaN(blackCaps[m, s])) { bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]); throw new Exception("Malformed black caps"); } if (blackCaps[m, s] == 0.0) { logic[m, s] = 0.0; } else { logic[m, s] = 1.0; } //filter if (preferences != null) { if (capRate[s] < preferences.MinCapRate || capRate[s] > preferences.MaxCapRate || capMaturity[m] < preferences.MinCapMaturity || capMaturity[m] > preferences.MaxCapMaturity) { logic[m, s] = 0; blackCaps[m, s] = 0; } } } } DateTime t0 = DateTime.Now; CapHW1 hw1Caps = new CapHW1(zr); Matrix caps = hw1Caps.HWMatrixCaps(capMaturity, capRate, a, sigma, deltak); for (int m = 0; m < capMaturity.Length; m++) { for (int s = 0; s < capRate.Length; s++) { caps[m, s] = logic[m, s] * caps[m, s]; } } CapsHW1OptimizationProblem problem = new CapsHW1OptimizationProblem(hw1Caps, blackCaps, capMaturity, capRate, deltak); Vector provaparam = new Vector(2); var solver = new QADE(); IOptimizationAlgorithm solver2 = new SteepestDescent(); DESettings o = new DESettings(); o.NP = 20; o.MaxIter = 10; o.Verbosity = 1; o.Parallel = false; SolutionInfo solution = null; Vector x0 = new Vector(new double[] { 0.05, 0.01 }); o.controller = controller; solution = solver.Minimize(problem, o, x0); o.epsilon = 10e-8; o.h = 10e-8; o.MaxIter = 100; solution = solver2.Minimize(problem, o, solution.x); if (solution.errors) { return(new EstimationResult(solution.message)); } Console.WriteLine("Solution:"); Console.WriteLine(solution); string[] names = new string[] { "Alpha", "Sigma" }; //solution.x[0] *= 3; EstimationResult result = new EstimationResult(names, solution.x); result.ZRX = (double[])dataset.ZRMarketDates.ToArray(); result.ZRY = (double[])dataset.ZRMarket.ToArray(); return(result); }
public BlackViewModel(BlackModel blackModel) { _blackModel = blackModel; }
/// <summary> /// Attempts a calibration through <see cref="PelsserCappletOptimizationProblem"/> /// using caps matrices. /// </summary> /// <param name="data">The data to be used in order to perform the calibration.</param> /// <param name="settings">The parameter is not used.</param> /// <param name="controller">The controller which may be used to cancel the process.</param> /// <returns>The results of the calibration.</returns> public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null) { InterestRateMarketData dataset = data[0] as InterestRateMarketData; EstimationResult result; if ((dataset.ZRMarket == null) || (dataset.CapVolatility == null)) { result = new EstimationResult(); result.ErrorMessage = "Not enough data to calibrate.\n" + "The estimator needs a ZRMarket and a CapVolatility " + "defined inside InterestRateMarketData"; return result; } // Backup the dates DateTime effectiveDate = DateTime.Now.Date; DateTime valuationDate = DateTime.Now.Date; if (Document.ActiveDocument != null) { effectiveDate = Document.ActiveDocument.ContractDate; valuationDate = Document.ActiveDocument.SimulationStartDate; } // Creates the Context. Document doc = new Document(); ProjectROV prj = new ProjectROV(doc); doc.Part.Add(prj); Function zr = new PFunction(null); zr.VarName = "zr"; // Load the zr. double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray()); zr.Expr = zrvalue; prj.Symbols.Add(zr); BlackModel bm = new BlackModel(zr); double deltak = dataset.CapTenor; Matrix capVol = dataset.CapVolatility; Vector capMat = dataset.CapMaturity; Vector capK = dataset.CapRate; var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering; // Matrix calculated with black. Matrix blackCaps = new Matrix(capMat.Length, capK.Length); for (int m = 0; m < capMat.Length; m++) { for (int s = 0; s < capK.Length; s++) { bool skip = false; if (preferences != null) { if (capK[s] < preferences.MinCapRate || capK[s] > preferences.MaxCapRate || capMat[m] < preferences.MinCapMaturity || capMat[m] > preferences.MaxCapMaturity) {skip = true; } } if (capVol[m, s] == 0 || skip) blackCaps[m, s] = 0; else blackCaps[m, s] = bm.Cap(capK[s], capVol[m, s], deltak, capMat[m]); } } if (blackCaps.IsNAN()) { Console.WriteLine("Black caps matrix has non real values:"); Console.WriteLine(blackCaps); throw new Exception("Cannot calculate Black caps"); } // Maturity goes from 0 to the last item with step deltaK. Vector maturity = new Vector((int)(1.0 + capMat[capMat.Length - 1] / deltak)); for (int l = 0; l < maturity.Length; l++) maturity[l] = deltak * l; Vector fwd = new Vector(maturity.Length - 1); for (int i = 0; i < fwd.Length; i++) { fwd[i] = bm.Fk(maturity[i + 1], deltak); } // Creates a default Pelsser model. Pelsser.SquaredGaussianModel model = new Pelsser.SquaredGaussianModel(); model.a1 = (ModelParameter)0.014; model.sigma1 = (ModelParameter)0.001; model.zr = (ModelParameter)"@zr"; StochasticProcessExtendible iex = new StochasticProcessExtendible(prj, model); prj.Processes.AddProcess(iex); prj.Parse(); DateTime t0 = DateTime.Now; Caplet cp = new Caplet(); PelsserCappletOptimizationProblem problem = new PelsserCappletOptimizationProblem(prj, cp, maturity, fwd, capK, deltak, capMat, blackCaps); IOptimizationAlgorithm solver = new QADE(); IOptimizationAlgorithm solver2 = new SteepestDescent(); DESettings o = new DESettings(); o.NP = 35; o.TargetCost = 0.0025; o.MaxIter = 10; o.Verbosity = Math.Max(1, Engine.Verbose); o.controller = controller; // Parallel evaluation is not supported for this calibration. o.Parallel = false; o.Debug = true; SolutionInfo solution = null; Vector x0 = (Vector)new double[] { 0.1, 0.1 }; solution = solver.Minimize(problem, o, x0); if (solution.errors) return new EstimationResult(solution.message); o.epsilon = 10e-7; o.h = 10e-7; o.MaxIter = 1000; o.Debug = true; o.Verbosity = Math.Max(1, Engine.Verbose); if (solution != null) solution = solver2.Minimize(problem, o, solution.x); else solution = solver2.Minimize(problem, o, x0); if (solution.errors) return new EstimationResult(solution.message); Console.WriteLine(solution); string[] names = new string[] { "alpha1", "sigma1" }; result = new EstimationResult(names, solution.x); result.ZRX = (double[])dataset.ZRMarketDates.ToArray(); result.ZRY = (double[])dataset.ZRMarket.ToArray(); result.Objects = new object[1]; result.Objects[0] = solution.obj; //result.Fit = solution.obj;//Uncomment in 1.6 // Restore the dates if (Document.ActiveDocument != null) { Document.ActiveDocument.ContractDate = effectiveDate; Document.ActiveDocument.SimulationStartDate = valuationDate; } return result; }
/// <summary> /// Constructor for the Cox-Ingersoll-Ross Calibration Problem based on caps matrices, /// using an <see cref="InterestRateMarketData"/> to derive the required data. /// </summary> /// <param name="irmd"> /// An <see cref="InterestRateMarketData"/> containing the /// required information for the optimization problem. /// </param> public CapCIROptimizationProblem(InterestRateMarketData irmd) { this.capMaturity = irmd.CapMaturity; this.capRate = irmd.CapRate; this.tau = irmd.CapTenor; PFunction zr = new PFunction(null); zr.m_Function.iType = DVPLUtils.EInterpolationType.LINEAR; double[,] zrval = (double[,])ArrayHelper.Concat(irmd.ZRMarketDates.ToArray(), irmd.ZRMarket.ToArray()); zr.Expr = zrval; this.r0 = zr.Evaluate(0.0); BlackModel bm = new BlackModel(zr); this.blackCaps = new Matrix(this.capMaturity.Length, this.capRate.Length); for (int i = 0; i < this.capMaturity.Length; i++) { for (int j = 0; j < this.capRate.Length; j++) { if (irmd.CapVolatility[i, j] == 0) this.blackCaps[i, j] = 0; else this.blackCaps[i, j] = bm.Cap(this.capRate[j], irmd.CapVolatility[i, j], this.tau, this.capMaturity[i]); if (double.IsNaN(this.blackCaps[i, j])) throw new Exception("Error on cap market price calculation"); } } }
public void OnReceiveMsg(ReceiveMsgOrder receiveMsgOrder) { string[] msg = null; if (receiveMsgOrder.MsgContent.IndexOf(MessageTypes.NSP) > -1) { msg = receiveMsgOrder.MsgContent.Split(MessageTypes.NSP.ToCharArray()); } // ilogger.Logger(string.Format("接收到的数据:{0}-{1}", receiveMsgOrder.ModuleType, receiveMsgOrder.MsgContent)); if (receiveMsgOrder.Sign == 0) { XWT.MessageBox.Show(receiveMsgOrder.MsgContent, "提示", MessageBoxButton.OK, MessageBoxImage.Information); return; } switch (receiveMsgOrder.ModuleType) { #region 返回个人信息_PER case MessageTypes.PER: this.UserID = msg[0]; this.CardWord = msg[1]; this.UserName = msg[2]; this.ImgSrc = msg[3]; //存储用户信息 this.regionManager.Regions[RegionTypes.CardRegion].Context = msg; break; #endregion #region 返回游戏成就_ACH case MessageTypes.ACH: //更新 foreach (AchieveViewModel viewmodel in achieveList) { if (viewmodel.GameName == msg[0]) { viewmodel.Level = msg[1]; viewmodel.Rank = msg[2]; viewmodel.Total = msg[3]; viewmodel.Single = msg[4]; return; } } //添加 _achieveModel = AchieveModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[4]); achieveList.Add(new AchieveViewModel(_achieveModel)); //this.AllAchieves.Add(new AchieveViewModel(_achieveModel)); this.Achieve++; ChangePage(this._pagingAchieve.CurrentPage == 0 ? 1 : this._pagingAchieve.CurrentPage, Paging.ACH, this._pagingAchieve); break; #endregion #region 返回消息_MSG case MessageTypes.MSG: string msginfo = msg[0] + "," + GetString.GetRandomCode(GetString.Code.StrAndNum, 4); _msgModel = MsgModel.CreateModel(msginfo, msg[0], msg[1], msg[2], msg[3]); msgList.Add(new MsgViewModel(_msgModel)); this.Message++; ChangePage(this._pagingMsg.CurrentPage == 0 ? 1 : this._pagingMsg.CurrentPage, Paging.MSG, this._pagingMsg); break; #endregion #region 修改密码返回的信息_SET case MessageTypes.SET: this.PassWord = ""; this.NewPassWord = ""; this.ConPassWord = ""; XWT.MessageBox.Show(receiveMsgOrder.MsgContent, "提示", MessageBoxButton.OK, MessageBoxImage.Information); break; #endregion #region 返回好友信息_FRI case MessageTypes.FRI: switch (msg[5]) { case MessageTypes.Friend: _friendModel = FriendModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[5], msg[4] == MessageTypes.N ? true : false, msg[4] == MessageTypes.N ? false : true); this.AllFriends.Add(new FriendViewModel(_friendModel)); this.Friend++; break; case MessageTypes.Family: _familyModel = FamilyModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[5], msg[4] == MessageTypes.N ? true : false, msg[4] == MessageTypes.N ? false : true); this.AllFamilys.Add(new FamilyViewModel(_familyModel)); this.Friend++; break; case MessageTypes.Black: _blackModel = BlackModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[5], msg[4] == MessageTypes.N ? true : false, false); this.AllBlacks.Add(new BlackViewModel(_blackModel)); this.Friend++; break; } break; #endregion #region 返回查找好友结果_SFR case MessageTypes.SFR: _resultModel = ResultModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[1] == this.CardWord ? false : true, msg[4] == MessageTypes.N ? true : false); this.AllResults.Add(new ResultViewModel(_resultModel)); break; #endregion #region 好友上线通知_UPL case MessageTypes.UPL: foreach (FriendViewModel friend in this.AllFriends.Where(f => f.FriendID == receiveMsgOrder.MsgContent)) { friend.FriendStatus = false; friend.MenuIsEnabled = true; } foreach (FamilyViewModel family in this.AllFamilys.Where(f => f.FriendID == receiveMsgOrder.MsgContent)) { family.FriendStatus = false; family.MenuIsEnabled = true; } break; #endregion #region 好友下线通知_OFF case MessageTypes.OFF: foreach (FriendViewModel friend in this.AllFriends.Where(f => f.FriendID == receiveMsgOrder.MsgContent)) { friend.FriendStatus = true; friend.MenuIsEnabled = false; } foreach (FamilyViewModel family in this.AllFamilys.Where(f => f.FriendID == receiveMsgOrder.MsgContent)) { family.FriendStatus = true; family.MenuIsEnabled = false; } break; #endregion #region 询问好友添加请求_ASK case MessageTypes.ASK: string msginfo1 = MessageTypes.F + "," + GetString.GetRandomCode(GetString.Code.StrAndNum, 4) + "," + msg[0]; _msgModel = MsgModel.CreateModel(msginfo1, MessageTypes.F, "请求添加您为好友.", "", msg[1]); msgList.Add(new MsgViewModel(_msgModel)); this.Message++; ChangePage(this._pagingMsg.CurrentPage == 0 ? 1 : this._pagingMsg.CurrentPage, Paging.MSG, this._pagingMsg); break; #endregion #region 返回查找好友资料进行添加_AGR case MessageTypes.AGR: //添加信息提示 string msginfo2 = MessageTypes.T + "," + GetString.GetRandomCode(GetString.Code.StrAndNum, 4); _msgModel = MsgModel.CreateModel(msginfo2, MessageTypes.T, "对方同意您的添加请求.", "", msg[1]); msgList.Add(new MsgViewModel(_msgModel)); this.Message++; ChangePage(this._pagingMsg.CurrentPage == 0 ? 1 : this._pagingMsg.CurrentPage, Paging.MSG, this._pagingMsg); //添加好友 _friendModel = FriendModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[5], msg[4] == MessageTypes.N ? true : false, msg[4] == MessageTypes.N ? false : true); this.AllFriends.Add(new FriendViewModel(_friendModel)); this.Friend++; //添加信息提示 string msginfo3 = MessageTypes.T + "," + GetString.GetRandomCode(GetString.Code.StrAndNum, 4); _msgModel = MsgModel.CreateModel(msginfo3, MessageTypes.T, "新的好友添加成功.", "", "系统"); msgList.Add(new MsgViewModel(_msgModel)); this.Message++; ChangePage(this._pagingMsg.CurrentPage == 0 ? 1 : this._pagingMsg.CurrentPage, Paging.MSG, this._pagingMsg); break; #endregion #region 返回查找好友资料进行添加_AFR case MessageTypes.AFR: //添加好友信息 _friendModel = FriendModel.CreateModel(msg[0], msg[1], msg[2], msg[3], msg[5], msg[4] == MessageTypes.N ? true : false, msg[4] == MessageTypes.N ? false : true); this.AllFriends.Add(new FriendViewModel(_friendModel)); this.Friend++; //添加信息提示 string msginfo4 = MessageTypes.T + "," + GetString.GetRandomCode(GetString.Code.StrAndNum, 4); _msgModel = MsgModel.CreateModel(msginfo4, MessageTypes.T, "新的好友添加成功.", "", "系统"); msgList.Add(new MsgViewModel(_msgModel)); this.Message++; ChangePage(this._pagingMsg.CurrentPage == 0 ? 1 : this._pagingMsg.CurrentPage, Paging.MSG, this._pagingMsg); break; #endregion #region 对方将自己删除,此处也将对方删除_DFR case MessageTypes.DFR: foreach (FriendViewModel friend in this.AllFriends) { if (friend.FriendID == receiveMsgOrder.MsgContent) { this.AllFriends.Remove(friend); break; } } if (this.Friend > 0) { this.Friend--; } break; #endregion #region 返回移动好友结果,本地进行移动_MFR case MessageTypes.MFR: switch (msg[1]) { #region 该好友原来在“我的好友”组 case MessageTypes.Friend: foreach (FriendViewModel friend in this.AllFriends) { if (friend.FriendID == msg[0]) { //从该组移除 this.AllFriends.Remove(friend); switch (msg[2]) { //现移动到“我的家族” case MessageTypes.Family: _familyModel = FamilyModel.CreateModel(friend.FriendID, friend.FriendCard, friend.FriendName, friend.FriendImg, MessageTypes.Family, friend.FriendStatus, friend.MenuIsEnabled); this.AllFamilys.Add(new FamilyViewModel(_familyModel)); break; //现移动到“黑名单” case MessageTypes.Black: _blackModel = BlackModel.CreateModel(friend.FriendID, friend.FriendCard, friend.FriendName, friend.FriendImg, MessageTypes.Black, friend.FriendStatus, false); this.AllBlacks.Add(new BlackViewModel(_blackModel)); break; } break; } } break; #endregion #region 该好友原来在“我的家族”组 case MessageTypes.Family: foreach (FamilyViewModel family in this.AllFamilys) { if (family.FriendID == msg[0]) { //从该组移除 this.AllFamilys.Remove(family); switch (msg[2]) { //现移动到“我的好友” case MessageTypes.Friend: _friendModel = FriendModel.CreateModel(family.FriendID, family.FriendCard, family.FriendName, family.FriendImg, MessageTypes.Friend, family.FriendStatus, family.MenuIsEnabled); this.AllFriends.Add(new FriendViewModel(_friendModel)); break; //现移动到“黑名单” case MessageTypes.Black: _blackModel = BlackModel.CreateModel(family.FriendID, family.FriendCard, family.FriendName, family.FriendImg, MessageTypes.Black, family.FriendStatus, false); this.AllBlacks.Add(new BlackViewModel(_blackModel)); break; } break; } } break; #endregion #region 该好友原来在“黑名单”组 case MessageTypes.Black: foreach (BlackViewModel black in this.AllBlacks) { if (black.FriendID == msg[0]) { //从该组移除 this.AllBlacks.Remove(black); switch (msg[2]) { //现移动到“我的好友” case MessageTypes.Friend: _friendModel = FriendModel.CreateModel(black.FriendID, black.FriendCard, black.FriendName, black.FriendImg, MessageTypes.Friend, black.FriendStatus, !black.FriendStatus); this.AllFriends.Add(new FriendViewModel(_friendModel)); break; //现移动到“我的家族” case MessageTypes.Family: _familyModel = FamilyModel.CreateModel(black.FriendID, black.FriendCard, black.FriendName, black.FriendImg, MessageTypes.Friend, black.FriendStatus, !black.FriendStatus); this.AllFamilys.Add(new FamilyViewModel(_familyModel)); break; } break; } } break; #endregion } break; #endregion } //MessageBox.Show(receiveMsgOrder.MsgContent); //ReceiveMsgEvent msgEvent = receive_Aggregator.GetEvent<ReceiveMsgEvent>(); //if (subscriptionToken != null) // msgEvent.Unsubscribe(subscriptionToken); }