/// <summary>
        /// Creates a trade representing the CDS at the node.
        /// <para>
        /// This uses the observed market data to build the CDS trade that the node represents.
        /// The resulting trade is not resolved.
        /// The notional of the trade is taken from the 'quantity' variable.
        /// The quantity is signed and will affect whether the trade is Buy or Sell.
        /// The valuation date is defined by the market data.
        ///
        /// </para>
        /// </summary>
        /// <param name="quantity">  the quantity or notional of the trade </param>
        /// <param name="marketData">  the market data required to build a trade for the instrument, including the valuation date </param>
        /// <param name="refData">  the reference data, used to resolve the trade dates </param>
        /// <returns> a trade representing the instrument at the node </returns>
        public CdsCalibrationTrade trade(double quantity, MarketData marketData, ReferenceData refData)
        {
            BuySell   buySell       = quantity > 0 ? BuySell.BUY : BuySell.SELL;
            LocalDate valuationDate = marketData.ValuationDate;
            double    quoteValue    = marketData.getValue(observableId);
            CdsQuote  quote         = CdsQuote.of(quoteConvention, quoteValue);
            double    notional      = Math.Abs(quantity);

            if (quoteConvention.Equals(CdsQuoteConvention.PAR_SPREAD))
            {
                return(CdsCalibrationTrade.of(template.createTrade(legalEntityId, valuationDate, buySell, notional, quoteValue, refData), quote));
            }
            double coupon = FixedRate.Value;     // always success

            return(CdsCalibrationTrade.of(template.createTrade(legalEntityId, valuationDate, buySell, notional, coupon, refData), quote));
        }
        internal virtual LegalEntitySurvivalProbabilities calibrate(IList <CdsIsdaCreditCurveNode> curveNodes, CurveName name, MarketData marketData, ImmutableCreditRatesProvider ratesProvider, DayCount definitionDayCount, Currency definitionCurrency, bool computeJacobian, bool storeTrade, ReferenceData refData)
        {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <StandardId> legalEntities = curveNodes.Select(CdsIsdaCreditCurveNode::getLegalEntityId).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            StandardId legalEntityId = legalEntities.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(legalEntities.hasNext(), "legal entity must be common to curve nodes");
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <Currency> currencies = curveNodes.Select(n => n.Template.Convention.Currency).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            Currency currency = currencies.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(currencies.hasNext(), "currency must be common to curve nodes");
            ArgChecker.isTrue(definitionCurrency.Equals(currency), "curve definition currency must be the same as the currency of CDS");
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            IEnumerator <CdsQuoteConvention> quoteConventions = curveNodes.Select(n => n.QuoteConvention).collect(Collectors.toSet()).GetEnumerator();
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            CdsQuoteConvention quoteConvention = quoteConventions.next();

//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
            ArgChecker.isFalse(quoteConventions.hasNext(), "quote convention must be common to curve nodes");
            LocalDate valuationDate = marketData.ValuationDate;

            ArgChecker.isTrue(valuationDate.Equals(marketData.ValuationDate), "ratesProvider and marketDate must be based on the same valuation date");
            CreditDiscountFactors discountFactors = ratesProvider.discountFactors(currency);

            ArgChecker.isTrue(definitionDayCount.Equals(discountFactors.DayCount), "credit curve and discount curve must be based on the same day count convention");
            RecoveryRates recoveryRates = ratesProvider.recoveryRates(legalEntityId);

            int nNodes = curveNodes.Count;

            double[] coupons = new double[nNodes];
            double[] pufs    = new double[nNodes];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] diag = new double[nNodes][nNodes];
            double[][] diag = RectangularArrays.ReturnRectangularDoubleArray(nNodes, nNodes);
            ImmutableList.Builder <ResolvedCdsTrade> tradesBuilder = ImmutableList.builder();
            for (int i = 0; i < nNodes; i++)
            {
                CdsCalibrationTrade tradeCalibration = curveNodes[i].trade(1d, marketData, refData);
                ResolvedCdsTrade    trade            = tradeCalibration.UnderlyingTrade.resolve(refData);
                tradesBuilder.add(trade);
                double[] temp = getStandardQuoteForm(trade, tradeCalibration.Quote, valuationDate, discountFactors, recoveryRates, computeJacobian, refData);
                coupons[i] = temp[0];
                pufs[i]    = temp[1];
                diag[i][i] = temp[2];
            }
            ImmutableList <ResolvedCdsTrade> trades = tradesBuilder.build();
            NodalCurve nodalCurve = calibrate(trades, DoubleArray.ofUnsafe(coupons), DoubleArray.ofUnsafe(pufs), name, valuationDate, discountFactors, recoveryRates, refData);

            if (computeJacobian)
            {
                LegalEntitySurvivalProbabilities            creditCurve      = LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, nodalCurve));
                ImmutableCreditRatesProvider                ratesProviderNew = ratesProvider.toBuilder().creditCurves(ImmutableMap.of(Pair.of(legalEntityId, currency), creditCurve)).build();
                System.Func <ResolvedCdsTrade, DoubleArray> sensiFunc        = quoteConvention.Equals(CdsQuoteConvention.PAR_SPREAD) ? getParSpreadSensitivityFunction(ratesProviderNew, name, currency, refData) : getPointsUpfrontSensitivityFunction(ratesProviderNew, name, currency, refData);
                DoubleMatrix sensi = DoubleMatrix.ofArrayObjects(nNodes, nNodes, i => sensiFunc(trades.get(i)));
                sensi = (DoubleMatrix)MATRIX_ALGEBRA.multiply(DoubleMatrix.ofUnsafe(diag), sensi);
                JacobianCalibrationMatrix jacobian = JacobianCalibrationMatrix.of(ImmutableList.of(CurveParameterSize.of(name, nNodes)), MATRIX_ALGEBRA.getInverse(sensi));
                nodalCurve = nodalCurve.withMetadata(nodalCurve.Metadata.withInfo(CurveInfoType.JACOBIAN, jacobian));
            }

            ImmutableList <ParameterMetadata> parameterMetadata;

            if (storeTrade)
            {
                parameterMetadata = IntStream.range(0, nNodes).mapToObj(n => ResolvedTradeParameterMetadata.of(trades.get(n), curveNodes[n].Label)).collect(Guavate.toImmutableList());
            }
            else
            {
                parameterMetadata = IntStream.range(0, nNodes).mapToObj(n => curveNodes[n].metadata(trades.get(n).Product.ProtectionEndDate)).collect(Guavate.toImmutableList());
            }
            nodalCurve = nodalCurve.withMetadata(nodalCurve.Metadata.withParameterMetadata(parameterMetadata));

            return(LegalEntitySurvivalProbabilities.of(legalEntityId, IsdaCreditDiscountFactors.of(currency, valuationDate, nodalCurve)));
        }