import copy
import datetime
from typing import Any, Iterator, Literal, Optional, Union

from lseg_analytics.core.common._resource_base import ResourceBase
from lseg_analytics.core.exceptions import (
    LibraryException,
    ResourceNotFound,
    check_exception_and_raise,
    check_id,
)

from lseg_analytics.pricing._basic_client.models import (
    AdjustableDate,
    AmortizationDefinition,
    AmortizationTypeEnum,
    Amount,
    BachelierParameters,
    BasePricingParameters,
    BlackScholesEquityParameters,
    BlackScholesFxParameters,
    BlackScholesInterestRateFuture,
    BusinessDayAdjustmentDefinition,
    CapFloorDefinition,
    CapFloorTypeEnum,
    Cashflow,
    CmdtyOptionVolSurfaceChoice,
    CmdtyVolSurfaceInput,
    CompoundingModeEnum,
    ConvexityAdjustment,
    CouponReferenceDateEnum,
    CreditCurveChoice,
    CreditCurveInput,
    CrossCurencySwapOverride,
    CurencyBasisSwapOverride,
    CurveDataPoint,
    Date,
    DatedRate,
    DatedValue,
    DateMovingConvention,
    DayCountBasis,
    Description,
    DirectionEnum,
    Dividend,
    DividendTypeEnum,
    EndOfMonthConvention,
    EqOptionVolSurfaceChoice,
    EqVolSurfaceInput,
    FixedRateDefinition,
    FloatingRateDefinition,
    FrequencyEnum,
    FutureDate,
    FutureDateCalculationMethodEnum,
    FxCurveInput,
    FxForwardCurveChoice,
    FxOptionVolSurfaceChoice,
    FxPricingParameters,
    FxRateTypeEnum,
    FxVolSurfaceInput,
    HestonEquityParameters,
    IncomeTaxCashflow,
    IndexCompoundingDefinition,
    IndexFixing,
    IndexFixingForwardSourceEnum,
    IndexObservationMethodEnum,
    InflationRateDefinition,
    InnerError,
    InterestCashflow,
    InterestRateDefinition,
    InterestRateLegDefinition,
    InterestRateTypeEnum,
    InterestType,
    IrCapVolSurfaceChoice,
    IrCurveChoice,
    IrLegDescriptionFields,
    IrLegResponseFields,
    IrLegValuationResponseFields,
    IrMeasure,
    IrPricingParameters,
    IrRiskFields,
    IrSwapAsCollectionItem,
    IrSwapDefinition,
    IrSwapDefinitionInstrument,
    IrSwapInstrumentDescriptionFields,
    IrSwapInstrumentRiskFields,
    IrSwapInstrumentSolveResponseFieldsOnResourceResponseData,
    IrSwapInstrumentSolveResponseFieldsResponseData,
    IrSwapInstrumentSolveResponseFieldsResponseWithError,
    IrSwapInstrumentValuationFields,
    IrSwapInstrumentValuationResponseFieldsOnResourceResponseData,
    IrSwapInstrumentValuationResponseFieldsResponseData,
    IrSwapInstrumentValuationResponseFieldsResponseWithError,
    IrSwapSolvingParameters,
    IrSwapSolvingTarget,
    IrSwapSolvingVariable,
    IrSwaptionVolCubeChoice,
    IrValuationFields,
    IrVolCubeInput,
    IrVolSurfaceInput,
    IrZcCurveInput,
    LoanDefinition,
    LoanInstrumentRiskFields,
    LoanInstrumentValuationFields,
    Location,
    MarketData,
    MarketVolatility,
    Measure,
    ModelParameters,
    MonthEnum,
    NumericalMethodEnum,
    OffsetDefinition,
    OptionPricingParameters,
    OptionSolvingParameters,
    OptionSolvingTarget,
    OptionSolvingVariable,
    OptionSolvingVariableEnum,
    PaidLegEnum,
    PartyEnum,
    PayerReceiverEnum,
    Payment,
    PaymentOccurrenceEnum,
    PaymentSettlementDefinition,
    PayoffCashflow,
    PremiumCashflow,
    PriceSideWithLastEnum,
    PrincipalCashflow,
    PrincipalDefinition,
    Rate,
    ReferenceDate,
    RelativeAdjustableDate,
    RequestPatternEnum,
    ResetDatesDefinition,
    ScheduleDefinition,
    ServiceError,
    SettlementCashflow,
    SolvingLegEnum,
    SolvingMethod,
    SolvingMethodEnum,
    SolvingResult,
    SortingOrderEnum,
    Spot,
    SpreadCompoundingModeEnum,
    StepRateDefinition,
    StrikeTypeEnum,
    StructuredNotePricingParameters,
    StubIndexReferences,
    StubRuleEnum,
    SwapSolvingVariableEnum,
    TenorBasisSwapOverride,
    TimeStampEnum,
    UnitEnum,
    VanillaIrsOverride,
    VolatilityTypeEnum,
    VolCubePoint,
    VolModelTypeEnum,
    VolSurfacePoint,
    ZcTypeEnum,
)
from lseg_analytics.pricing._client.client import Client
from lseg_analytics.pricing.async_handler._async_response import (
    AsyncPollingResponse,
    AsyncRequestResponse,
    check_async_polling_response,
    check_async_request_response,
)

from ._ir_swap import IrSwap
from ._logger import logger

