Esempio n. 1
0
 private static void CalculateForecastPaymentAmount(PrincipalExchange principleExchange,
                                                    IRateCurve discountCurve,
                                                    DateTime valuationDate)
 {
     principleExchange.discountFactor                      = (decimal)discountCurve.GetDiscountFactor(valuationDate, principleExchange.adjustedPrincipalExchangeDate);
     principleExchange.discountFactorSpecified             = true;
     principleExchange.presentValuePrincipalExchangeAmount = MoneyHelper.Mul(MoneyHelper.GetAmount(principleExchange.principalExchangeAmount), principleExchange.discountFactor);
 }
        //private static void ProcessStubs(InterestRateStream stream, SwapLegParametersRange_Old swapTermParametersRange, IBusinessCalendar paymentCalendar)
        //{
        //    //bool isFullFirstCoupon = swapTermParametersRange.FirstCouponType == FirstCouponType.Full?true:false;
        //    DateTime adjustedEffectiveDate = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, XsdClassesFieldResolver.CalculationPeriodDates_GetEffectiveDate(stream.calculationPeriodDates));
        //    DateTime adjustedTerminationDate = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, XsdClassesFieldResolver.CalculationPeriodDates_GetTerminationDate(stream.calculationPeriodDates));
        //    StubPeriodTypeEnum? initialStubType = null;
        //    if (!string.IsNullOrEmpty(swapTermParametersRange.InitialStubType))
        //    {
        //        initialStubType = EnumHelper.Parse<StubPeriodTypeEnum>(swapTermParametersRange.InitialStubType);
        //    }
        //    StubPeriodTypeEnum? finalStubType = null;
        //    if (!string.IsNullOrEmpty(swapTermParametersRange.FinalStubType))
        //    {
        //        finalStubType = EnumHelper.Parse<StubPeriodTypeEnum>(swapTermParametersRange.FinalStubType);
        //    }
        //    //Only calculate a stub if required i.e.
        //    //If a FirsteRegularPeriod is specified -> Roll forward
        //    //If a lastRegularePeriod is specified --> Roll Backwards
        //    //If intialstub is not null
        //    //if finalStubType is not null
        //    //Otherwise, check if the maturity - effective date is modulo the frequency.
        //    //If yes, there is no stub.
        //    var periods = CalculationPeriodGenerator.GenerateAdjustedCalculationPeriods(adjustedEffectiveDate,
        //                                                                                adjustedTerminationDate,
        //                                                                                swapTermParametersRange.FirstRegularPeriodStartDate,
        //                                                                                stream.calculationPeriodDates.calculationPeriodFrequency,
        //                                                                                stream.calculationPeriodDates.calculationPeriodDatesAdjustments,
        //                                                                                initialStubType,
        //                                                                                finalStubType,
        //                                                                                paymentCalendar);
        //    //var periods = CalculationPeriodGenerator.GenerateAdjustedCalculationPeriods(adjustedEffectiveDate,
        //    //                                                                            adjustedTerminationDate,
        //    //                                                                            stream.calculationPeriodDates.firstRegularPeriodStartDate,
        //    //                                                                            stream.calculationPeriodDates.lastRegularPeriodEndDate,
        //    //                                                                            stream.calculationPeriodDates.calculationPeriodFrequency,
        //    //                                                                            stream.calculationPeriodDates.calculationPeriodDatesAdjustments,
        //    //                                                                            paymentCalendar);
        //    if (!stream.calculationPeriodDates.firstRegularPeriodStartDateSpecified && periods.HasInitialStub)
        //    {
        //        stream.calculationPeriodDates.firstRegularPeriodStartDate = periods.FirstRegularPeriodUnadjustedStartDate;
        //        stream.calculationPeriodDates.firstRegularPeriodStartDateSpecified = true;
        //    }
        //    if (!stream.calculationPeriodDates.lastRegularPeriodEndDateSpecified && periods.HasFinalStub)
        //    {
        //        stream.calculationPeriodDates.lastRegularPeriodEndDate = periods.LastRegularPeriodUnadjustedEndDate;
        //        stream.calculationPeriodDates.lastRegularPeriodEndDateSpecified = true;
        //    }
        //}

        private static void SetNotional(Calculation calculation,
                                        decimal amount,
                                        string currencyAsString)
        {
            Money    notionalAsMoney  = MoneyHelper.GetAmount(amount, currencyAsString);
            Notional notionalSchedule = NotionalFactory.Create(notionalAsMoney);

            XsdClassesFieldResolver.CalculationSetNotionalSchedule(calculation, notionalSchedule);
        }
Esempio n. 3
0
 protected PriceableCashflow()
 {
     Multiplier                    = 1.0m;
     PaymentAmount                 = MoneyHelper.GetAmount(0.0m);
     ForecastAmount                = MoneyHelper.GetAmount(0.0m);
     PaymentType                   = PaymentTypeHelper.Create("Certain");
     ModelIdentifier               = "DiscountedCashflow";
     PaymentDateIncluded           = false;
     PricingStructureEvolutionType = PricingStructureEvolutionType.ForwardToSpot;
 }
Esempio n. 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PriceableSimpleIRSwap"/> class.
 /// </summary>
 /// <param name="amount">The amount.</param>
 /// <param name="discountingType">The discounting type.</param>
 /// <param name="effectiveDate">The base date.</param>
 /// <param name="tenor">The maturity tenor.</param>
 /// <param name="fxdDayFraction">The fixed leg day fraction.</param>
 /// <param name="businessCenters">The payment business centers.</param>
 /// <param name="businessDayConvention">The payment business day convention.</param>
 /// <param name="fxdFrequency">The business day adjustments.</param>
 /// <param name="underlyingRateIndex">Index of the rate.</param>
 /// <param name="fixedRate">The fixed rate.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="baseDate">The base date.</param>
 /// <param name="currency">THe currency.</param>
 /// <param name="fixingCalendar">The fixingCalendar.</param>
 /// <param name="paymentCalendar">The paymentCalendar.</param>
 public PriceableSimpleIRSwap(string id, DateTime baseDate, string currency,
                              decimal amount, DiscountingTypeEnum?discountingType,
                              DateTime effectiveDate, string tenor, string fxdDayFraction,
                              string businessCenters, string businessDayConvention, string fxdFrequency,
                              RateIndex underlyingRateIndex, IBusinessCalendar fixingCalendar, IBusinessCalendar paymentCalendar, BasicQuotation fixedRate)
     : this(baseDate, SimpleIrsHelper.Parse(id, currency, fxdDayFraction, tenor, fxdFrequency, id), effectiveDate,
            CalculationFactory.CreateFixed(fixedRate.value, MoneyHelper.GetAmount(amount, currency),
                                           DayCountFractionHelper.Parse(fxdDayFraction), discountingType),
            BusinessDayAdjustmentsHelper.Create(businessDayConvention, businessCenters), underlyingRateIndex, fixingCalendar, paymentCalendar, fixedRate)
 {
 }
Esempio n. 5
0
        public static Trade CreateFraTrade(FraInputRange2 fraInputRange)
        {
            var trade = new Trade();
            var fra   = new Fra
            {
                adjustedEffectiveDate =
                    DateTypesHelper.ToRequiredIdentifierDate(fraInputRange.AdjustedEffectiveDate),
                adjustedTerminationDate          = fraInputRange.AdjustedTerminationDate,
                adjustedTerminationDateSpecified = true,
                paymentDate =
                    DateTypesHelper.ToAdjustableDate(fraInputRange.UnadjustedPaymentDate,
                                                     fraInputRange.PaymentDateBusinessDayConvention,
                                                     fraInputRange.PaymentDateBusinessCenters),
                Items = new object[] { new ProductType {
                                           Value = ProductTypeSimpleEnum.FRA.ToString()
                                       } },
                ItemsElementName = new[] { ItemsChoiceType2.productType }
            };

            if ("resetDate" != fraInputRange.FixingDayOffsetDateRelativeTo)
            {
                throw new ArgumentException("The fixing date must be specified as 'resetDate'-relative!", nameof(fraInputRange));
            }
            var fixingDayType = EnumHelper.Parse <DayTypeEnum>(fraInputRange.FixingDayOffsetDayType);

            fra.fixingDateOffset = RelativeDateOffsetHelper.Create(fraInputRange.FixingDayOffsetPeriod, fixingDayType,
                                                                   fraInputRange.FixingDayOffsetBusinessDayConvention,
                                                                   fraInputRange.FixingDayOffsetBusinessCenters,
                                                                   fraInputRange.FixingDayOffsetDateRelativeTo);
            fra.dayCountFraction = DayCountFractionHelper.Parse(fraInputRange.DayCountFraction);
            IDayCounter dayCounter = DayCounterHelper.Parse(fra.dayCountFraction.Value);

            fra.calculationPeriodNumberOfDays = dayCounter.DayCount(fra.adjustedEffectiveDate.Value, fra.adjustedTerminationDate).ToString(CultureInfo.InvariantCulture);
            fra.notional                = MoneyHelper.GetAmount(fraInputRange.NotionalAmount, fraInputRange.NotionalCurrency);
            fra.fixedRate               = (decimal)fraInputRange.FixedRate;
            fra.fixedRateSpecified      = true;
            fra.floatingRateIndex       = FloatingRateIndexHelper.Parse(fraInputRange.FloatingRateIndex);
            fra.indexTenor              = new[] { PeriodHelper.Parse(fraInputRange.IndexTenor) };
            fra.fraDiscounting          = fraInputRange.FraDiscounting;
            fra.fraDiscountingSpecified = true;
            PartyReference party1 = PartyReferenceFactory.Create("party1");
            PartyReference party2 = PartyReferenceFactory.Create("party2");

            fra.sellerPartyReference = party1;
            fra.buyerPartyReference  = party2;
            if (bool.Parse(fraInputRange.IsParty1Buyer))
            {
                fra.sellerPartyReference = party2;
                fra.buyerPartyReference  = party1;
            }
            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            trade.id = fraInputRange.TradeId;
            return(trade);
        }
Esempio n. 6
0
        /// <summary>
        /// Creates the money amounts.
        /// </summary>
        /// <param name="amounts">The amounts.</param>
        /// <param name="currencys">The currencys.</param>
        /// <returns></returns>
        internal static Money[] CreateMoneyAmounts(decimal[] amounts, string[] currencys)
        {
            var currencyAmounts = new List <Money>();
            int index           = 0;

            foreach (decimal amount in amounts)
            {
                currencyAmounts.Add(MoneyHelper.GetAmount(amount, currencys[index]));
                index++;
            }
            return(currencyAmounts.ToArray());
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PriceablePrincipalExchange"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="payerIsBaseParty">A flag determining if the sign on the mamount is relative to the base party.</param>
 /// <param name="amount">The amount.</param>
 /// <param name="currency">The currency.</param>
 /// <param name="adjustedPaymentDate">The adjusted payment date.</param>
 /// <param name="paymentCalendar">Type paymentCalendar.</param>
 public PriceablePrincipalExchange
 (
     string id
     , bool payerIsBaseParty
     , Decimal amount
     , string currency
     , DateTime adjustedPaymentDate
     , IBusinessCalendar paymentCalendar) :
     base(id, "DiscountedCashflow", payerIsBaseParty, MoneyHelper.GetAmount(amount, currency), DateTypesHelper.ToAdjustableOrAdjustedDate(adjustedPaymentDate),
          PaymentTypeHelper.Create("Certain"), CashflowTypeHelper.Create(CashflowTypeEnum.PrincipalExchange.ToString()), false, paymentCalendar)
 {
 }
Esempio n. 8
0
        private void AddCashFlows(ILogger logger, ICoreCache cache,
                                  IBusinessCalendar fixingCalendar,
                                  IBusinessCalendar paymentCalendar,
                                  Fra fraFpML, bool isBuyer, String nameSpace)
        {
            EffectiveDate   = fraFpML.adjustedEffectiveDate.Value;
            TerminationDate = fraFpML.adjustedTerminationDate;
            if (paymentCalendar == null)
            {
                paymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, fraFpML.paymentDate.dateAdjustments.businessCenters, nameSpace);
            }
            if (fixingCalendar == null)
            {
                fixingCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, fraFpML.fixingDateOffset.businessCenters, nameSpace);
            }
            DateTime unadjustedPaymentDate = fraFpML.paymentDate.unadjustedDate.Value;
            var      notional = MoneyHelper.GetAmount(fraFpML.notional.amount, fraFpML.notional.currency);

            PaymentDate = paymentCalendar.Roll(unadjustedPaymentDate, BusinessDayConventionHelper.Parse(fraFpML.paymentDate.dateAdjustments.businessDayConvention.ToString()));
            DateTime adjustedFixingDate = GetResetDate(logger, cache, fixingCalendar, fraFpML, nameSpace);
            var      interval           = fraFpML.indexTenor[0];
            var      floatingInterest   = new PriceableFloatingRateCoupon(fraFpML.id + "FloatingCoupon_1"
                                                                          , isBuyer
                                                                          , EffectiveDate
                                                                          , TerminationDate
                                                                          , adjustedFixingDate
                                                                          , fraFpML.dayCountFraction
                                                                          , 0.0m
                                                                          , FixedRate
                                                                          , null
                                                                          , isBuyer ? MoneyHelper.Neg(notional) : notional
                                                                          , PaymentDate
                                                                          , new ForecastRateIndex {
                floatingRateIndex = fraFpML.floatingRateIndex, indexTenor = interval
            }
                                                                          , null
                                                                          , null
                                                                          , fraFpML.fraDiscounting
                                                                          , paymentCalendar
                                                                          , fixingCalendar)
            {
                ForecastRateInterpolation = ForecastRateInterpolation
            };

            // Combine two cashflows into one leg
            //
            FloatingCoupon = floatingInterest;//fraFpML.fraDiscounting,
        }
        /// <summary>
        /// Builds the calculation period.
        /// </summary>
        /// <returns></returns>
        override protected CalculationPeriod BuildCalculationPeriod()
        {
            CalculationPeriod cp = base.BuildCalculationPeriod();

            FloatingRateDefinition floatingRateDefinition = FloatingRateDefinitionHelper.CreateSimple(ForecastRateIndex.floatingRateIndex, ForecastRateIndex.indexTenor, AdjustedFixingDate, GetRate(), Margin);

            cp.Item1 = floatingRateDefinition;

            if (floatingRateDefinition.calculatedRateSpecified)
            {
                cp.forecastRate          = floatingRateDefinition.calculatedRate;
                cp.forecastRateSpecified = true;
            }
            cp.forecastAmount = MoneyHelper.GetAmount(CalculationResults.ExpectedValue, NotionalAmount.currency.Value);
            return(cp);
        }