__all__ = [
    "AmortizationDefinition",
    "AmortizationTypeEnum",
    "Amount",
    "BachelierParameters",
    "BasePricingParameters",
    "BlackScholesEquityParameters",
    "BlackScholesFxParameters",
    "BlackScholesInterestRateFuture",
    "BusinessDayAdjustmentDefinition",
    "CapFloorDefinition",
    "CapFloorTypeEnum",
    "Cashflow",
    "CmdtyOptionVolSurfaceChoice",
    "CmdtyVolSurfaceInput",
    "CompoundingModeEnum",
    "ConvexityAdjustment",
    "CouponReferenceDateEnum",
    "CreditCurveChoice",
    "CreditCurveInput",
    "CrossCurencySwapOverride",
    "CurencyBasisSwapOverride",
    "CurveDataPoint",
    "DatedRate",
    "DatedValue",
    "DirectionEnum",
    "Dividend",
    "DividendTypeEnum",
    "EqOptionVolSurfaceChoice",
    "EqVolSurfaceInput",
    "FixedRateDefinition",
    "FloatingRateDefinition",
    "FutureDate",
    "FutureDateCalculationMethodEnum",
    "FxCurveInput",
    "FxForwardCurveChoice",
    "FxOptionVolSurfaceChoice",
    "FxPricingParameters",
    "FxRateTypeEnum",
    "FxVolSurfaceInput",
    "HestonEquityParameters",
    "IncomeTaxCashflow",
    "IndexCompoundingDefinition",
    "IndexFixing",
    "IndexFixingForwardSourceEnum",
    "IndexObservationMethodEnum",
    "InflationRateDefinition",
    "InterestCashflow",
    "InterestRateDefinition",
    "InterestRateLegDefinition",
    "InterestRateTypeEnum",
    "IrCapVolSurfaceChoice",
    "IrCurveChoice",
    "IrLegDescriptionFields",
    "IrLegResponseFields",
    "IrLegValuationResponseFields",
    "IrMeasure",
    "IrPricingParameters",
    "IrRiskFields",
    "IrSwap",
    "IrSwapAsCollectionItem",
    "IrSwapDefinition",
    "IrSwapDefinitionInstrument",
    "IrSwapInstrumentDescriptionFields",
    "IrSwapInstrumentRiskFields",
    "IrSwapInstrumentSolveResponseFieldsOnResourceResponseData",
    "IrSwapInstrumentSolveResponseFieldsResponseData",
    "IrSwapInstrumentSolveResponseFieldsResponseWithError",
    "IrSwapInstrumentValuationFields",
    "IrSwapInstrumentValuationResponseFieldsOnResourceResponseData",
    "IrSwapInstrumentValuationResponseFieldsResponseData",
    "IrSwapInstrumentValuationResponseFieldsResponseWithError",
    "IrSwapSolvingParameters",
    "IrSwapSolvingTarget",
    "IrSwapSolvingVariable",
    "IrSwaptionVolCubeChoice",
    "IrValuationFields",
    "IrVolCubeInput",
    "IrVolSurfaceInput",
    "IrZcCurveInput",
    "LoanDefinition",
    "LoanInstrumentRiskFields",
    "LoanInstrumentValuationFields",
    "MarketData",
    "MarketVolatility",
    "Measure",
    "ModelParameters",
    "MonthEnum",
    "NumericalMethodEnum",
    "OffsetDefinition",
    "OptionPricingParameters",
    "OptionSolvingParameters",
    "OptionSolvingTarget",
    "OptionSolvingVariable",
    "OptionSolvingVariableEnum",
    "PartyEnum",
    "Payment",
    "PaymentOccurrenceEnum",
    "PaymentSettlementDefinition",
    "PayoffCashflow",
    "PremiumCashflow",
    "PriceSideWithLastEnum",
    "PrincipalCashflow",
    "PrincipalDefinition",
    "Rate",
    "RequestPatternEnum",
    "ResetDatesDefinition",
    "ScheduleDefinition",
    "SettlementCashflow",
    "SolvingLegEnum",
    "SolvingMethod",
    "SolvingMethodEnum",
    "SolvingResult",
    "Spot",
    "SpreadCompoundingModeEnum",
    "StepRateDefinition",
    "StrikeTypeEnum",
    "StructuredNotePricingParameters",
    "StubIndexReferences",
    "SwapSolvingVariableEnum",
    "TenorBasisSwapOverride",
    "TimeStampEnum",
    "UnitEnum",
    "VanillaIrsOverride",
    "VolCubePoint",
    "VolModelTypeEnum",
    "VolSurfacePoint",
    "VolatilityTypeEnum",
    "ZcTypeEnum",
    "create_from_cbs_template",
    "create_from_ccs_template",
    "create_from_leg_template",
    "create_from_tbs_template",
    "create_from_vanilla_irs_template",
    "delete",
    "load",
    "search",
    "solve",
    "solve_result",
    "value",
    "value_result",
]


def create_from_cbs_template(
    *,
    template_reference: str,
    overrides: Optional[CurencyBasisSwapOverride] = None,
    fields: Optional[str] = None,
) -> IrSwap:
    """
    Create an interest rate swap instance from a currency basis swap template.
    This user-defined instrument includes all trade-specific details (e.g., fixed rate, spread, start date, end date), and is typically based on a general template available via the Instrument Template API.

    Parameters
    ----------
    template_reference : str
        "The identifier of the currency basis swap template (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    overrides : CurencyBasisSwapOverride, optional
        An object that contains the currency basis swap properties that can be overridden.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap
        IrSwap

    Examples
    --------
    >>> swap_from_cbs = create_from_cbs_template(template_reference = "LSEG/GBUSSOSRBS")
    >>> print(swap_from_cbs.definition)
    {'firstLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/GBP_SONIA_ON', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['UKG', 'USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['UKG', 'USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_365', 'accrualDayCount': 'Dcb_Actual_365', 'principal': {'currency': 'GBP', 'amount': 10000000.0, 'initialPrincipalExchange': True, 'finalPrincipalExchange': True, 'interimPrincipalExchange': False, 'repaymentCurrency': 'GBP'}, 'payer': 'Party1', 'receiver': 'Party2'}, 'secondLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/USD_SOFR_ON', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['UKG', 'USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['UKG', 'USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'USD', 'initialPrincipalExchange': True, 'finalPrincipalExchange': True, 'interimPrincipalExchange': False, 'repaymentCurrency': 'USD'}, 'payer': 'Party2', 'receiver': 'Party1'}}

    """

    try:
        logger.info("Calling create_from_cbs_template")

        response = Client().ir_swaps_resource.create_irs_from_cbs_template(
            fields=fields, template_reference=template_reference, overrides=overrides
        )

        output = response.data
        logger.info("Called create_from_cbs_template")

        return IrSwap(output)
    except Exception as err:
        logger.error("Error create_from_cbs_template")
        check_exception_and_raise(err, logger)


def create_from_ccs_template(
    *,
    template_reference: str,
    overrides: Optional[CrossCurencySwapOverride] = None,
    fields: Optional[str] = None,
) -> IrSwap:
    """
    Create an interest rate swap instance from a cross currency swap template.
    This user-defined instrument includes all trade-specific details (e.g., fixed rate, spread, start date, end date), and is typically based on a general template available via the Instrument Template API.

    Parameters
    ----------
    template_reference : str
        "The identifier of the cross currency swap template (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    overrides : CrossCurencySwapOverride, optional
        An object that contains the cross currency swap properties that can be overridden.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap
        IrSwap

    Examples
    --------
    >>> swap_from_ccs = create_from_ccs_template(template_reference = "LSEG/CNUSQMSRBS")
    >>> print(swap_from_ccs.definition)
    {'firstLeg': {'rate': {'interestRateType': 'FixedRate', 'rate': {'value': 0.0, 'unit': 'Percentage'}}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['CHN', 'USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['CHN', 'USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'CNY', 'amount': 10000000.0, 'initialPrincipalExchange': False, 'finalPrincipalExchange': True, 'interimPrincipalExchange': False, 'repaymentCurrency': 'CNY'}, 'settlement': {'currency': 'USD'}, 'payer': 'Party1', 'receiver': 'Party2'}, 'secondLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/USD_SOFR_ON', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['CHN', 'USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['CHN', 'USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'USD', 'initialPrincipalExchange': False, 'finalPrincipalExchange': True, 'interimPrincipalExchange': False, 'repaymentCurrency': 'USD'}, 'settlement': {'currency': 'USD'}, 'payer': 'Party2', 'receiver': 'Party1'}}

    """

    try:
        logger.info("Calling create_from_ccs_template")

        response = Client().ir_swaps_resource.create_irs_from_ccs_template(
            fields=fields, template_reference=template_reference, overrides=overrides
        )

        output = response.data
        logger.info("Called create_from_ccs_template")

        return IrSwap(output)
    except Exception as err:
        logger.error("Error create_from_ccs_template")
        check_exception_and_raise(err, logger)