Esempio n. 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fraInputRange"></param>
        /// <returns></returns>
        public static Fra GetFpMLFra(FraInputRange fraInputRange)
        {
            var fra = new Fra
            {
                adjustedEffectiveDate =
                    DateTypesHelper.ToRequiredIdentifierDate(fraInputRange.AdjustedEffectiveDate),
                adjustedTerminationDate = fraInputRange.AdjustedTerminationDate,
                paymentDate             =
                    DateTypesHelper.ToAdjustableDate(fraInputRange.UnadjustedPaymentDate,
                                                     fraInputRange.PaymentDateBusinessDayConvention,
                                                     fraInputRange.PaymentDateBusinessCenters)
            };

            if ("resetDate" != fraInputRange.FixingDayOffsetDateRelativeTo)
            {
                throw new ArgumentException("The fixing date must be specified as 'resetDate'-relative!", nameof(fraInputRange));
            }
            var fixingDayType = EnumHelper.Parse <DayTypeEnum>(fraInputRange.FixingDayOffsetDayType);

            fra.fixingDateOffset = RelativeDateOffsetHelper.Create(fraInputRange.FixingDayOffsetPeriod, fixingDayType,
                                                                   fraInputRange.FixingDayOffsetBusinessDayConvention,
                                                                   fraInputRange.FixingDayOffsetBusinessCenters,
                                                                   fraInputRange.FixingDayOffsetDateRelativeTo);
            fra.dayCountFraction = DayCountFractionHelper.Parse(fraInputRange.DayCountFraction);
            IDayCounter dayCounter = DayCounterHelper.Parse(fra.dayCountFraction.Value);

            fra.calculationPeriodNumberOfDays = dayCounter.DayCount(fra.adjustedEffectiveDate.Value, fra.adjustedTerminationDate).ToString();
            fra.notional          = MoneyHelper.GetAmount(fraInputRange.NotionalAmount, fraInputRange.NotionalCurrency);
            fra.fixedRate         = (decimal)fraInputRange.FixedRate;
            fra.floatingRateIndex = FloatingRateIndexHelper.Parse(fraInputRange.FloatingRateIndex);
            fra.indexTenor        = new[] { PeriodHelper.Parse(fraInputRange.IndexTenor) };
            fra.fraDiscounting    = fraInputRange.FraDiscounting;
            PartyReference nabParty     = PartyReferenceFactory.Create("NAB");
            PartyReference counterParty = PartyReferenceFactory.Create("COUNTERPARTY");

            if (bool.Parse(fraInputRange.Sell))
            {
                fra.sellerPartyReference = nabParty;
                fra.buyerPartyReference  = counterParty;
            }
            else
            {
                fra.sellerPartyReference = counterParty;
                fra.buyerPartyReference  = nabParty;
            }
            return(fra);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="couponId"></param>
        /// <param name="bondAsset"></param>
        /// <param name="notionalAmount"></param>
        /// <param name="bondCouponType"></param>
        /// <param name="paymentDate"></param>
        /// <param name="unadjustedStartDate"></param>
        /// <param name="unadjustedEndDate"></param>
        /// <param name="paymentCalendar"></param>
        /// <returns></returns>
        public static PriceableRateCoupon CreatePriceableBondCoupon(string couponId, Bond bondAsset, decimal notionalAmount, CouponStreamType bondCouponType, DateTime unadjustedStartDate,
                                                                    DateTime unadjustedEndDate, DateTime paymentDate, IBusinessCalendar paymentCalendar)//bool fOCalculationMethod, IBusinessCalendar fixingCalendar,
        {
            var currency         = bondAsset.currency;
            var dayCountFraction = bondAsset.dayCountFraction;
            var money            = MoneyHelper.GetAmount(notionalAmount, currency);

            //  If has a fixed rate (fixed rate coupon)
            if (bondCouponType == CouponStreamType.GenericFixedRate)
            {
                PriceableRateCoupon rateCoupon = new PriceableFixedRateCoupon(couponId, false, unadjustedStartDate, unadjustedEndDate,
                                                                              dayCountFraction, bondAsset.couponRate, money, null, paymentDate, null, null,
                                                                              null, paymentCalendar);
                return(rateCoupon);
            }
            throw new System.Exception("CalculationPeriod has neither fixedRate nor floatingRateDefinition.");
        }
Esempio n. 12
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <returns></returns>
        public BulletPayment Build()
        {
            var px = new BulletPayment
            {
                payment =
                    new Payment
                {
                    paymentAmount =
                        MoneyHelper.GetNonNegativeAmount(PaymentAmount.amount,
                                                         PaymentAmount.currency.Value)
                },
                Items            = new object[] { ProductTypeHelper.Create(ProductTypeSimpleEnum.BulletPayment.ToString()) },
                ItemsElementName = new[] { ItemsChoiceType2.productType }
            };

            //Setting the items array which contains product type and product is information.
            //payment type information
            px.payment.paymentType = PaymentTypeHelper.Create("Payment");
            //Set the party information
            px.payment.payerPartyReference = new PartyReference {
                href = "Party2"
            };
            px.payment.receiverPartyReference = new PartyReference {
                href = "Party1"
            };
            if (PayerIsBaseParty)
            {
                px.payment.payerPartyReference = new PartyReference {
                    href = "Party1"
                };
                px.payment.receiverPartyReference = new PartyReference {
                    href = "Party2"
                };
            }
            //The payment date
            px.payment.paymentDate = AdjustableOrAdjustedDateHelper.Create(null, PaymentDate, PaymentDateAdjustments);
            if (CalculationPerformedIndicator)
            {
                px.payment.discountFactor          = PaymentDiscountFactor;
                px.payment.discountFactorSpecified = true;
                px.payment.presentValueAmount      = MoneyHelper.GetAmount(CalculationResults.NPV, PaymentAmount.currency.Value);
            }
            return(px);
        }
Esempio n. 13
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <returns></returns>
        public Payment Build()
        {
            var px = PaymentHelper.Create(PayerPartyReference.href, ReceiverPartyReference.href, PaymentAmount.currency.Value, Math.Abs(PaymentAmount.amount), PaymentDate);

            px.id = Id;
            //px.paymentAmount = PaymentAmount;//this is the raw amount without the multiplier effect.
            px.paymentDate = AdjustableOrAdjustedDateHelper.CreateAdjustedDate(AdjustedPaymentDate.Value, PaymentDateAdjustments);
            if (CalculationPerformedIndicator)
            {
                var payment = Math.Abs(ForecastAmount.amount);
                px.paymentAmount = MoneyHelper.GetNonNegativeAmount(payment, ForecastAmount.currency.Value);
                var npv   = Math.Abs(NPV.amount);
                var money = MoneyHelper.GetAmount(npv, PaymentAmount.currency.Value);
                px.discountFactor          = PaymentDiscountFactor;
                px.discountFactorSpecified = true;
                px.presentValueAmount      = money;
            }
            return(px);
        }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PriceablePayment"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="receiverPartyReference">The receiver.</param>
 /// <param name="payerIsBase">The flag determining if the payer is the base party.</param>
 /// <param name="amount">The amount.</param>
 /// <param name="currency">The currency.</param>
 /// <param name="adjustedPaymentDate">The adjusted payment date.</param>
 /// <param name="payerPartyReference">The payer.</param>
 /// <param name="paymentCalendar">Type paymentCalendar.</param>
 public PriceablePayment
 (
     string id
     , string payerPartyReference
     , string receiverPartyReference
     , bool payerIsBase
     , Decimal amount
     , string currency
     , DateTime adjustedPaymentDate
     , IBusinessCalendar paymentCalendar) :
     base(id, "DiscountedCashflow", payerIsBase, MoneyHelper.GetAmount(amount, currency),
          AdjustableOrAdjustedDateHelper.CreateAdjustedDate(adjustedPaymentDate),
          PaymentTypeHelper.Create("Certain"), CashflowTypeHelper.Create(CashflowTypeEnum.PrincipalExchange.ToString()), false, paymentCalendar)
 {
     PayerPartyReference    = PartyReferenceFactory.Create(payerPartyReference);
     ReceiverPartyReference = PartyReferenceFactory.Create(receiverPartyReference);
     OrderedPartyNames.Add(PayerPartyReference.href);
     OrderedPartyNames.Add(ReceiverPartyReference.href);
 }
Esempio n. 15
0
        public static Trade CreateFraTrade(string tradeId, RequiredIdentifierDate adjustedEffectiveDate, DateTime adjustedTerminationDate,
                                           AdjustableDate paymentDate, RelativeDateOffset fixingDayOffset, DayCountFraction dayCountFraction, decimal notionalAmount,
                                           string notionalCurrency, decimal fixedRate, string floatingRateIndex, string indexTenor, FraDiscountingEnum fraDiscounting)
        {
            var trade = new Trade();
            var fra   = new Fra
            {
                adjustedEffectiveDate            = adjustedEffectiveDate,
                adjustedTerminationDate          = adjustedTerminationDate,
                adjustedTerminationDateSpecified = true,
                paymentDate = paymentDate,
                Items       = new object[] { new ProductType {
                                                 Value = ProductTypeSimpleEnum.FRA.ToString()
                                             } },
                ItemsElementName = new[] { ItemsChoiceType2.productType }
            };

            if ("resetDate" != fixingDayOffset.dateRelativeTo.href)
            {
                throw new ArgumentException("The fixing date must be specified as 'resetDate'-relative!", nameof(fixingDayOffset));
            }
            fra.fixingDateOffset = fixingDayOffset;
            fra.dayCountFraction = dayCountFraction;
            IDayCounter dayCounter = DayCounterHelper.Parse(fra.dayCountFraction.Value);

            fra.calculationPeriodNumberOfDays = dayCounter.DayCount(fra.adjustedEffectiveDate.Value, fra.adjustedTerminationDate).ToString(CultureInfo.InvariantCulture);
            fra.notional                = MoneyHelper.GetAmount(notionalAmount, notionalCurrency);
            fra.fixedRate               = fixedRate;
            fra.fixedRateSpecified      = true;
            fra.floatingRateIndex       = FloatingRateIndexHelper.Parse(floatingRateIndex);
            fra.indexTenor              = new[] { PeriodHelper.Parse(indexTenor) };
            fra.fraDiscounting          = fraDiscounting;
            fra.fraDiscountingSpecified = true;
            PartyReference party1 = PartyReferenceFactory.Create("party1");
            PartyReference party2 = PartyReferenceFactory.Create("party2");

            fra.sellerPartyReference = party2;
            fra.buyerPartyReference  = party1;
            XsdClassesFieldResolver.TradeSetFra(trade, fra);
            trade.id = tradeId;
            return(trade);
        }
Esempio n. 16
0
        /// <summary>
        /// Builds this instance and returns the underlying instrument associated with the controller
        /// </summary>
        /// <returns></returns>
        public TermDeposit Build()
        {
            var deposit = new TermDeposit
            {
                Items = new object[] { new ProductType {
                                           Value = ProductType.ToString()
                                       } },
                ItemsElementName      = new[] { ItemsChoiceType2.productType },
                dayCountFraction      = DayCountFraction,
                principal             = MoneyHelper.GetPositiveMoney(Principal),
                maturityDate          = TerminationDate,
                maturityDateSpecified = true,
                startDate             = EffectiveDate,
                startDateSpecified    = true,
                fixedRate             = FixedRate,
                fixedRateSpecified    = true
            };

            if (BasePartyPayingFixed)//From the viewpoint of the counterparty!
            {
                deposit.receiverPartyReference = PartyReferenceHelper.Parse(BaseParty);
                deposit.payerPartyReference    = PartyReferenceHelper.Parse(CounterParty);
            }
            else
            {
                deposit.payerPartyReference    = PartyReferenceHelper.Parse(BaseParty);
                deposit.receiverPartyReference = PartyReferenceHelper.Parse(CounterParty);
            }
            //deposit payments.
            if (deposit.payment?.Length == 3)
            {
                var initialDate  = AdjustableOrAdjustedDateHelper.Create(null, EffectiveDate, null);
                var maturityDate = AdjustableOrAdjustedDateHelper.Create(null, PaymentDate, null);
                deposit.payment[0].paymentDate = initialDate;
                deposit.payment[1].paymentDate = maturityDate;
                deposit.payment[2].paymentDate = maturityDate;
            }
            var interest = System.Math.Abs(InterestAmount.AccruedInterest);

            deposit.interest = MoneyHelper.GetAmount(interest, deposit.principal.currency.Value);
            return(deposit);
        }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PriceableFxOptionPremium"/> class.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="receiverPartyReference">The receiver.</param>
        /// <param name="payerIsBase">The flag determining if the payer is the base party.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="currency">The currency.</param>
        /// <param name="settlementDate">The adjusted payment date.</param>
        /// <param name="payerPartyReference">The payer.</param>
        /// <param name="premiumQuote">The premium quote </param>
        /// <param name="settlementInformation">The settlement information. </param>
        /// <param name="paymentCalendar">Type paymentCalendar.</param>
        public PriceableFxOptionPremium
        (
            string id
            , string payerPartyReference
            , string receiverPartyReference
            , bool payerIsBase
            , decimal amount
            , string currency
            , DateTime settlementDate
            , PremiumQuote premiumQuote
            , SettlementInformation settlementInformation
            , IBusinessCalendar paymentCalendar) :
            base(id, "DiscountedCashflow", payerIsBase, MoneyHelper.GetAmount(amount, currency),
                 AdjustableOrAdjustedDateHelper.CreateAdjustedDate(settlementDate),
                 PaymentTypeHelper.Create("Certain"), CashflowTypeHelper.Create(CashflowTypeEnum.Premium.ToString()), false, paymentCalendar)
        {
            PayerPartyReference    = PartyReferenceFactory.Create(payerPartyReference);
            ReceiverPartyReference = PartyReferenceFactory.Create(receiverPartyReference);
            OrderedPartyNames.Add(PayerPartyReference.href);
            OrderedPartyNames.Add(ReceiverPartyReference.href);
            if (premiumQuote != null)
            {
                PremiumQuote = new PremiumQuote
                {
                    quoteBasis = premiumQuote.quoteBasis,
                    value      = premiumQuote.value
                };
            }
            if (settlementInformation == null)
            {
                return;
            }
            SettlementInformation = new SettlementInformation();
            var item = BinarySerializerHelper.Clone(settlementInformation.Item);

            SettlementInformation.Item = item;
        }
        public PropertyTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime paymentDate, String referenceContract,
                                         IBusinessCalendar settlementCalendar, PropertyTransaction propertyFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            logger.LogInfo("PropertyType set. Commence to build a property transaction.");
            if (propertyFpML == null)
            {
                return;
            }
            //
            //Set the multiplier
            //
            Multiplier = 1.0m;
            //
            //Set the trade information
            //
            BuyerReference    = propertyFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                propertyFpML.purchasePrice.currency.Value
            };
            SellerReference           = propertyFpML.sellerPartyReference.href;
            BasePartyBuyer            = basePartyReference == propertyFpML.buyerPartyReference.href;
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            PaymentDate = paymentDate;
            //
            //Set the issuer information
            //
            ReferenceContract = referenceContract;
            //
            //Set the notional information
            //
            PurchasePrice     = MoneyHelper.GetAmount(propertyFpML.purchasePrice.amount, propertyFpML.purchasePrice.currency.Value);
            PaymentCurrencies = new List <string> {
                propertyFpML.purchasePrice.currency.Value
            };
            //
            //Get the instrument configuration information.
            //
            var propertyTypeInfo = propertyFpML.property;

            if (propertyFpML.property != null && propertyTypeInfo != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, propertyTypeInfo.businessDayAdjustments.businessCenters, nameSpace);
                }
                //Pre processes the data for the priceable asset.
                PropertyInfo = XmlSerializerHelper.Clone(propertyTypeInfo);
                //This is done because the config data is not stored in the correct way. Need to add a price quote units.
                //TODO Set other relevant property information
                //PropertyTypeInfo.Property.faceAmount = NotionalAmount.amount;
                if (!PaymentCurrencies.Contains(propertyFpML.purchasePrice.currency.Value))
                {
                    PaymentCurrencies.Add(propertyFpML.purchasePrice.currency.Value);
                }
                logger.LogInfo("Property transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Property type data not available.");
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="settlementDate">The payment settlement date.</param>
        /// <param name="settlementCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="bondFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="bondType"></param>
        /// <param name="forecastRateInterpolation"></param>
        public BondTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate,
                                     DateTime settlementDate, IBusinessCalendar settlementCalendar, IBusinessCalendar paymentCalendar,
                                     BondTransaction bondFpML, string basePartyReference, string bondType, bool forecastRateInterpolation)
        {
            Multiplier = 1.0m;
            TradeDate  = tradeDate;
            BondType   = EnumHelper.Parse <BondTypesEnum>(bondType);
            logger.LogInfo("BondType set. Commence to build a bond transaction.");
            if (bondFpML == null)
            {
                return;
            }
            BuyerReference    = bondFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                bondFpML.notionalAmount.currency.Value
            };
            SellerReference = bondFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == bondFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            PaymentCalendar           = paymentCalendar;
            //Set the bond price information
            BondPrice = new BondPrice();
            if (bondFpML.price.accrualsSpecified)
            {
                BondPrice.accrualsSpecified = true;
                BondPrice.accruals          = bondFpML.price.accruals;
            }
            if (bondFpML.price.dirtyPriceSpecified)
            {
                BondPrice.dirtyPriceSpecified = true;
                BondPrice.dirtyPrice          = bondFpML.price.dirtyPrice;
            }
            BondPrice.cleanOfAccruedInterest = bondFpML.price.cleanOfAccruedInterest;
            BondPrice.cleanPrice             = bondFpML.price.cleanPrice;
            //Set the currencies
            CouponCurrency  = bondFpML.notionalAmount.currency;
            PaymentCurrency = bondFpML.notionalAmount.currency;//This could be another currency!
            //Set the notional information
            NotionalAmount = MoneyHelper.GetAmount(bondFpML.notionalAmount.amount, bondFpML.notionalAmount.currency.Value);
            //Determines the quotation and units
            QuoteType = BondPriceEnum.YieldToMaturity;
            //We need to get the ytm in until there is a bond market price/spread.
            if (BondPrice.dirtyPriceSpecified)
            {
                QuoteType = BondPriceEnum.DirtyPrice;
                Quote     = BasicQuotationHelper.Create(BondPrice.dirtyPrice, RateQuotationType);
            }
            //Get the instrument configuration information.
            var            assetIdentifier = bondFpML.bond.currency.Value + "-Bond-" + BondType;
            BondNodeStruct bondTypeInfo    = null;
            //TODO Set the swap curves for asset swap valuation.
            //
            //Gets the template bond type
            var instrument = InstrumentDataHelper.GetInstrumentConfigurationData(cache, nameSpace, assetIdentifier);

            if (instrument != null)
            {
                bondTypeInfo = instrument.InstrumentNodeItem as BondNodeStruct;
            }
            if (bondFpML.bond != null && bondTypeInfo != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.SettlementDate.businessCenters, nameSpace);
                }
                if (PaymentCalendar == null)
                {
                    PaymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.BusinessDayAdjustments.businessCenters, nameSpace);
                }
                //Pre-processes the data for the priceable asset.
                var bond = XmlSerializerHelper.Clone(bondFpML.bond);
                Bond = bond;
                bondTypeInfo.Bond = Bond;
                //Set the curves to use for valuations.
                BondCurveName = CurveNameHelpers.GetBondCurveName(Bond.currency.Value, Bond.id);
                //THe discount curve is only for credit calculations.
                DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(Bond.currency.Value, true);
                if (bond.maturitySpecified)
                {
                    MaturityDate = bond.maturity;
                }
                SettlementDateConvention = bondTypeInfo.SettlementDate;
                BusinessDayAdjustments   = bondTypeInfo.BusinessDayAdjustments;
                ExDivDateConvention      = bondTypeInfo.ExDivDate;
                //This is done because the config data is not stored in the correct way. Need to add a price quote units.
                if (bond.couponRateSpecified)
                {
                    var coupon = bond.couponRate;
                    Bond.couponRate = coupon;
                }
                bondTypeInfo.Bond.faceAmount          = NotionalAmount.amount;
                bondTypeInfo.Bond.faceAmountSpecified = true;
                Bond.faceAmount = NotionalAmount.amount;
                if (Bond.maturitySpecified)
                {
                    RiskMaturityDate = Bond.maturity;
                }
                SettlementDate = settlementDate;
                if (!PaymentCurrencies.Contains(bondFpML.bond.currency.Value))
                {
                    PaymentCurrencies.Add(bondFpML.bond.currency.Value);
                }
                logger.LogInfo("Bond transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Bond type data not available.");
            }
            //Set the underlying bond
            UnderlyingBond = new PriceableSimpleBond(tradeDate, bondTypeInfo, SettlementCalendar, PaymentCalendar, Quote, QuoteType);
            BondIssuer     = UnderlyingBond.Issuer;
            if (BondPrice.dirtyPriceSpecified)
            {
                UnderlyingBond.PurchasePrice = BondPrice.dirtyPrice / 100; //PriceQuoteUnits
            }
            //Set the coupons
            var bondId = Bond.id;//Could use one of the instrumentIds

            //bondStream is an interest Rate Stream but needs to be converted to a bond stream.
            //It automatically contains the coupon currency.
            Coupons = new PriceableBondCouponRateStream(logger, cache, nameSpace, bondId, tradeDate,
                                                        bondFpML.notionalAmount.amount, CouponStreamType.GenericFixedRate, Bond,
                                                        BusinessDayAdjustments, ForecastRateInterpolation, null, PaymentCalendar);
            //Add payments like the settlement price
            if (!BondPrice.dirtyPriceSpecified)
            {
                return;
            }
            var amount            = BondPrice.dirtyPrice * NotionalAmount.amount / 100;
            var settlementPayment = PaymentHelper.Create(BuyerReference, SellerReference, PaymentCurrency.Value, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            //
            var finalPayment = PaymentHelper.Create(BondIssuer, BuyerReference, CouponCurrency.Value, NotionalAmount.amount, RiskMaturityDate);

            FinalRedemption =
                PriceableInstrumentsFactory.CreatePriceablePayment(basePartyReference, finalPayment, PaymentCalendar);
            AdditionalPayments.Add(FinalRedemption);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override AssetValuation Calculate(IInstrumentControllerData modelData)
        {
            ModelData = modelData;
            AnalyticModelParameters = null;
            AnalyticsModel          = new FloatingRateCouponAnalytic();
            RequiresReset           = modelData.ValuationDate > ResetDate;
            IsRealised = HasBeenRealised(ModelData.ValuationDate);
            //Make sure there are some bucket dates even if not set previously.
            if (BucketedDates.Length < 1)
            {
                UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval));
            }
            //Add the extra metrics required
            var quotes = ModelData.AssetValuation.quote.ToList();

            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.BreakEvenRate.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.BreakEvenRate.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.AccrualFactor.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.AccrualFactor.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.FloatingNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.FloatingNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.NPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.RiskNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyExpectedValue.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            //Check if risk calc are required.
            bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null;
            //Check if risk calc are required.
            bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null;

            ModelData.AssetValuation.quote = quotes.ToArray();
            var        metrics       = ResolveModelMetrics(AnalyticsModel.Metrics);
            IFxCurve   fxCurve       = null;
            IRateCurve discountCurve = null;
            IRateCurve forecastCurve = null;

            //// Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored
            //if (metrics.Contains(InstrumentMetrics.DiscountFactorAtMaturity))
            //{
            //    metrics.RemoveAll(metricItem => metricItem != InstrumentMetrics.DiscountFactorAtMaturity);
            //}
            //Set the forrecast rate dates. The ForecastRateInterpolation shhould have been set.
            ForwardStartDate = AccrualStartDate;
            ForwardEndDate   = ForecastRateInterpolation ? AccrualEndDate : AdjustedDateHelper.ToAdjustedDate(FixingCalendar, ForecastRateIndex.indexTenor.Add(ForwardStartDate), AccrualBusinessDayAdjustments);
            //var metricsToEvaluate = metrics.ToArray();
            if (metrics.Count > 0)
            {
                YearFractionToCashFlowPayment = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate);
                var reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value;
                var amount            = NotionalAmount.amount;
                IRateCouponParameters analyticModelParameters = new RateCouponParameters {
                    Multiplier        = Multiplier,
                    ValuationDate     = modelData.ValuationDate,
                    PaymentDate       = PaymentDate,
                    Currency          = PaymentCurrency.Value,
                    ReportingCurrency = reportingCurrency,
                    DiscountType      = DiscountType,
                    IsRealised        = IsRealised,
                    HasReset          = RequiresReset,
                    NotionalAmount    = amount,
                    Spread            = Margin,
                    YearFraction      = CouponYearFraction,
                    CurveYearFraction = YearFractionToCashFlowPayment
                };
                decimal?discountRate = null;
                // Curve Related
                if (modelData.MarketEnvironment is ISwapLegEnvironment environment)
                {
                    var streamMarket = environment;
                    discountCurve = streamMarket.GetDiscountRateCurve();
                    discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    forecastCurve = streamMarket.GetForecastRateCurve();
                    forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    DiscountCurveName = discountCurve.GetPricingStructureId().UniqueIdentifier;
                    analyticModelParameters.DiscountCurve = discountCurve;
                    ForecastCurveName = forecastCurve.GetPricingStructureId().UniqueIdentifier;
                    analyticModelParameters.ForecastCurve = forecastCurve;
                    // Bucketed Delta
                    if (BucketedDates.Length > 1)
                    {
                        analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0],
                                                                                              BucketedDates[1]);
                        analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve,
                                                                                                     ModelData.
                                                                                                     ValuationDate,
                                                                                                     BucketedDates);
                    }
                    //Check for currency.
                    if (ModelData.ReportingCurrency != null)
                    {
                        if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value)
                        {
                            fxCurve = streamMarket.GetReportingCurrencyFxCurve();
                            fxCurve.PricingStructureEvolutionType            = PricingStructureEvolutionType;
                            analyticModelParameters.ReportingCurrencyFxCurve = fxCurve;
                        }
                    }
                    AnalyticModelParameters = analyticModelParameters;
                }
                else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment))
                {
                    var market = (MarketEnvironment)modelData.MarketEnvironment;
                    discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName);
                    discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    forecastCurve = (IRateCurve)market.SearchForPricingStructureType(ForecastCurveName);
                    forecastCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    analyticModelParameters.DiscountCurve       = discountCurve;
                    analyticModelParameters.ForecastCurve       = forecastCurve;
                    // Bucketed Delta
                    if (BucketedDates.Length > 1)
                    {
                        analyticModelParameters.PeriodAsTimesPerYear = GetPaymentYearFraction(BucketedDates[0],
                                                                                              BucketedDates[1]);
                        analyticModelParameters.BucketedDiscountFactors = GetBucketedDiscountFactors(discountCurve,
                                                                                                     ModelData.
                                                                                                     ValuationDate,
                                                                                                     BucketedDates);
                    }
                    if (delta1PDH)
                    {
                        var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH");
                        analyticModelParameters.Delta1PDHCurves       = riskMarket;
                        analyticModelParameters.Delta1PDHPerturbation = 10;
                    }
                    if (delta0PDH)
                    {
                        var riskMarket = market.SearchForPerturbedPricingStructures(ForecastCurveName, "delta0PDH");
                        analyticModelParameters.Delta0PDHCurves       = riskMarket;
                        analyticModelParameters.Delta0PDHPerturbation = 10;
                    }
                    //Check for currency.
                    if (ModelData.ReportingCurrency != null)
                    {
                        if (ModelData.ReportingCurrency.Value != PaymentCurrency.Value)
                        {
                            string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value);
                            fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName);
                            fxCurve.PricingStructureEvolutionType            = PricingStructureEvolutionType;
                            analyticModelParameters.ReportingCurrencyFxCurve = fxCurve;
                        }
                    }
                    AnalyticModelParameters = analyticModelParameters;
                }
                //Set the base rate. Default is zero
                if (AnalyticModelParameters != null)
                {
                    AnalyticModelParameters.BaseRate = BaseRate;
                }
                if (UseObservedRate)
                {
                    AnalyticsModel = new FixedRateCouponAnalytic(ModelData.ValuationDate, AccrualStartDate, AccrualEndDate, PaymentDate, Rate,
                                                                 analyticModelParameters.YearFraction, DiscountType, fxCurve, discountCurve, forecastCurve);
                    if (Rate != null)
                    {
                        analyticModelParameters.Rate = (decimal)Rate;
                    }
                }
                else
                {
                    if (Rate != null)
                    {
                        discountRate = Rate;
                    }
                    if (DiscountRate != null)
                    {
                        discountRate = DiscountRate;
                    }
                    AnalyticsModel = new FloatingRateCouponAnalytic(ModelData.ValuationDate, AccrualStartDate,
                                                                    AccrualEndDate, PaymentDate, discountRate,
                                                                    analyticModelParameters.YearFraction,
                                                                    DiscountType, fxCurve, discountCurve,
                                                                    forecastCurve);
                }
                CalculationResults           = AnalyticsModel.Calculate <IRateInstrumentResults, RateInstrumentResults>(AnalyticModelParameters, metrics.ToArray());
                CalculationPerfomedIndicator = true;
                PaymentDiscountFactor        = ((FixedRateCouponAnalytic)AnalyticsModel).PaymentDiscountFactor;
                if (!UseObservedRate)
                {
                    Rate = CalculationResults.BreakEvenRate;
                }
                ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency);
                NPV            = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency);
            }
            AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate);

            valuation.id = Id;
            return(valuation);
        }
Esempio n. 21
0
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override AssetValuation Calculate(IInstrumentControllerData modelData)
        {
            ModelData = modelData;
            AnalyticModelParameters       = null;
            AnalyticsModel                = new FxOptionAnalytic();
            CalculationResults            = null;
            YearFractionToCashFlowPayment = Convert.ToDecimal(CDefaultDayCounter.YearFraction(ModelData.ValuationDate, PaymentDate));
            //Make sure there are some bucket dates even if not set previously.
            if (BucketedDates.Length < 1)
            {
                UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval));
            }
            IsRealised = HasBeenRealised(ModelData.ValuationDate);
            //Add the extra metrics required
            var quotes = ModelData.AssetValuation.quote.ToList();

            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.NPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            //Check if risk calc are required.
            bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null;
            //Check if risk calc are required.
            bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null;

            ModelData.AssetValuation.quote = quotes.ToArray();
            //Set the cash flowdetails.
            HasReset     = modelData.ValuationDate > ResetDate;
            IsRealised   = HasBeenRealised(ModelData.ValuationDate);
            TimeToExpiry = GetPaymentYearFraction(ModelData.ValuationDate, AdjustedFixingDate);
            var                volatilityCurveNodeTime = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate);
            IFxCurve           fxCurve       = null;
            IRateCurve         discountCurve = null;
            IFxCurve           currencyCurve = null;
            IVolatilitySurface volSurface    = null;
            var                metrics       = ResolveModelMetrics(AnalyticsModel.Metrics);

            //var metricsToEvaluate = metrics.ToArray();
            //if (metricsToEvaluate.Length > 0)
            //{
            YearFractionToCashFlowPayment = GetPaymentYearFraction(ModelData.ValuationDate, PaymentDate);
            var reportingCurrency = ModelData.ReportingCurrency == null
                                        ? PaymentCurrency.Value
                                        : ModelData.ReportingCurrency.Value;
            decimal?premium = null;

            if (Premium != null)
            {
                premium = Premium;
            }
            IFxRateCashflowParameters analyticModelParameters = new FxRateCashflowParameters
            {
                ValuationDate      = modelData.ValuationDate,
                PaymentDate        = PaymentDate,
                Currency           = PaymentCurrency.Value,
                ReportingCurrency  = reportingCurrency,
                IsRealised         = IsRealised,
                IsReset            = HasReset,
                NotionalAmount     = NotionalAmount.amount,
                CurveYearFraction  = YearFractionToCashFlowPayment,
                ExpiryYearFraction = TimeToExpiry,
                Premium            = premium
            };

            // Curve Related
            if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                var market = (MarketEnvironment)modelData.MarketEnvironment;
                discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName);
                discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                volSurface = (IVolatilitySurface)market.SearchForPricingStructureType(VolatilitySurfaceName);
                volSurface.PricingStructureEvolutionType = PricingStructureEvolutionType;
                var currencyCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(StartFxRate.quotedCurrencyPair.currency1.Value,
                                                                                    StartFxRate.quotedCurrencyPair.currency2.Value);
                currencyCurve = (IFxCurve)market.SearchForPricingStructureType(currencyCurveName);
                currencyCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                analyticModelParameters.DiscountCurve       = discountCurve;
                if (delta1PDH)
                {
                    var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH");
                    analyticModelParameters.Delta1PDHCurves       = riskMarket;
                    analyticModelParameters.Delta1PDHPerturbation = 10;
                }
                if (delta0PDH)//TODO Do this for the fxrate
                {
                    //var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta0PDH");
                    //    //TODO The fx deltas
                    //analyticModelParameters.Delta1PDHCurves = riskMarket;
                    //analyticModelParameters.Delta1PDHPerturbation = 10;
                }
                if (modelData.ReportingCurrency.Value != PaymentCurrency.Value)
                {
                    string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value,
                                                                                   modelData.ReportingCurrency.Value);
                    fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName);
                    fxCurve.PricingStructureEvolutionType            = PricingStructureEvolutionType;
                    analyticModelParameters.ReportingCurrencyFxCurve = fxCurve;
                }
                if (HybridValuation)
                {
                    var currency1RateCurve =
                        (IRateCurve)market.SearchForPricingStructureType(Currency1DiscountCurveName);
                    currency1RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    var currency2RateCurve =
                        (IRateCurve)market.SearchForPricingStructureType(Currency2DiscountCurveName);
                    currency2RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    AnalyticsModel = new FxOptionAnalytic(ModelData.ValuationDate, PaymentDate, currencyCurve, currency1RateCurve,
                                                          currency2RateCurve, IsSettlementInCurrency1, !InvertFxRate, Strike, TimeToExpiry, volatilityCurveNodeTime, volSurface, FxOptionType, fxCurve);
                }
            }
            // store inputs and results from this run
            AnalyticModelParameters = analyticModelParameters;
            if (!HybridValuation)
            {
                AnalyticsModel = new FxOptionAnalytic(ModelData.ValuationDate, PaymentDate, Strike, TimeToExpiry, volatilityCurveNodeTime,
                                                      fxCurve, currencyCurve, discountCurve, volSurface, FxOptionType);
            } //TODO Fix this with a generic index curve.
            //AnalyticsModel = analyticsModel;
            CalculationResults =
                AnalyticsModel.Calculate <IFloatingCashflowResults, FloatingCashflowResults>(
                    AnalyticModelParameters, metrics.ToArray());
            CalculationPerfomedIndicator = true;
            PaymentDiscountFactor        = ((FxRateCashflowAnalytic)AnalyticsModel).PaymentDiscountFactor;
            ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue,
                                                   PaymentAmount.currency);
            NPV = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency);
            AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate);

            valuation.id = Id;
            return(valuation);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="buyerIsBase"></param>
        /// <param name="calculation"></param>
        /// <param name="coupon"></param>
        /// <param name="fOCalculationMethod"></param>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <returns></returns>
        public static PriceableCapFloorCoupon CreatePriceableCapFloorCoupon(bool buyerIsBase,
                                                                            Calculation calculation, PaymentCalculationPeriod coupon, bool fOCalculationMethod
                                                                            , IBusinessCalendar fixingCalendar, IBusinessCalendar paymentCalendar)
        {
            var notional         = (Notional)calculation.Item;
            var currency         = notional.notionalStepSchedule.currency;
            var dayCountFraction = calculation.dayCountFraction;
            var paymentDate      = coupon.adjustedPaymentDateSpecified
                                  ? coupon.adjustedPaymentDate
                                  : coupon.unadjustedPaymentDate;
            var calculationPeriods =
                XsdClassesFieldResolver.GetPaymentCalculationPeriodCalculationPeriodArray(coupon);

            if (calculationPeriods.Length == 1)
            {
                var calculationPeriod = calculationPeriods[0];
                //Money expectedCashFlow = null;
                decimal notionalamount   = XsdClassesFieldResolver.CalculationPeriodGetNotionalAmount(calculationPeriod);
                Money   money            = buyerIsBase ? MoneyHelper.GetAmount(-1 * notionalamount, currency) : MoneyHelper.GetAmount(notionalamount, currency);
                var     accrualStartDate = calculationPeriod.adjustedStartDateSpecified
                                           ? calculationPeriod.adjustedStartDate
                                           : calculationPeriod.unadjustedStartDate;
                var accrualEndDate = calculationPeriod.adjustedEndDateSpecified
                                         ? calculationPeriod.adjustedEndDate
                                         : calculationPeriod.unadjustedEndDate;
                //  If has a fixed rate (fixed rate coupon)
                var isThereDiscounting = XsdClassesFieldResolver.CalculationHasDiscounting(calculation);
                if (XsdClassesFieldResolver.CalculationPeriodHasFloatingRateDefinition(calculationPeriod))
                {
                    //The floating rate definition.
                    FloatingRateDefinition floatingRateDefinition = XsdClassesFieldResolver.CalculationPeriodGetFloatingRateDefinition(calculationPeriod);
                    //The floatingrateCalculation.
                    Debug.Assert(calculation.Items != null);
                    Debug.Assert(calculation.Items.Length > 0);
                    Debug.Assert(calculation.Items[0] is FloatingRateCalculation);
                    var floatingRateCalculation = (FloatingRateCalculation)calculation.Items[0];
                    //The forecast rate index.
                    var floatingRateIndex = floatingRateCalculation.floatingRateIndex;
                    var indexTenor        = floatingRateCalculation.indexTenor.ToString();
                    var forecastRate      = ForecastRateIndexHelper.Parse(floatingRateIndex.Value, indexTenor);
                    //The rate observation
                    // Apply spread from schedule if it hasn't been specified yet.
                    decimal margin = 0m;
                    if (floatingRateDefinition.spreadSpecified)
                    {
                        margin = floatingRateDefinition.spread;
                    }
                    //The observed rate.
                    Decimal?observedRate = null;
                    Decimal?capStrike    = null;
                    Decimal?floorStrike  = null;
                    if (floatingRateDefinition.capRate != null)
                    {
                        capStrike = floatingRateDefinition.capRate[0].strikeRate;
                    }
                    if (floatingRateDefinition.floorRate != null)
                    {
                        floorStrike = floatingRateDefinition.floorRate[0].strikeRate;
                    }
                    if (floatingRateDefinition.rateObservation != null)
                    {
                        var rateObservation = floatingRateDefinition.rateObservation[0];
                        if (rateObservation.observedRateSpecified)
                        {
                            observedRate = rateObservation.observedRate;
                        }
                        PriceableCapFloorCoupon rateCoupon;
                        if (isThereDiscounting)
                        {
                            var discounting = XsdClassesFieldResolver.CalculationGetDiscounting(calculation);
                            var floatingCouponWithDiscounting = new PriceableCapFloorCoupon(coupon.id, buyerIsBase,
                                                                                            capStrike, floorStrike, accrualStartDate, accrualEndDate,
                                                                                            rateObservation.adjustedFixingDate, dayCountFraction,
                                                                                            margin, observedRate, money, paymentDate,
                                                                                            forecastRate, discounting.discountingType,
                                                                                            observedRate, null, fixingCalendar, paymentCalendar);
                            if (fOCalculationMethod)
                            {
                                floatingCouponWithDiscounting.ForecastRateInterpolation = true;
                            }
                            rateCoupon = floatingCouponWithDiscounting;
                            return(rateCoupon);
                        }
                        var floatingCoupon = new PriceableCapFloorCoupon(coupon.id, buyerIsBase, capStrike, floorStrike,
                                                                         accrualStartDate, accrualEndDate,
                                                                         rateObservation.adjustedFixingDate, dayCountFraction,
                                                                         margin, observedRate, money, paymentDate,
                                                                         forecastRate, null, null, null,
                                                                         fixingCalendar, paymentCalendar);
                        if (fOCalculationMethod)
                        {
                            floatingCoupon.ForecastRateInterpolation = true;
                        }
                        rateCoupon = floatingCoupon;
                        return(rateCoupon);
                    }
                    throw new NotImplementedException("Need to return a rate coupon, Alex!");
                }
                throw new System.Exception("CalculationPeriod has neither fixedRate nor floatingRateDefinition.");
            }
            throw new System.Exception("PaymentCalculationPeriod has zero, or multiple CalculationPeriods.");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="payerIsBase"></param>
        /// <param name="calculation"></param>
        /// <param name="coupon"></param>
        /// <param name="fOCalculationMethod"></param>
        /// <param name="fixingCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <returns></returns>
        public static PriceableRateCoupon CreatePriceableCoupon(bool payerIsBase, Calculation calculation, PaymentCalculationPeriod coupon, bool fOCalculationMethod
                                                                , IBusinessCalendar fixingCalendar, IBusinessCalendar paymentCalendar)
        {
            var notional         = (Notional)calculation.Item;
            var currency         = notional.notionalStepSchedule.currency;
            var dayCountFraction = calculation.dayCountFraction;
            var paymentDate      = coupon.adjustedPaymentDateSpecified
                                  ? coupon.adjustedPaymentDate
                                  : coupon.unadjustedPaymentDate;
            var calculationPeriods      = XsdClassesFieldResolver.GetPaymentCalculationPeriodCalculationPeriodArray(coupon);
            var discountFactorSpecified = coupon.discountFactorSpecified;

            if (calculationPeriods.Length == 1)
            {
                var calculationPeriod = calculationPeriods[0];
                var notionalAmount    = XsdClassesFieldResolver.CalculationPeriodGetNotionalAmount(calculationPeriod);
                var money             = payerIsBase ? MoneyHelper.GetAmount(-1 * notionalAmount, currency) : MoneyHelper.GetAmount(notionalAmount, currency);
                var accrualStartDate  = calculationPeriod.adjustedStartDateSpecified
                                           ? calculationPeriod.adjustedStartDate
                                           : calculationPeriod.unadjustedStartDate;
                var accrualEndDate = calculationPeriod.adjustedEndDateSpecified
                                         ? calculationPeriod.adjustedEndDate
                                         : calculationPeriod.unadjustedEndDate;
                //  If has a fixed rate (fixed rate coupon)
                var isThereDiscounting = XsdClassesFieldResolver.CalculationHasDiscounting(calculation);
                PriceableRateCoupon rateCoupon;
                if (XsdClassesFieldResolver.CalculationPeriodHasFixedRate(calculationPeriod))
                {
                    decimal finalRate = XsdClassesFieldResolver.CalculationPeriodGetFixedRate(calculationPeriod);
                    //The discount rate must be set. It would normally be the final rate. The assumption is that, it the discounting rate is zero then the final rate should be used.
                    if (isThereDiscounting)
                    {
                        var discounting = XsdClassesFieldResolver.CalculationGetDiscounting(calculation);
                        //This test works because if the rate is zero, then the coupon is not discounted and discounting Type should be null.
                        var discountRate = discounting.discountRate == 0.0m ? finalRate : discounting.discountRate;
                        rateCoupon = new PriceableFixedRateCoupon(coupon.id, payerIsBase, accrualStartDate, accrualEndDate,
                                                                  dayCountFraction, finalRate, money, null, paymentDate, discounting.discountingType, discountRate,
                                                                  null, paymentCalendar);
                        if (discountFactorSpecified)
                        {
                            rateCoupon.PaymentDiscountFactor = coupon.discountFactor;
                        }
                        return(rateCoupon);
                    }
                    rateCoupon = new PriceableFixedRateCoupon(coupon.id, payerIsBase, accrualStartDate, accrualEndDate,
                                                              dayCountFraction, finalRate, money, null, paymentDate, null, null,
                                                              null, paymentCalendar);
                    if (discountFactorSpecified)
                    {
                        rateCoupon.PaymentDiscountFactor = coupon.discountFactor;
                    }
                    return(rateCoupon);
                }
                if (XsdClassesFieldResolver.CalculationPeriodHasFloatingRateDefinition(calculationPeriod))
                {
                    //The floating rate definition.
                    FloatingRateDefinition floatingRateDefinition = XsdClassesFieldResolver.CalculationPeriodGetFloatingRateDefinition(calculationPeriod);
                    //The floating rate Calculation.
                    Debug.Assert(calculation.Items != null);
                    Debug.Assert(calculation.Items.Length > 0);
                    Debug.Assert(calculation.Items[0] is FloatingRateCalculation);
                    var floatingRateCalculation = (FloatingRateCalculation)calculation.Items[0];
                    //The forecast rate index.
                    var floatingRateIndex = floatingRateCalculation.floatingRateIndex;
                    var indexTenor        = floatingRateCalculation.indexTenor.ToString();
                    var forecastRate      = ForecastRateIndexHelper.Parse(floatingRateIndex.Value, indexTenor);
                    //The rate observation
                    // Apply spread from schedule if it hasn't been specified yet.
                    var margin = 0m;
                    if (floatingRateDefinition.spreadSpecified)
                    {
                        margin = floatingRateDefinition.spread;
                    }
                    //The observed rate.
                    Decimal?observedRate = null;
                    Decimal?capStrike    = null;
                    Decimal?floorStrike  = null;
                    if (floatingRateDefinition.capRate != null)
                    {
                        capStrike = floatingRateDefinition.capRate[0].strikeRate;
                    }
                    if (floatingRateDefinition.floorRate != null)
                    {
                        floorStrike = floatingRateDefinition.floorRate[0].strikeRate;
                    }
                    if (floatingRateDefinition.rateObservation != null)//TODO This is a big problem. Need to handle the case of no fixing date!
                    {
                        var rateObservation = floatingRateDefinition.rateObservation[0];
                        if (rateObservation.observedRateSpecified)
                        {
                            observedRate = rateObservation.observedRate;
                        }
                        //Removed because Igor's old code populates these fields when the trade is created. This means the coupon is not recalculated!
                        //Now the coupon will ignore any previous calculations and only treat as a fixed coupon if the observed rate has been specified.
                        if (isThereDiscounting)
                        {
                            var discounting = XsdClassesFieldResolver.CalculationGetDiscounting(calculation);
                            if (capStrike != null || floorStrike != null)
                            {
                                rateCoupon = new PriceableCapFloorCoupon(coupon.id, !payerIsBase,
                                                                         capStrike, floorStrike, accrualStartDate, accrualEndDate,
                                                                         rateObservation.adjustedFixingDate, dayCountFraction,
                                                                         margin, observedRate, money, paymentDate,
                                                                         forecastRate, discounting.discountingType,
                                                                         observedRate, null, fixingCalendar, paymentCalendar);
                            }
                            else
                            {
                                rateCoupon = new PriceableFloatingRateCoupon(coupon.id, !payerIsBase, accrualStartDate, accrualEndDate,
                                                                             rateObservation.adjustedFixingDate, dayCountFraction,
                                                                             margin, observedRate, money, paymentDate,
                                                                             forecastRate, discounting.discountingType,
                                                                             observedRate, null, fixingCalendar, paymentCalendar);
                            }
                        }
                        else
                        {
                            if (capStrike != null || floorStrike != null)
                            {
                                rateCoupon = new PriceableCapFloorCoupon(coupon.id, !payerIsBase, capStrike, floorStrike,
                                                                         accrualStartDate, accrualEndDate,
                                                                         rateObservation.adjustedFixingDate, dayCountFraction,
                                                                         margin, observedRate, money, paymentDate,
                                                                         forecastRate, null, null, null,
                                                                         fixingCalendar, paymentCalendar);
                            }
                            else
                            {
                                rateCoupon = new PriceableFloatingRateCoupon(coupon.id, payerIsBase, accrualStartDate, accrualEndDate,
                                                                             rateObservation.adjustedFixingDate, dayCountFraction,
                                                                             margin, observedRate, money, paymentDate,
                                                                             forecastRate, null, null, null,
                                                                             fixingCalendar, paymentCalendar);
                            }
                        }
                        if (fOCalculationMethod)
                        {
                            ((PriceableFloatingRateCoupon)rateCoupon).ForecastRateInterpolation = true;
                        }
                        if (discountFactorSpecified)
                        {
                            rateCoupon.PaymentDiscountFactor = coupon.discountFactor;
                        }
                        return(rateCoupon);
                    }
                    throw new NotImplementedException("Need to return a rate coupon, Alex!");
                }
                throw new System.Exception("CalculationPeriod has neither fixedRate nor floatingRateDefinition.");
            }
            throw new System.Exception("PaymentCalculationPeriod has zero, or multiple CalculationPeriods.");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="settlementDate">The payment settlement date.</param>
        /// <param name="settlementCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="bondFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="bondType"></param>
        /// <param name="forecastRateInterpolation"></param>
        public BondTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate,
                                     DateTime settlementDate, IBusinessCalendar settlementCalendar, IBusinessCalendar paymentCalendar,
                                     BondTransaction bondFpML, string basePartyReference, string bondType, Boolean forecastRateInterpolation)
        {
            Multiplier = 1.0m;
            TradeDate  = tradeDate;
            BondType   = EnumHelper.Parse <BondTypesEnum>(bondType);
            logger.LogInfo("BondType set. Commence to build a bond transaction.");
            if (bondFpML == null)
            {
                return;
            }
            BuyerReference    = bondFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                bondFpML.notionalAmount.currency.Value
            };
            SellerReference = bondFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == bondFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            PaymentCalendar           = paymentCalendar;
            //Set the bond price information
            BondPrice = new BondPrice();
            if (bondFpML.price.accrualsSpecified)
            {
                BondPrice.accrualsSpecified = true;
                BondPrice.accruals          = bondFpML.price.accruals;
            }
            if (bondFpML.price.dirtyPriceSpecified)
            {
                BondPrice.dirtyPriceSpecified = true;
                BondPrice.dirtyPrice          = bondFpML.price.dirtyPrice;
            }
            BondPrice.cleanOfAccruedInterest = bondFpML.price.cleanOfAccruedInterest;
            BondPrice.cleanPrice             = bondFpML.price.cleanPrice;
            //Set the notional information
            NotionalAmount = MoneyHelper.GetAmount(bondFpML.notionalAmount.amount, bondFpML.notionalAmount.currency.Value);
            //Determines the quotation and units
            QuoteType = BondPriceEnum.YieldToMaturity;
            //We need to get the ytm in until there is a bond market price/spread.
            if (BondPrice.dirtyPriceSpecified)
            {
                QuoteType = BondPriceEnum.DirtyPrice;
                Quote     = BasicQuotationHelper.Create(BondPrice.dirtyPrice, RateQuotationType);
            }
            //Get the insturment configuration information.
            var            assetIdentifier = bondFpML.bond.currency.Value + "-Bond-" + BondType;
            BondNodeStruct bondTypeInfo    = null;
            var            instrument      = InstrumentDataHelper.GetInstrumentConfigurationData(cache, nameSpace, assetIdentifier);

            if (instrument != null)
            {
                bondTypeInfo = instrument.InstrumentNodeItem as BondNodeStruct;
            }
            if (bondFpML.bond != null && bondTypeInfo != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.SettlementDate.businessCenters, nameSpace);
                }
                if (PaymentCalendar == null)
                {
                    PaymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.BusinessDayAdjustments.businessCenters, nameSpace);
                }
                //Preprocesses the data for the priceableasset.
                var bond = XmlSerializerHelper.Clone(bondFpML.bond);
                BondTypeInfo      = XmlSerializerHelper.Clone(bondTypeInfo);
                BondTypeInfo.Bond = bond;
                //This is done because the config data is not stored in the ciorrect way. Need to add a price quote units.
                if (bond.couponRateSpecified)
                {
                    var coupon = bond.couponRate;
                    BondTypeInfo.Bond.couponRate = coupon;
                }
                BondTypeInfo.Bond.faceAmount = NotionalAmount.amount;
                if (BondTypeInfo.Bond.maturitySpecified)
                {
                    RiskMaturityDate = BondTypeInfo.Bond.maturity;
                }
                SettlementDate = settlementDate;
                if (!PaymentCurrencies.Contains(bondFpML.bond.currency.Value))
                {
                    PaymentCurrencies.Add(bondFpML.bond.currency.Value);
                }
                logger.LogInfo("Bond transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Bond type data not available.");
            }
            //Add payments like the settlement price
            if (!BondPrice.dirtyPriceSpecified)
            {
                return;
            }
            var amount            = BondPrice.dirtyPrice * NotionalAmount.amount / 100;
            var settlementPayment = PaymentHelper.Create("BondSettlemetAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
Esempio n. 25
0
        private static void CalculateForecastPaymentAmount(Calculation calculation,
                                                           FloatingRateCalculation floatingRateCalculation,
                                                           PaymentCalculationPeriod paymentCalculationPeriod,
                                                           IRateCurve forecastCurve,
                                                           IRateCurve discountCurve,
                                                           DateTime valuationDate)
        {
            var      amountAccruedPerPaymentPeriod = new List <Money>();
            decimal  interestFromPreviousPeriods   = 0;
            Notional notionalSchedule = XsdClassesFieldResolver.CalculationGetNotionalSchedule(calculation);
            Currency notionalCurrency = notionalSchedule.notionalStepSchedule.currency;

            //  Cashflows
            //
            foreach (CalculationPeriod calculationPeriod in XsdClassesFieldResolver.GetPaymentCalculationPeriodCalculationPeriodArray(paymentCalculationPeriod))
            {
                decimal notional  = XsdClassesFieldResolver.CalculationPeriodGetNotionalAmount(calculationPeriod);
                decimal finalRate = 0.0m;
                //  If has a fixed rate (fixed rate coupon)
                //
                if (XsdClassesFieldResolver.CalculationPeriodHasFixedRate(calculationPeriod))
                {
                    finalRate = XsdClassesFieldResolver.CalculationPeriodGetFixedRate(calculationPeriod);
                }
                else if (XsdClassesFieldResolver.CalculationPeriodHasFloatingRateDefinition(calculationPeriod))
                {
                    if (null != forecastCurve)
                    {
                        FloatingRateDefinition floatingRateDefinition = XsdClassesFieldResolver.CalculationPeriodGetFloatingRateDefinition(calculationPeriod);
                        // Apply spread from schedule if it hasn't been specified yet.
                        //
                        if (!floatingRateDefinition.spreadSpecified)
                        {
                            floatingRateDefinition.spread          = floatingRateCalculation.spreadSchedule[0].initialValue;
                            floatingRateDefinition.spreadSpecified = true;
                        }
                        ForecastRateHelper.UpdateFloatingRateDefinition(floatingRateDefinition, floatingRateCalculation,
                                                                        calculation.dayCountFraction,
                                                                        calculationPeriod,
                                                                        forecastCurve);
                        calculationPeriod.Item1 = floatingRateDefinition;
                        decimal calculatedRate = floatingRateDefinition.calculatedRate;
                        //  final rate after application of Cap/Floor  rates
                        //
                        finalRate = calculatedRate;
                        //  If has a Cap rate, finalRate = MAX(0, FinalRate - CapRate)
                        //
                        if (null != floatingRateDefinition.capRate)
                        {
                            Strike strike = floatingRateDefinition.capRate[0];
                            finalRate = System.Math.Max(0, finalRate - strike.strikeRate);
                        }
                        //  If has a Floor rate, finalRate = MAX(0, FloorRate - FinalRate)
                        //
                        if (null != floatingRateDefinition.floorRate)
                        {
                            Strike strike = floatingRateDefinition.floorRate[0];
                            finalRate = System.Math.Max(0, strike.strikeRate - finalRate);
                        }
                    }
                }
                else
                {
                    throw new System.Exception("CalculationPeriod has neither fixedRate nor floatngRateDefinition.");
                }
                // Compound interest accrued during previos calculation periods in this payment period.
                //
                decimal notionalAdjustedForInterestFromPreviousPeriods = notional + interestFromPreviousPeriods;
                if (calculation.discounting == null)
                {
                    interestFromPreviousPeriods = notionalAdjustedForInterestFromPreviousPeriods * finalRate * calculationPeriod.dayCountYearFraction;
                }
                else if (calculation.discounting.discountingType == DiscountingTypeEnum.FRA || calculation.discounting.discountingType == DiscountingTypeEnum.Standard)
                {
                    interestFromPreviousPeriods = notionalAdjustedForInterestFromPreviousPeriods * (1.0m - 1.0m / (1.0m + finalRate * calculationPeriod.dayCountYearFraction));
                }
                else
                {
                    throw new NotSupportedException("The specified discountingType is not supported.");
                }
                Money amountAccruedPerCalculationPeriod = MoneyHelper.GetAmount(interestFromPreviousPeriods, notionalCurrency);
                amountAccruedPerPaymentPeriod.Add(amountAccruedPerCalculationPeriod);
            }
            paymentCalculationPeriod.forecastPaymentAmount   = MoneyHelper.Sum(amountAccruedPerPaymentPeriod);
            paymentCalculationPeriod.discountFactor          = (decimal)discountCurve.GetDiscountFactor(valuationDate, paymentCalculationPeriod.adjustedPaymentDate);
            paymentCalculationPeriod.discountFactorSpecified = true;
            paymentCalculationPeriod.presentValueAmount      = MoneyHelper.Mul(paymentCalculationPeriod.forecastPaymentAmount, paymentCalculationPeriod.discountFactor);
        }
Esempio n. 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="effectiveDate"></param>
        /// <param name="referenceEquity"></param>
        /// <param name="settlementCalendar"></param>
        /// <param name="equityFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="forecastRateInterpolation"></param>
        public EquityTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate, DateTime effectiveDate,
                                       String referenceEquity, IBusinessCalendar settlementCalendar, EquityTransaction equityFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            logger.LogInfo("EquityType set. Commence to build a equity transaction.");
            if (equityFpML == null)
            {
                return;
            }
            SettlementDate    = effectiveDate;
            TradeDate         = tradeDate;
            Multiplier        = 1.0m;
            BuyerReference    = equityFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                equityFpML.unitPrice.currency.Value
            };
            SellerReference           = equityFpML.sellerPartyReference.href;
            BasePartyBuyer            = basePartyReference == equityFpML.buyerPartyReference.href;
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            ReferenceEquity           = referenceEquity;
            NumberOfShares            = Convert.ToInt16(equityFpML.numberOfUnits);
            PurchasePrice             = MoneyHelper.GetAmount(equityFpML.unitPrice.amount, equityFpML.unitPrice.currency.Value);
            PaymentCurrencies         = new List <string> {
                equityFpML.unitPrice.currency.Value
            };
            var exchangeMIC     = equityFpML.equity.exchangeId;
            var exchangeMICData = InstrumentDataHelper.CreateEquityExchangeKey(nameSpace, exchangeMIC.Value);
            var exchangeData    = cache.LoadItem <ExchangeConfigData>(exchangeMICData);

            if (exchangeData?.Data is ExchangeConfigData)
            {
                var exchange       = (ExchangeConfigData)exchangeData.Data;
                var equityTypeInfo = new EquityNodeStruct {
                    SettlementDate = exchange.SettlementDate
                };
                if (equityFpML.equity != null)
                {
                    if (SettlementCalendar == null)
                    {
                        SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache,
                                                                                     equityTypeInfo.SettlementDate
                                                                                     .businessCenters,
                                                                                     nameSpace);
                    }
                    if (PaymentCalendar == null)
                    {
                        PaymentCalendar = SettlementCalendar;
                    }
                    var equity = XmlSerializerHelper.Clone(equityFpML.equity);
                    EquityTypeInfo        = XmlSerializerHelper.Clone(equityTypeInfo);
                    EquityTypeInfo.Equity = equity;;
                    RiskMaturityDate      = SettlementDate;
                    MaturityDate          = SettlementDate;
                    if (!PaymentCurrencies.Contains(equityFpML.equity.currency.Value))
                    {
                        PaymentCurrencies.Add(equityFpML.equity.currency.Value);
                    }
                    logger.LogInfo("Equity transaction has been successfully created.");
                }
            }
            else
            {
                logger.LogInfo("Equity type data not available.");
            }
            //Add payments like the settlement price
            if (PurchasePrice == null || !PurchasePrice.amountSpecified)
            {
                return;
            }
            var amount            = PurchasePrice.amount * NumberOfShares;
            var settlementPayment = PaymentHelper.Create("EquitySettlemetAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, PaymentCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>//TODO the floating delta?
        /// <returns></returns>
        public override AssetValuation Calculate(IInstrumentControllerData modelData)
        {
            ModelData = modelData;
            AnalyticModelParameters       = null;
            AnalyticsModel                = new FxRateCashflowAnalytic();
            CalculationResults            = null;
            YearFractionToCashFlowPayment = Convert.ToDecimal(CDefaultDayCounter.YearFraction(ModelData.ValuationDate, PaymentDate));
            //Make sure there are some bucket dates even if not set previously.
            if (BucketedDates.Length < 1)
            {
                UpdateBucketingInterval(ModelData.ValuationDate, PeriodHelper.Parse(CDefaultBucketingInterval));
            }
            IsRealised = HasBeenRealised(ModelData.ValuationDate);
            //Add the extra metrics required
            var quotes = ModelData.AssetValuation.quote.ToList();

            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.NPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyNPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.RiskNPV.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, InstrumentMetrics.NPV.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            if (AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString()) == null)
            {
                var quote = QuotationHelper.Create(0.0m, FloatingCashflowMetrics.LocalCurrencyExpectedValue.ToString(), "DecimalValue", ModelData.ValuationDate);
                quotes.Add(quote);
            }
            //Check if risk calc are required.
            bool delta1PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta1PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta1PDH.ToString()) != null;
            //Check if risk calc are required.
            bool delta0PDH = AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.LocalCurrencyDelta0PDH.ToString()) != null ||
                             AssetValuationHelper.GetQuotationByMeasureType(ModelData.AssetValuation, InstrumentMetrics.Delta0PDH.ToString()) != null;

            ModelData.AssetValuation.quote = quotes.ToArray();
            var        metrics           = ResolveModelMetrics(AnalyticsModel.Metrics);
            IFxCurve   fxCurve           = null;
            IRateCurve discountCurve     = null;
            IFxCurve   currencyCurve     = null;
            var        reportingCurrency = ModelData.ReportingCurrency == null ? PaymentCurrency.Value : ModelData.ReportingCurrency.Value;
            //Set the basic model.
            var analyticModelParameters = new FxRateCashflowParameters
            {
                Multiplier        = Multiplier,
                ValuationDate     = ModelData.ValuationDate,
                PaymentDate       = PaymentDate,
                Currency          = PaymentCurrency.Value,
                ReportingCurrency = reportingCurrency,
                NotionalAmount    = PaymentAmount.amount,
                StartIndex        = StartIndex,
                IsRealised        = IsRealised,
                CurveYearFraction =
                    YearFractionToCashFlowPayment,
                PeriodAsTimesPerYear = 0.25m,
                BucketingRate        = 0.05m
            };

            if (modelData.MarketEnvironment is ISwapLegEnvironment environment)
            {
                var marketEnvironment = environment;
                //The discount curve.
                discountCurve = marketEnvironment.GetDiscountRateCurve();
                discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                analyticModelParameters.DiscountCurve       = discountCurve;
                //Check if it is our of currency.
                if (ModelData.ReportingCurrency != null && ModelData.ReportingCurrency.Value != PaymentCurrency.Value)
                {
                    fxCurve = marketEnvironment.GetReportingCurrencyFxCurve();
                    fxCurve.PricingStructureEvolutionType            = PricingStructureEvolutionType;
                    analyticModelParameters.ReportingCurrencyFxCurve = fxCurve;
                }
            }
            else if (modelData.MarketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                var market = (MarketEnvironment)modelData.MarketEnvironment;
                discountCurve = (IRateCurve)market.SearchForPricingStructureType(DiscountCurveName);
                discountCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                analyticModelParameters.DiscountCurve       = discountCurve;
                var currencyCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(StartFxRate.quotedCurrencyPair.currency1.Value, StartFxRate.quotedCurrencyPair.currency2.Value);
                currencyCurve = (IFxCurve)market.SearchForPricingStructureType(currencyCurveName);
                currencyCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                if (delta1PDH)
                {
                    var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta1PDH");
                    analyticModelParameters.Delta1PDHCurves       = riskMarket;
                    analyticModelParameters.Delta1PDHPerturbation = 10;
                }
                if (delta0PDH)
                {
                    var riskMarket = market.SearchForPerturbedPricingStructures(DiscountCurveName, "delta0PDH");//TODO The fx deltas
                    analyticModelParameters.Delta1PDHCurves       = riskMarket;
                    analyticModelParameters.Delta1PDHPerturbation = 10;
                }
                if (modelData.ReportingCurrency.Value != PaymentCurrency.Value)
                {
                    string curveName = MarketEnvironmentHelper.ResolveFxCurveNames(PaymentCurrency.Value, modelData.ReportingCurrency.Value);
                    fxCurve = (IFxCurve)market.SearchForPricingStructureType(curveName);
                    fxCurve.PricingStructureEvolutionType            = PricingStructureEvolutionType;
                    analyticModelParameters.ReportingCurrencyFxCurve = fxCurve;
                }
                if (HybridValuation)
                {
                    var currency1RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency1DiscountCurveName);
                    currency1RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    var currency2RateCurve = (IRateCurve)market.SearchForPricingStructureType(Currency2DiscountCurveName);
                    currency2RateCurve.PricingStructureEvolutionType = PricingStructureEvolutionType;
                    AnalyticsModel = new FxRateCashflowAnalytic(ModelData.ValuationDate, PaymentDate, currencyCurve, currency1RateCurve, currency2RateCurve, !InvertFxRate, IsSettlementInCurrency1, fxCurve);
                }
            }
            // store inputs and results from this run
            AnalyticModelParameters = analyticModelParameters;
            if (!HybridValuation)
            {
                AnalyticsModel = new FxRateCashflowAnalytic(ModelData.ValuationDate, PaymentDate,
                                                            fxCurve, currencyCurve, discountCurve);
            } //TODO Fix this with a generic index curve.
            //AnalyticsModel = analyticsModel;
            CalculationResults            = AnalyticsModel.Calculate <IFloatingCashflowResults, FloatingCashflowResults>(AnalyticModelParameters, metrics.ToArray());
            CalculationPerformedIndicator = true;
            PaymentDiscountFactor         = ((FxRateCashflowAnalytic)AnalyticsModel).PaymentDiscountFactor;
            ForecastAmount = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyExpectedValue, PaymentAmount.currency);
            NPV            = MoneyHelper.GetAmount(CalculationResults.LocalCurrencyNPV, PaymentAmount.currency);
            AssetValuation valuation = GetValue(CalculationResults, modelData.ValuationDate);

            valuation.id = Id;
            return(valuation);
        }