def create_from_leg_template(
    *, first_leg_reference: str, second_leg_reference: str, fields: Optional[str] = None
) -> IrSwap:
    """
    Create an interest rate swap instance from two interest rate leg templates.
    This user-defined instrument includes all trade-specific details (e.g., fixed rate, spread, start date, end date), and is typically based on a general template available via the Instrument Template API.

    Parameters
    ----------
    first_leg_reference : str
        The identifier of the template for the instrument's first leg (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    second_leg_reference : str
        The identifier of the template for the instrument's second leg (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap
        IrSwap

    Examples
    --------
    >>> swap_from_leg = create_from_leg_template(first_leg_reference = "LSEG/EUR_AB3E_FLT", second_leg_reference = "LSEG/EUR_AB3E_FXD")
    >>> print(swap_from_leg.definition)
    {'firstLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/EUR_EURIBOR_3M', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodStartDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['EMU'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': ['EMU'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'EUR', 'amount': 10000000.0, 'initialPrincipalExchange': False, 'finalPrincipalExchange': False, 'interimPrincipalExchange': False, 'repaymentCurrency': 'EUR'}, 'payer': 'Party2', 'receiver': 'Party1'}, 'secondLeg': {'rate': {'interestRateType': 'FixedRate', 'rate': {'value': 0.0, 'unit': 'Percentage'}}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Annual', 'businessDayAdjustment': {'calendars': ['EMU'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': ['EMU'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_30_360', 'accrualDayCount': 'Dcb_30_360', 'principal': {'currency': 'EUR', 'amount': 10000000.0, 'initialPrincipalExchange': False, 'finalPrincipalExchange': False, 'interimPrincipalExchange': False, 'repaymentCurrency': 'EUR'}, 'payer': 'Party1', 'receiver': 'Party2'}}

    """

    try:
        logger.info("Calling create_from_leg_template")

        response = Client().ir_swaps_resource.create_irs_from_leg_template(
            fields=fields,
            first_leg_reference=first_leg_reference,
            second_leg_reference=second_leg_reference,
        )

        output = response.data
        logger.info("Called create_from_leg_template")

        return IrSwap(output)
    except Exception as err:
        logger.error("Error create_from_leg_template")
        check_exception_and_raise(err, logger)


def create_from_tbs_template(
    *,
    template_reference: str,
    overrides: Optional[TenorBasisSwapOverride] = None,
    fields: Optional[str] = None,
) -> IrSwap:
    """
    Create an interest rate swap instance from a tenor basis swap template.
    This user-defined instrument includes all trade-specific details (e.g., fixed rate, spread, start date, end date), and is typically based on a general template available via the Instrument Template API.

    Parameters
    ----------
    template_reference : str
        "The identifier of the tenor basis swap template (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    overrides : TenorBasisSwapOverride, optional
        An object that contains the tenor basis swap properties that can be overridden.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap
        IrSwap

    Examples
    --------
    >>> swap_from_tbs = create_from_tbs_template(template_reference = "LSEG/CBS_USDSR3LIMM")
    >>> print(swap_from_tbs.definition)
    {'firstLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/USD_SOFR_ON', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '0D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'USD', 'amount': 10000000.0, 'initialPrincipalExchange': False, 'finalPrincipalExchange': False, 'interimPrincipalExchange': False, 'repaymentCurrency': 'USD'}, 'payer': 'Party1', 'receiver': 'Party2'}, 'secondLeg': {'rate': {'interestRateType': 'FloatingRate', 'index': 'LSEG/USD_LIBOR_3M', 'spreadSchedule': [{'rate': {'value': 0.0, 'unit': 'BasisPoint'}}], 'resetDates': {'offset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': [], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodStartDate', 'direction': 'Backward'}}, 'leverage': 1.0}, 'interestPeriods': {'startDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '0D', 'referenceDate': 'SpotDate'}, 'endDate': {'dateType': 'RelativeAdjustableDate', 'tenor': '10Y', 'referenceDate': 'StartDate'}, 'frequency': 'Quarterly', 'businessDayAdjustment': {'calendars': ['USA'], 'convention': 'ModifiedFollowing'}, 'rollConvention': 'Same'}, 'paymentOffset': {'tenor': '2D', 'businessDayAdjustment': {'calendars': ['USA'], 'convention': 'ModifiedFollowing'}, 'referenceDate': 'PeriodEndDate', 'direction': 'Forward'}, 'couponDayCount': 'Dcb_Actual_360', 'accrualDayCount': 'Dcb_Actual_360', 'principal': {'currency': 'USD', 'amount': 10000000.0, 'initialPrincipalExchange': False, 'finalPrincipalExchange': False, 'interimPrincipalExchange': False, 'repaymentCurrency': 'USD'}, 'payer': 'Party2', 'receiver': 'Party1'}}

    """

    try:
        logger.info("Calling create_from_tbs_template")

        response = Client().ir_swaps_resource.create_irs_from_tbs_template(
            fields=fields, template_reference=template_reference, overrides=overrides
        )

        output = response.data
        logger.info("Called create_from_tbs_template")

        return IrSwap(output)
    except Exception as err:
        logger.error("Error create_from_tbs_template")
        check_exception_and_raise(err, logger)


def create_from_vanilla_irs_template(
    *,
    template_reference: str,
    overrides: Optional[VanillaIrsOverride] = None,
    fields: Optional[str] = None,
) -> IrSwap:
    """
    Create an interest rate swap instance from a vanilla IRS template.
    This user-defined instrument includes all trade-specific details (e.g., fixed rate, spread, start date, end date), and is typically based on a general template available via the Instrument Template API.

    Parameters
    ----------
    template_reference : str
        "The identifier of the vanilla interest rate swap template (GUID or URI).
        Note that a URI must be at least 2 and at most 102 characters long, start with an alphanumeric character, and contain only alphanumeric characters, slashes and underscores.
    overrides : VanillaIrsOverride, optional
        An object that contains interest rate swap properties that can be overridden.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap
        IrSwap

    Examples
    --------
    >>> # build the swap from 'LSEG/OIS_SOFR' template
    >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
    >>>
    >>> fwd_start_sofr_def = IrSwapDefinitionInstrument(definition = fwd_start_sofr.definition)
    >>>
    >>> print(js.dumps(fwd_start_sofr_def.as_dict(), indent=4))
    {
        "definition": {
            "firstLeg": {
                "rate": {
                    "interestRateType": "FixedRate",
                    "rate": {
                        "value": 0.0,
                        "unit": "Percentage"
                    }
                },
                "interestPeriods": {
                    "startDate": {
                        "dateType": "RelativeAdjustableDate",
                        "tenor": "0D",
                        "referenceDate": "SpotDate"
                    },
                    "endDate": {
                        "dateType": "RelativeAdjustableDate",
                        "tenor": "10Y",
                        "referenceDate": "StartDate"
                    },
                    "frequency": "Annual",
                    "businessDayAdjustment": {
                        "calendars": [
                            "USA"
                        ],
                        "convention": "NextBusinessDay"
                    },
                    "rollConvention": "Same"
                },
                "paymentOffset": {
                    "tenor": "2D",
                    "businessDayAdjustment": {
                        "calendars": [
                            "USA"
                        ],
                        "convention": "NextBusinessDay"
                    },
                    "referenceDate": "PeriodEndDate",
                    "direction": "Forward"
                },
                "couponDayCount": "Dcb_Actual_360",
                "accrualDayCount": "Dcb_Actual_360",
                "principal": {
                    "currency": "USD",
                    "amount": 10000000.0,
                    "initialPrincipalExchange": false,
                    "finalPrincipalExchange": false,
                    "interimPrincipalExchange": false,
                    "repaymentCurrency": "USD"
                },
                "payer": "Party1",
                "receiver": "Party2"
            },
            "secondLeg": {
                "rate": {
                    "interestRateType": "FloatingRate",
                    "index": "LSEG/USD_SOFR_ON",
                    "spreadSchedule": [
                        {
                            "rate": {
                                "value": 0.0,
                                "unit": "BasisPoint"
                            }
                        }
                    ],
                    "resetDates": {
                        "offset": {
                            "tenor": "0D",
                            "businessDayAdjustment": {
                                "calendars": [],
                                "convention": "ModifiedFollowing"
                            },
                            "referenceDate": "PeriodEndDate",
                            "direction": "Backward"
                        }
                    },
                    "leverage": 1.0
                },
                "interestPeriods": {
                    "startDate": {
                        "dateType": "RelativeAdjustableDate",
                        "tenor": "0D",
                        "referenceDate": "SpotDate"
                    },
                    "endDate": {
                        "dateType": "RelativeAdjustableDate",
                        "tenor": "10Y",
                        "referenceDate": "StartDate"
                    },
                    "frequency": "Annual",
                    "businessDayAdjustment": {
                        "calendars": [
                            "USA"
                        ],
                        "convention": "NextBusinessDay"
                    },
                    "rollConvention": "Same"
                },
                "paymentOffset": {
                    "tenor": "2D",
                    "businessDayAdjustment": {
                        "calendars": [
                            "USA"
                        ],
                        "convention": "NextBusinessDay"
                    },
                    "referenceDate": "PeriodEndDate",
                    "direction": "Forward"
                },
                "couponDayCount": "Dcb_Actual_360",
                "accrualDayCount": "Dcb_Actual_360",
                "principal": {
                    "currency": "USD",
                    "amount": 10000000.0,
                    "initialPrincipalExchange": false,
                    "finalPrincipalExchange": false,
                    "interimPrincipalExchange": false,
                    "repaymentCurrency": "USD"
                },
                "payer": "Party2",
                "receiver": "Party1"
            }
        }
    }

    """

    try:
        logger.info("Calling create_from_vanilla_irs_template")

        response = Client().ir_swaps_resource.create_irs_from_vanilla_irs_template(
            fields=fields, template_reference=template_reference, overrides=overrides
        )

        output = response.data
        logger.info("Called create_from_vanilla_irs_template")

        return IrSwap(output)
    except Exception as err:
        logger.error("Error create_from_vanilla_irs_template")
        check_exception_and_raise(err, logger)


def _delete_by_id(instrument_id: str) -> bool:
    """
    Delete a IrSwap stored on the platform. The IrSwap can be identified either by its unique ID (UUID/GUID format) or by its location path (space/name).

    Parameters
    ----------
    instrument_id : str
        The instrument identifier.

    Returns
    --------
    bool


    Examples
    --------


    """

    try:
        logger.info(f"Deleting IrSwap with id: {instrument_id}")
        Client().ir_swap_resource.delete(instrument_id=instrument_id)
        logger.info(f"Deleted IrSwap with id: {instrument_id}")

        return True
    except Exception as err:
        logger.error(f"Error deleting IrSwap with id: {instrument_id}")
        check_exception_and_raise(err, logger)


def _load_by_id(instrument_id: str, fields: Optional[str] = None) -> IrSwap:
    """
    Access a IrSwap stored on the platform (read). The IrSwap can be identified either by its unique ID (UUID/GUID format) or by its location path (space/name).

    Parameters
    ----------
    instrument_id : str
        The instrument identifier.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    IrSwap


    Examples
    --------


    """

    try:
        logger.info(f"Opening IrSwap with id: {instrument_id}")

        response = Client().ir_swap_resource.read(instrument_id=instrument_id, fields=fields)

        output = IrSwap(response.data.definition, response.data.description)

        output._id = response.data.id

        output._location = response.data.location

        return output
    except Exception as err:
        logger.error("Error opening IrSwap:")
        check_exception_and_raise(err, logger)


def search(
    *,
    item_per_page: Optional[int] = None,
    page: Optional[int] = None,
    spaces: Optional[list[str]] = None,
    names: Optional[list[str]] = None,
    space_name_sort_order: Optional[Union[str, SortingOrderEnum]] = None,
    tags: Optional[list[str]] = None,
    fields: Optional[str] = None,
) -> list[IrSwapAsCollectionItem]:
    """
    List the IrSwaps stored on the platform that are available depending on user permissions. Use search filters to find specific resources by location (names, spaces) and/or tags, and field filters to control which properties are included in the response.

    Parameters
    ----------
    item_per_page : int, optional
        A parameter used to select the number of items allowed per page. The valid range is 1-500. If not provided, 50 will be used.
    page : int, optional
        A parameter used to define the page number to display.
    spaces : list[str], optional
        A parameter used to search for platform resources stored in a given space. Space is like a namespace where resources are stored. By default there are two spaces:
        LSEG is reserved for LSEG maintained resources, HOME is reserved for user's default space.
        If space is not specified, it will search within all spaces.
    names : list[str], optional
        A parameter used to search for platform resources with given names.
    space_name_sort_order : Union[str, SortingOrderEnum], optional
        A parameter used to sort platform resources by name based on a defined order.
    tags : list[str], optional
        A parameter used to search for platform resources with given tags.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'

    Returns
    --------
    list[IrSwapAsCollectionItem]
        Defines a lightweight resource reference without the complete definition.
        Used in collection responses to efficiently list multiple resources without including complete definitions.

    Examples
    --------
    >>> # execute the search of IR swaps
    >>> available_swaps = search()
    >>>
    >>> print(available_swaps)
    [{'type': 'IrSwap', 'id': 'b93c30e7-1f96-4d88-81b5-7dc42b5c1ad2', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952237147'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '66432c69-05ee-465e-811c-9b7c9fc096b5', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952237658'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'f9ac4641-dc56-4bd9-b259-5720d31a8956', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952249789'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '00b1e6d1-7477-47b5-a73d-b7a3637d49db', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952250289'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '03c486df-2a75-428f-a94a-240148c2d81d', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952250797'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '7efa6c18-6a0d-4bc0-ace9-37c84068a24d', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952256633'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'ee384aed-2d67-4c97-b8cd-6d892537dca1', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765952257415'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'c3fe2c58-f91c-4c16-8bc0-01bd4d231360', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957373401'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '70bcc40c-4d6b-4f93-bf72-da374df9b97d', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957374020'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'c7a064c1-573e-4ea6-9a1e-f855d535bf92', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957386387'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '0797d5da-e7de-4505-9bdb-f946bd583ed0', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957386848'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '8d74a872-3130-486a-bc5b-5cdd4ce20b2a', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957387278'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '0c91dd38-a7bd-4f33-8b68-fd6b0308ca75', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957393213'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '3c2fd73b-62d0-464b-84df-4f154405e24d', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765957394016'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '09f0e93d-5dd2-4d9b-b0fb-95719ed596e4', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964754922'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '3b179bb7-13d6-4e0a-8985-c72c04b736bd', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964755427'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'a208894e-7ea5-47e9-ba0f-7f9c50b954ee', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964767842'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '42753798-3a71-44cb-af88-34d6eeac317d', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964768294'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '4058d7f3-04cc-4eb9-960a-a26ceda33943', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964768803'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'd302997a-cbd1-4f50-a4b9-6f0e839eb9ae', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964774572'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'a7aa6aa3-cf25-4b22-a172-89585df7c2ef', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765964775489'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '3ffbafdc-4e86-4ef6-bd20-8da8897deff1', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966971816'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'fb42d1c7-3b84-41f7-b3a9-1b8b6341666b', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966972295'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '0a71c2a0-cddd-413d-b9c2-5aea49c9ccdf', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966984467'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'df1eeda9-2f42-4880-94e1-4e057f90dcbf', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966984912'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'f3a01987-4afb-4dcb-a9a2-9d056a6de38c', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966985457'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '539297c8-cd6e-41c2-aec4-af4c008a8fb8', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966991331'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '69d2af87-f5b2-48b3-9866-9a5e2c9c6683', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765966992158'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '52d66e0d-98b4-49ee-a27e-f3c7db58bc64', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969004041'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'be433016-fb3c-4dcc-9a79-6760fcec9fe1', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969004607'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '73bb881f-75ef-420a-b0fe-c2eb78699cb3', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969016716'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '6515040d-0567-4b13-b698-7b927e7b9696', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969017207'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'ddfa9d0c-d82a-46c1-af64-c4f436e1dda1', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969017643'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '97e8f8e9-c6bd-4426-b509-9c67904c5558', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969023572'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '4d653534-93b6-41f7-ad65-a347169ca553', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1765969024285'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '1903c317-ab0c-4d50-a973-2bf2f7c2e2f4', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131977490'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '296ab2ec-b1ad-4c07-b7c4-a5a65c2215ac', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131977975'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'ca010fbe-a4ed-4afd-942f-8e40e0999243', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131990296'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '167a3bdf-20fb-4c0b-a068-b1e3b5e89512', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131990740'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '65113da3-f4cf-42a4-9987-3daefaa5dd8b', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131991236'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '51cbde76-1598-4bdc-89a0-ff4f0cc77cf4', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131997157'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'fda634b6-9b75-48e7-8ae0-0eabe4ca2767', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766131997948'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '3b603b3f-9033-4749-8209-c72d248a3855', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137477220'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '498cbf4f-173b-49cf-b586-61f8ce191b1c', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137477689'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '643b23a4-c4b8-44a6-b46d-a3950434ccf0', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137501069'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': 'ad944d65-d60d-4e5c-8a9b-4a7f96bff383', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137501533'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '0ca1b579-02f7-4998-b59d-0a2e7c32fa29', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137502167'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '419b913d-a228-42d5-b749-89fb1730e99f', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137508157'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '55c49890-e5ef-4f0b-937c-2b96ca9b8dda', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766137509047'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}, {'type': 'IrSwap', 'id': '33e32b7b-0ac3-4a4a-b4e6-88fb909396bc', 'location': {'space': 'HOME', 'name': 'GatewayIrSwap1766147665222'}, 'description': {'summary': 'Gateway integration IR swap', 'tags': ['Gateway']}}]

    """

    try:
        logger.info("Calling search")

        response = Client().ir_swaps_resource.list(
            item_per_page=item_per_page,
            page=page,
            spaces=spaces,
            names=names,
            space_name_sort_order=space_name_sort_order,
            tags=tags,
            fields=fields,
        )

        output = response.data
        logger.info("Called search")

        return output
    except Exception as err:
        logger.error("Error search.")
        check_exception_and_raise(err, logger)


def solve(
    *,
    definitions: list[IrSwapDefinitionInstrument],
    pricing_preferences: Optional[IrPricingParameters] = None,
    market_data: Optional[MarketData] = None,
    return_market_data: Optional[bool] = None,
    fields: Optional[str] = None,
    request_pattern: Optional[Union[str, RequestPatternEnum]] = RequestPatternEnum.SYNC,
) -> Union[IrSwapInstrumentSolveResponseFieldsResponseData, AsyncRequestResponse]:
    """
    Calculate analytics for one or more swaps not stored on the platform, by solving a variable parameter (e.g., fixed rate) provided in the request,
    so that a specified property (e.g., market value, duration) matches a target value.

    Parameters
    ----------
    definitions : list[IrSwapDefinitionInstrument]
        Array (collection) of instrument definitions for the analytics computation.
    pricing_preferences : IrPricingParameters, optional
        Configuration parameters that control the analytics computation.
    market_data : MarketData, optional
        Market data inputs used for the analytics computation.
        Can include rates, curves, surfaces, quotes, and other relevant market data.
    return_market_data : bool, optional
        Controls whether market data used in computations should be included in the response.
        Set to true to include market data details in the response.
        Defaults to false.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'
    request_pattern : Union[str, RequestPatternEnum], optional
        Header indicating whether the request is synchronous or asynchronous polling.
        When asyncPolling is used, the operation should return a 202 Accepted response with a Location header to poll for the final result.

    Returns
    --------
    Union[IrSwapInstrumentSolveResponseFieldsResponseData, AsyncRequestResponse]


    Examples
    --------
    >>> # build the swap from 'LSEG/OIS_SOFR' template
    >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
    >>>
    >>> # prepare the Definition Instrument
    >>> fwd_start_sofr_def = IrSwapDefinitionInstrument(definition = fwd_start_sofr.definition)
    >>>
    >>> # set a solving variable between first and second leg and Fixed Rate or Spread
    >>> solving_variable = IrSwapSolvingVariable(leg='FirstLeg', name='FixedRate')
    >>>
    >>> # Apply solving target(s)
    >>> solving_target=IrSwapSolvingTarget(market_value=IrMeasure(value=0.0))
    >>>
    >>> # Setup the solving parameter object
    >>> solving_parameters = IrSwapSolvingParameters(variable=solving_variable, target=solving_target)
    >>>
    >>> # instantiate pricing parameters
    >>> pricing_parameters = IrPricingParameters(solving_parameters=solving_parameters)
    >>>
    >>> # solve the swap par rate
    >>> solving_response_general = solve(
    >>>     definitions=[fwd_start_sofr_def],
    >>>     pricing_preferences=pricing_parameters
    >>>     )
    >>>
    >>> print(js.dumps(solving_response_general.as_dict(), indent=4))
    {
        "pricingPreferences": {
            "valuationDate": "2026-02-13",
            "reportCurrency": "USD"
        },
        "analytics": [
            {
                "solving": {
                    "result": 3.7046893212640555
                },
                "description": {
                    "instrumentTag": "",
                    "instrumentDescription": "Pay USD Annual 3.7% vs Receive USD Annual +0bp SOFR 2036-02-19",
                    "startDate": "2026-02-18",
                    "endDate": "2036-02-19",
                    "tenor": "10Y"
                },
                "valuation": {
                    "accrued": {
                        "value": 0.0,
                        "percent": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    },
                    "marketValue": {
                        "value": -9.31322574615479e-10,
                        "dealCurrency": {
                            "value": -9.31322574615479e-10,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -9.31322574615479e-10,
                            "currency": "USD"
                        }
                    },
                    "cleanMarketValue": {
                        "value": -9.31322574615479e-10,
                        "dealCurrency": {
                            "value": -9.31322574615479e-10,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -9.31322574615479e-10,
                            "currency": "USD"
                        }
                    }
                },
                "risk": {
                    "duration": {
                        "value": -8.50972758988991
                    },
                    "modifiedDuration": {
                        "value": -8.19702875855138
                    },
                    "benchmarkHedgeNotional": {
                        "value": -9926401.55504069,
                        "currency": "USD"
                    },
                    "annuity": {
                        "value": -8394.47615887458,
                        "dealCurrency": {
                            "value": -8394.47615887458,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -8394.47615887458,
                            "currency": "USD"
                        }
                    },
                    "dv01": {
                        "value": -8191.61698718183,
                        "bp": -8.19161698718183,
                        "dealCurrency": {
                            "value": -8191.61698718183,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -8191.61698718183,
                            "currency": "USD"
                        }
                    },
                    "pv01": {
                        "value": -8191.61698717717,
                        "bp": -8.19161698717717,
                        "dealCurrency": {
                            "value": -8191.61698717717,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": -8191.61698717717,
                            "currency": "USD"
                        }
                    },
                    "br01": {
                        "value": 0.0,
                        "dealCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "reportCurrency": {
                            "value": 0.0,
                            "currency": "USD"
                        }
                    }
                },
                "firstLeg": {
                    "description": {
                        "legTag": "PaidLeg",
                        "legDescription": "Pay USD Annual 3.7%",
                        "interestType": "Fixed",
                        "currency": "USD",
                        "startDate": "2026-02-18",
                        "endDate": "2036-02-19",
                        "index": ""
                    },
                    "valuation": {
                        "accrued": {
                            "value": 0.0,
                            "percent": 0.0,
                            "dealCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            }
                        },
                        "marketValue": {
                            "value": 3109892.618338711,
                            "dealCurrency": {
                                "value": 3109892.618338711,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 3109892.618338711,
                                "currency": "USD"
                            }
                        },
                        "cleanMarketValue": {
                            "value": 3109892.618338711,
                            "dealCurrency": {
                                "value": 3109892.618338711,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 3109892.618338711,
                                "currency": "USD"
                            }
                        }
                    },
                    "risk": {
                        "duration": {
                            "value": 8.50972758988991
                        },
                        "modifiedDuration": {
                            "value": 8.214714976140979
                        },
                        "benchmarkHedgeNotional": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "annuity": {
                            "value": 8394.476158874575,
                            "dealCurrency": {
                                "value": 8394.476158874575,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 8394.476158874575,
                                "currency": "USD"
                            }
                        },
                        "dv01": {
                            "value": 8209.29152812995,
                            "bp": 8.20929152812995,
                            "dealCurrency": {
                                "value": 8209.29152812995,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 8209.29152812995,
                                "currency": "USD"
                            }
                        },
                        "pv01": {
                            "value": 1564.9220031267032,
                            "bp": 1.5649220031267033,
                            "dealCurrency": {
                                "value": 1564.9220031267032,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 1564.9220031267032,
                                "currency": "USD"
                            }
                        },
                        "br01": {
                            "value": 0.0,
                            "dealCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            }
                        }
                    },
                    "cashflows": [
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.9654899899332677,
                            "startDate": "2026-02-18",
                            "endDate": "2027-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.486855865377292,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2027-02-22"
                            },
                            "amount": {
                                "value": -375614.3339614945,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.935558067831983,
                            "startDate": "2027-02-18",
                            "endDate": "2028-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.340166738650341,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2028-02-23"
                            },
                            "amount": {
                                "value": -375614.3339614945,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.9053282881087193,
                            "startDate": "2028-02-18",
                            "endDate": "2029-02-20",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.345969095172574,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2029-02-21"
                            },
                            "amount": {
                                "value": -378701.57506254787,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8745318381700324,
                            "startDate": "2029-02-20",
                            "endDate": "2030-02-19",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.3919288007708603,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2030-02-20"
                            },
                            "amount": {
                                "value": -374585.25359447673,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8434332000905406,
                            "startDate": "2030-02-19",
                            "endDate": "2031-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.4506800905624857,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2031-02-20"
                            },
                            "amount": {
                                "value": -374585.25359447673,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8119278355950935,
                            "startDate": "2031-02-18",
                            "endDate": "2032-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.521934621541556,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2032-02-20"
                            },
                            "amount": {
                                "value": -375614.3339614945,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7801387372913783,
                            "startDate": "2032-02-18",
                            "endDate": "2033-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.5962339575009494,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2033-02-23"
                            },
                            "amount": {
                                "value": -376643.4143285123,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7490781399704934,
                            "startDate": "2033-02-18",
                            "endDate": "2034-02-21",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.665898617196661,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2034-02-22"
                            },
                            "amount": {
                                "value": -378701.57506254787,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7184725468300216,
                            "startDate": "2034-02-21",
                            "endDate": "2035-02-20",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.7326959360830747,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2035-02-21"
                            },
                            "amount": {
                                "value": -374585.25359447673,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.7046893212640555,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.6883505268226094,
                            "startDate": "2035-02-20",
                            "endDate": "2036-02-19",
                            "remainingNotional": 0.0,
                            "interestRateType": "FixedRate",
                            "zeroRate": {
                                "value": 3.797761977499059,
                                "unit": "Percentage"
                            },
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2036-02-20"
                            },
                            "amount": {
                                "value": -374585.25359447673,
                                "currency": "USD"
                            },
                            "payer": "Party1",
                            "receiver": "Party2",
                            "occurrence": "Future"
                        }
                    ]
                },
                "secondLeg": {
                    "description": {
                        "legTag": "ReceivedLeg",
                        "legDescription": "Receive USD Annual +0bp SOFR",
                        "interestType": "Float",
                        "currency": "USD",
                        "startDate": "2026-02-18",
                        "endDate": "2036-02-19",
                        "index": "SOFR"
                    },
                    "valuation": {
                        "accrued": {
                            "value": 0.0,
                            "percent": 0.0,
                            "dealCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            }
                        },
                        "marketValue": {
                            "value": 3109892.61833871,
                            "dealCurrency": {
                                "value": 3109892.61833871,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 3109892.61833871,
                                "currency": "USD"
                            }
                        },
                        "cleanMarketValue": {
                            "value": 3109892.61833871,
                            "dealCurrency": {
                                "value": 3109892.61833871,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 3109892.61833871,
                                "currency": "USD"
                            }
                        }
                    },
                    "risk": {
                        "duration": {
                            "value": 0.0
                        },
                        "modifiedDuration": {
                            "value": 0.01768621758959935
                        },
                        "benchmarkHedgeNotional": {
                            "value": 0.0,
                            "currency": "USD"
                        },
                        "annuity": {
                            "value": 0.0,
                            "dealCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            }
                        },
                        "dv01": {
                            "value": 17.67454094812274,
                            "bp": 0.01767454094812274,
                            "dealCurrency": {
                                "value": 17.67454094812274,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 17.67454094812274,
                                "currency": "USD"
                            }
                        },
                        "pv01": {
                            "value": -6626.694984050468,
                            "bp": -6.626694984050467,
                            "dealCurrency": {
                                "value": -6626.694984050468,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": -6626.694984050468,
                                "currency": "USD"
                            }
                        },
                        "br01": {
                            "value": 0.0,
                            "dealCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            },
                            "reportCurrency": {
                                "value": 0.0,
                                "currency": "USD"
                            }
                        }
                    },
                    "cashflows": [
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.4385000001265,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.9654899899332677,
                            "startDate": "2026-02-18",
                            "endDate": "2027-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.486855865377292,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2027-02-18",
                                    "accrualStartDate": "2026-02-18",
                                    "couponRate": {
                                        "value": 3.4385,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2026-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.4385,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2027-02-22"
                            },
                            "amount": {
                                "value": 348625.69445727015,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.1458929137358003,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.935558067831983,
                            "startDate": "2027-02-18",
                            "endDate": "2028-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.340166738650341,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2028-02-18",
                                    "accrualStartDate": "2027-02-18",
                                    "couponRate": {
                                        "value": 3.1458929,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2027-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.1458929,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2028-02-23"
                            },
                            "amount": {
                                "value": 318958.58708710194,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.3015030977682005,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.9053282881087193,
                            "startDate": "2028-02-18",
                            "endDate": "2029-02-20",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.345969095172574,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2029-02-20",
                                    "accrualStartDate": "2028-02-18",
                                    "couponRate": {
                                        "value": 3.3015032,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2028-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.3015032,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2029-02-21"
                            },
                            "amount": {
                                "value": 337486.98332741606,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.4823370510398,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8745318381700324,
                            "startDate": "2029-02-20",
                            "endDate": "2030-02-19",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.3919288007708603,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2030-02-19",
                                    "accrualStartDate": "2029-02-20",
                                    "couponRate": {
                                        "value": 3.482337,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2029-02-20",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.482337,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2030-02-20"
                            },
                            "amount": {
                                "value": 352102.9684940242,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.6357262541897,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8434332000905406,
                            "startDate": "2030-02-19",
                            "endDate": "2031-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.4506800905624857,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2031-02-18",
                                    "accrualStartDate": "2030-02-19",
                                    "couponRate": {
                                        "value": 3.6357262,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2030-02-19",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.6357262,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2031-02-20"
                            },
                            "amount": {
                                "value": 367612.32125695853,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.8261886420758,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.8119278355950935,
                            "startDate": "2031-02-18",
                            "endDate": "2032-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.521934621541556,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2032-02-18",
                                    "accrualStartDate": "2031-02-18",
                                    "couponRate": {
                                        "value": 3.8261886,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2031-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.8261886,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2032-02-20"
                            },
                            "amount": {
                                "value": 387933.01509935193,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 3.9735136507102005,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7801387372913783,
                            "startDate": "2032-02-18",
                            "endDate": "2033-02-18",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.5962339575009494,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2033-02-18",
                                    "accrualStartDate": "2032-02-18",
                                    "couponRate": {
                                        "value": 3.9735136,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2032-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 3.9735136,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2033-02-23"
                            },
                            "amount": {
                                "value": 403973.8878222037,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 4.1008735422327005,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7490781399704934,
                            "startDate": "2033-02-18",
                            "endDate": "2034-02-21",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.665898617196661,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2034-02-21",
                                    "accrualStartDate": "2033-02-18",
                                    "couponRate": {
                                        "value": 4.1008735,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2033-02-18",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 4.1008735,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2034-02-22"
                            },
                            "amount": {
                                "value": 419200.40653934266,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 4.2126924593093005,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.7184725468300216,
                            "startDate": "2034-02-21",
                            "endDate": "2035-02-20",
                            "remainingNotional": 10000000.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.7326959360830747,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2035-02-20",
                                    "accrualStartDate": "2034-02-21",
                                    "couponRate": {
                                        "value": 4.2126923,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2034-02-21",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 4.2126923,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2035-02-21"
                            },
                            "amount": {
                                "value": 425950.01533016254,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        },
                        {
                            "paymentType": "Interest",
                            "annualRate": {
                                "value": 4.3275784562810005,
                                "unit": "Percentage"
                            },
                            "discountFactor": 0.6883505268226094,
                            "startDate": "2035-02-20",
                            "endDate": "2036-02-19",
                            "remainingNotional": 0.0,
                            "interestRateType": "FloatingRate",
                            "zeroRate": {
                                "value": 3.797761977499059,
                                "unit": "Percentage"
                            },
                            "indexFixings": [
                                {
                                    "accrualEndDate": "2036-02-19",
                                    "accrualStartDate": "2035-02-20",
                                    "couponRate": {
                                        "value": 4.3275785,
                                        "unit": "Percentage"
                                    },
                                    "fixingDate": "2035-02-20",
                                    "forwardSource": "ZcCurve",
                                    "referenceRate": {
                                        "value": 4.3275785,
                                        "unit": "Percentage"
                                    },
                                    "spreadBp": 0.0
                                }
                            ],
                            "date": {
                                "dateType": "AdjustableDate",
                                "date": "2036-02-20"
                            },
                            "amount": {
                                "value": 437566.2661350789,
                                "currency": "USD"
                            },
                            "payer": "Party2",
                            "receiver": "Party1",
                            "occurrence": "Projected"
                        }
                    ]
                }
            }
        ]
    }

    """

    try:
        logger.info("Calling solve")

        response = check_async_request_response(
            Client().ir_swaps_resource.solve(
                fields=fields,
                request_pattern=request_pattern,
                definitions=definitions,
                pricing_preferences=pricing_preferences,
                market_data=market_data,
                return_market_data=return_market_data,
            )
        )

        output = response
        logger.info("Called solve")

        return output
    except Exception as err:
        logger.error("Error solve.")
        check_exception_and_raise(err, logger)


def solve_result(*, operation_id: str) -> IrSwapInstrumentSolveResponseFieldsResponseData:
    """
    Get the response of the $solve async action once completed

    Parameters
    ----------
    operation_id : str
        The operation identifier.

    Returns
    --------
    IrSwapInstrumentSolveResponseFieldsResponseData


    Examples
    --------


    """

    try:
        logger.info("Calling solve_result")

        response = Client().ir_swaps_resource.solve_result(operation_id=operation_id)

        output = response.data
        logger.info("Called solve_result")

        return output
    except Exception as err:
        logger.error("Error solve_result.")
        check_exception_and_raise(err, logger)


def value(
    *,
    definitions: list[IrSwapDefinitionInstrument],
    pricing_preferences: Optional[IrPricingParameters] = None,
    market_data: Optional[MarketData] = None,
    return_market_data: Optional[bool] = None,
    fields: Optional[str] = None,
    request_pattern: Optional[Union[str, RequestPatternEnum]] = RequestPatternEnum.SYNC,
) -> Union[IrSwapInstrumentValuationResponseFieldsResponseData, AsyncRequestResponse]:
    """
    Calculate analytics for one or more swaps not stored on the platform, including valuation results, risk metrics, and other relevant measures.

    Parameters
    ----------
    definitions : list[IrSwapDefinitionInstrument]
        Array (collection) of instrument definitions for the analytics computation.
    pricing_preferences : IrPricingParameters, optional
        Configuration parameters that control the analytics computation.
    market_data : MarketData, optional
        Market data inputs used for the analytics computation.
        Can include rates, curves, surfaces, quotes, and other relevant market data.
    return_market_data : bool, optional
        Controls whether market data used in computations should be included in the response.
        Set to true to include market data details in the response.
        Defaults to false.
    fields : str, optional
        A parameter used to select the fields to return in response. If not provided, all fields will be returned.
        Some usage examples:
        1. Simply enumerating the fields, separating them by ',', e.g. 'fields=//please insert the selected fields here, e.g., field1, field2 //'
        2. Using parentheses to indicate nesting, e.g. 'fields= //please insert the selected field and subfields here, e.g., field1(subfield1, subfield2), field2(subfield3)//’
        3. Using forward slash '/' to indicate nesting, e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1/subfield1, field1/subfield2, field2/subfield3//’ (same result as example above)
        4. Operators can even be combined (forward slashes in brackets, not the way around), e.g. 'fields=//please insert the selected field and subfields here, e.g.,  field1(subfield1/subsubfield1), field2/subfield2//'
    request_pattern : Union[str, RequestPatternEnum], optional
        Header indicating whether the request is synchronous or asynchronous polling.
        When asyncPolling is used, the operation should return a 202 Accepted response with a Location header to poll for the final result.

    Returns
    --------
    Union[IrSwapInstrumentValuationResponseFieldsResponseData, AsyncRequestResponse]


    Examples
    --------
    >>> # build the swap from 'LSEG/OIS_SOFR' template
    >>> fwd_start_sofr = create_from_vanilla_irs_template(template_reference = "LSEG/OIS_SOFR")
    >>>
    >>> fwd_start_sofr_def = IrSwapDefinitionInstrument(definition = fwd_start_sofr.definition)
    >>>
    >>> # instantiate pricing parameters
    >>> pricing_parameters = IrPricingParameters()
    >>>
    >>> # value the swap
    >>> valuation_response = value(
    >>>     definitions=[fwd_start_sofr_def],
    >>>     pricing_preferences=pricing_parameters
    >>> )
    >>>
    >>> print(js.dumps(valuation_response.analytics[0].valuation.as_dict(), indent=4))
    {
        "accrued": {
            "value": 0.0,
            "percent": 0.0,
            "dealCurrency": {
                "value": 0.0,
                "currency": "USD"
            },
            "reportCurrency": {
                "value": 0.0,
                "currency": "USD"
            }
        },
        "marketValue": {
            "value": 3109807.92670901,
            "dealCurrency": {
                "value": 3109807.92670901,
                "currency": "USD"
            },
            "reportCurrency": {
                "value": 3109807.92670901,
                "currency": "USD"
            }
        },
        "cleanMarketValue": {
            "value": 3109807.92670901,
            "dealCurrency": {
                "value": 3109807.92670901,
                "currency": "USD"
            },
            "reportCurrency": {
                "value": 3109807.92670901,
                "currency": "USD"
            }
        }
    }

    """

    try:
        logger.info("Calling value")

        response = check_async_request_response(
            Client().ir_swaps_resource.value(
                fields=fields,
                request_pattern=request_pattern,
                definitions=definitions,
                pricing_preferences=pricing_preferences,
                market_data=market_data,
                return_market_data=return_market_data,
            )
        )

        output = response
        logger.info("Called value")

        return output
    except Exception as err:
        logger.error("Error value.")
        check_exception_and_raise(err, logger)


def value_result(*, operation_id: str) -> IrSwapInstrumentValuationResponseFieldsResponseData:
    """
    Get the response of the $value async action once completed

    Parameters
    ----------
    operation_id : str
        The operation identifier.

    Returns
    --------
    IrSwapInstrumentValuationResponseFieldsResponseData


    Examples
    --------


    """

    try:
        logger.info("Calling value_result")

        response = Client().ir_swaps_resource.value_result(operation_id=operation_id)

        output = response.data
        logger.info("Called value_result")

        return output
    except Exception as err:
        logger.error("Error value_result.")
        check_exception_and_raise(err, logger)


def load(
    *,
    resource_id: Optional[str] = None,
    name: Optional[str] = None,
    space: Optional[str] = None,
):
    """
    Load a IrSwap using its name and space

    Parameters
    ----------
    resource_id : str, optional
        The IrSwap id. Or the combination of the space and name of the resource with a slash, e.g. 'HOME/my_resource'.
        Required if name is not provided.
    name : str, optional
        The IrSwap name.
        Required if resource_id is not provided. The name parameter must be specified when the object is first created. Thereafter it is optional.
    space : str, optional
        The space where the IrSwap is stored. Space is like a namespace where resources are stored. By default there are two spaces:
        LSEG is reserved for LSEG maintained resources, HOME is reserved for user's default space. If space is not specified, HOME will be used.

    Returns
    -------
    IrSwap
        The IrSwap instance.

    Examples
    --------
    >>> # fetch all available swaps
    >>> available_swaps = search()
    >>>
    >>> # execute the load of a swap using the first element of previously fetched data
    >>> loaded_swap = load(resource_id=available_swaps[0].id)
    >>>
    >>> print(loaded_swap)
    <IrSwap space='HOME' name='GatewayIrSwap1765952237147' b93c30e7‥>

    """
    if not isinstance(resource_id, (str, type(None))):
        raise TypeError(f"Expected resource_id as a string, got {resource_id!r}")
    if resource_id:
        if name or space:
            logger.warn("resource_id argument received, name & space arguments are ignored")
        return _load_by_id(resource_id)
    if not name:
        raise ValueError("Either resource_id or name argument should be provided")
    logger.info(f"Load IrSwap {name} from space={space!r}")
    spaces = [space] if space else None
    result = search(names=[name], spaces=spaces)
    if not result:
        logger.error(f"IrSwap {name} not found in space={space!r}")
        raise ResourceNotFound(f"Resource IrSwap not found by identifier name={name} space={space}")
    elif not isinstance(result, list):
        raise LibraryException(f"Expected list of results, got {result}")
    elif len(result) > 1:
        logger.warn(f"Found more than one result for name={name!r} and space={space!r}, returning the first one")
    return _load_by_id(result[0].id)


def delete(
    *,
    resource_id: Optional[str] = None,
    name: Optional[str] = None,
    space: Optional[str] = None,
):
    """
    Delete IrSwap instance from the server.

    Parameters
    ----------
    resource_id : str, optional
        The IrSwap resource ID.
        Required if name is not provided.
    name : str, optional
        The IrSwap name.
        Required if resource_id is not provided.
    space : str, optional
        The space where the IrSwap is stored. Space is like a namespace where resources are stored. By default there are two spaces:
        LSEG is reserved for LSEG maintained resources, HOME is reserved for user's default space. If space is not specified, HOME will be used.

    Returns
    -------
    ServiceErrorResponse, optional
        Error response, if applicable, otherwise None

    Examples
    --------
    >>> # Let's delete the instrument we created in HOME space
    >>> from lseg_analytics.pricing.instruments.ir_swaps import delete
    >>>
    >>> swap_id = "SOFR_OIS_1Y2Y"
    >>>
    >>> delete(name=swap_id, space="HOME")
    True

    """
    if not isinstance(resource_id, (str, type(None))):
        raise TypeError(f"Expected resource_id as a string, got {resource_id!r}")
    if resource_id:
        if name or space:
            logger.warn("resource_id argument received, name & space arguments are ignored")
        return _delete_by_id(resource_id)
    if not name:
        raise ValueError("Either resource_id or name argument should be provided")
    logger.info(f"Delete IrSwap {name} from space={space!r}")
    spaces = [space] if space else None
    result = search(names=[name], spaces=spaces)
    if not result:
        logger.error(f"IrSwap {name} not found in space={space!r}")
        raise ResourceNotFound(f"Resource IrSwap not found by identifier name={name} space={space}")
    elif not isinstance(result, list):
        raise LibraryException(f"Expected list of results, got {result}")
    return _delete_by_id(result[0].id)