Esempio n. 28
0
        public FutureTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate, ExchangeContractTypeEnum futuresType,
                                       IBusinessCalendar settlementCalendar, FutureTransaction futureFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            logger.LogInfo("FuturesType set. Commence to build a future transaction.");
            if (futureFpML == null)
            {
                return;
            }
            Multiplier        = 1.0m;
            BuyerReference    = futureFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                futureFpML.unitPrice.currency.Value
            };
            SellerReference = futureFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == futureFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            FuturesType       = futuresType;
            ReferenceContract = futureFpML.future.id;
            var futuresCode = ReferenceContract.Split('-')[2];

            NumberOfContracts = Convert.ToInt16(futureFpML.numberOfUnits);
            PurchasePrice     = MoneyHelper.GetAmount(futureFpML.unitPrice.amount, futureFpML.unitPrice.currency.Value);
            var exchangeMIC = futureFpML.future.exchangeId;

            FuturesCurveName  = CurveNameHelpers.GetExchangeTradedCurveName(futureFpML.unitPrice.currency.Value, exchangeMIC.Value, futuresCode);
            DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(futureFpML.unitPrice.currency, true);
            FuturesTypeInfo   = new FutureNodeStruct();
            var exchangeMICData = InstrumentDataHelper.CreateEquityExchangeKey(nameSpace, exchangeMIC.Value);
            var exchangeData    = cache.LoadItem <ExchangeConfigData>(exchangeMICData);

            if (exchangeData?.Data is ExchangeConfigData)
            {
                Exchange = (ExchangeConfigData)exchangeData.Data;
                FuturesTypeInfo.SpotDate = Exchange.SettlementDate;
            }
            if (futureFpML.future != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache,
                                                                                 FuturesTypeInfo.SpotDate
                                                                                 .businessCenters,
                                                                                 nameSpace);
                }
                var future = XmlSerializerHelper.Clone(futureFpML.future);
                FuturesTypeInfo.Future = future;
                if (FuturesTypeInfo.SpotDate != null)
                {
                    SettlementDate = GetSettlementDate(tradeDate, SettlementCalendar,
                                                       FuturesTypeInfo.SpotDate);
                }
                //Instantiate the priceable future.
                NamedValueSet namedValueSet = PriceableAssetFactory.BuildPropertiesForAssets(nameSpace, FuturesTypeInfo.Future.id, tradeDate);
                var           asset         = AssetHelper.Parse(FuturesTypeInfo.Future.id, 0.0m, 0.0m);
                UnderlyingFuture = PriceableAssetFactory.Create(logger, cache, nameSpace, asset.Second, namedValueSet, null, null) as IPriceableFuturesAssetController;
                if (UnderlyingFuture != null)
                {
                    RiskMaturityDate = UnderlyingFuture.GetRiskMaturityDate();
                    MaturityDate     = RiskMaturityDate;
                    LastTradeDate    = UnderlyingFuture.LastTradeDate;
                }
                if (!PaymentCurrencies.Contains(futureFpML.future.currency.Value))
                {
                    PaymentCurrencies.Add(futureFpML.future.currency.Value);
                }
                logger.LogInfo("Futures transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Futures type data not available.");
            }
            //Add payments like the settlement price
            if (!PurchasePrice.amountSpecified)
            {
                return;
            }
            var amount            = PurchasePrice.amount * NumberOfContracts / 100;
            var settlementPayment = PaymentHelper.Create("FuturesSettlemetAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }