> ## Documentation Index
> Fetch the complete documentation index at: https://docs.activeviam.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How to write your own collateral algorithm

> How an application adds a collateral algorithm to the PFE and xVA cubes through an ICollateralConfigurer bean, the ICollateralEvaluator contract and its inputs, how to replace a built-in algorithm, and how to select an algorithm per query or per CSA.

An application can add collateral algorithms to the cubes that use Netting Set Analytics. An algorithm decides how much collateral a credit support annex (CSA) holds at each time point. The library subtracts the collateral of the CSAs from the exposure of the master agreement. This page describes the configurer, the evaluator contract, and the ways to select an algorithm.

Understanding [collateral algorithms](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/collateral-evaluator-framework.md) is a prerequisite for this page.

## How does an application add an algorithm?

The application declares at most one `ICollateralConfigurer` bean. A second bean makes the application fail at startup. Declare the bean with a `static @Bean` method, because the cubes are built from what the configurer declares, so it cannot depend on a cube.

Netting Set Analytics calls the configurer once for each cube. The configurer receives an `ICollateralConfigurator`. Its `cube(String cubeName)` method returns the `ICollateralCubeConfigurator` of that cube, so each cube gets its own algorithms and cashflows. The name is the cube name that the cube properties return from `getName()`, which a `static @Bean` method can take as a parameter, for example `IPfeCubeProperties` or `IXvaCubeProperties`. Declarations made for a cube that the application does not have are ignored, so one configurer can serve applications that have only some of the cubes. When a name matches none of the cubes of the application, the application logs a warning at startup, because a misspelled or renamed cube would otherwise silently get no custom algorithm and no cashflows.

Within a cube, a later declaration of an algorithm with the same name replaces an earlier one, and a later call to `cashflows(...)` replaces an earlier one.

The `ICollateralCubeConfigurator` has the following methods:

| Method | What it does |
| - | - |
| `addEvaluator(ICollateralEvaluator)` | Adds an algorithm. |
| `addEvaluator(Function<ICollateralServices, ICollateralEvaluator>)` | Adds an algorithm built from the cube services. |
| `cashflows(Function<ICollateralServices, ICashflowsService>)` | Supplies the projected cashflows. See [Cashflow measures](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/cashflows.md). |

`ICollateralServices` has one method, `scenarioCount()`. It returns the number of scenarios of the cube, which is the length that every vector must have.

The following configurer adds the evaluator described in the next section and a cashflows service to the PFE cube:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration(proxyBeanMethods = false)
class CollateralCustomizationSnippetExample {
  @Bean
  static ICollateralConfigurer collateralConfigurer(final IPfeCubeProperties pfeProperties) {
    return configurator ->
        configurator
            .cube(pfeProperties.getName())
            .addEvaluator(new ThresholdCsaEvaluator())
            .cashflows(
                services ->
                    new ScheduledCashflows(
                        services.scenarioCount(),
                        Map.of("TRADE-1", Map.of(LocalDate.of(2025, Month.JANUARY, 31), 12_500d))));
  }
}
```

## What must an algorithm implement?

An algorithm implements `ICollateralEvaluator<T>`. The type `T` is the data point that the algorithm builds for each time point. It extends `CollateralEvaluationData.DataPoint`, which is serializable and returns its time point.

| Method | What it returns |
| - | - |
| `algoName()` | The name of the algorithm. It is the name of the member in the `Collateral Algorithm` hierarchy. |
| `skipTimePoint(asOfDate, timePoint)` | `true` to leave the time point out. The balance of the CSA at that time point is then null, and so is the collateralized exposure of the master agreement the CSA belongs to. The default is `false`. |
| `buildDataPoint(timePoint, vectors)` | The data point of the time point, or null to leave the time point out. `vectors` holds one vector, the gross MtM sum of the CSA. |
| `evaluateCollateralBalance(asOfDate, timePoint, data, csaParameters, displayCurrency, marketDataSet)` | The collateral balance of the CSA at the time point, one value per scenario, in the display currency. Null when the balance cannot be evaluated, which leaves the collateralized exposure of the master agreement empty. |

Every vector has one value per scenario. The evaluator does not need to be serializable. The cube keeps the evaluators in a registry for each cube and looks them up by name when it evaluates.

## Which inputs does an algorithm receive?

| Input | Content |
| - | - |
| `CollateralEvaluationData<T>` | The data points of the CSA, by time point. `getDataPoint(timePoint)` returns one, and `getAllDataPoints()` returns all of them in time-point order. |
| `displayCurrency` | The currency that the gross MtM vectors of the data points are expressed in. The CSA parameters are in the CSA currency, `getParametersCurrency()`. Only `evaluateCollateralBalance` receives it. |
| `marketDataSet` | The market data set that the FX rates are read from, the one selected in the query. Only `evaluateCollateralBalance` receives it. |
| `CsaParameters` | The collateral terms of the CSA, with getters such as `getCptyThreshold()`, `getBankThreshold()`, `getCptyMinTransferAmount()`, `getHairCut()`, `getInitialCollateral()`, the margin periods of risk (`getBankHoldingPeriod()` and `getCptyHoldingPeriod()`), the independent amounts, the scale factors, the floors, `getParametersCurrency()`, and `getAdditionalParameters()`. `getBankRounding()` and `getCptyRounding()` return `0`: the rounding columns are loaded but not yet passed to the algorithms. |

The library computes the collateralized exposure from the balances that the algorithm returns. The algorithm does not compute it. See [How is collateralized exposure computed?](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/collateral-evaluator-framework.md#how-is-collateralized-exposure-computed).

The cube assembles the `CsaParameters` from the `CollateralAgreements` table and the CSA parameter measures. See [What are the CSA parameter measures?](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/exposure-measures.md#what-are-the-csa-parameter-measures).

## What does an example algorithm look like?

The following evaluator is a one-way algorithm named `Threshold CSA`. The counterparty posts the exposure above its threshold. The data point holds the gross MtM of the time point.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
public final class ThresholdCsaEvaluator
    implements ICollateralEvaluator<ThresholdCsaEvaluator.MtmPoint> {
  public static final String NAME = "Threshold CSA";
  /** The gross mark-to-market of a netting set at one time point. */
  public record MtmPoint(LocalDate timePoint, IVector mtm)
      implements CollateralEvaluationData.DataPoint {
    @Override
    public LocalDate getTimePoint() {
      return timePoint;
    }
  }
  @Override
  public String algoName() {
    return NAME;
  }
  // The vector is the gross MtM sum of the netting set.
  @Override
  public MtmPoint buildDataPoint(final LocalDate timePoint, final IVector[] vectors) {
    return new MtmPoint(timePoint, vectors[0]);
  }
  // The counterparty posts the exposure above its threshold.
  @Override
  public IVector evaluateCollateralBalance(
      final LocalDate asOfDate,
      final LocalDate timePoint,
      final CollateralEvaluationData<MtmPoint> data,
      final CsaParameters csaParameters,
      final String displayCurrency,
      final String marketDataSet) {
    final var point = data.getDataPoint(timePoint);
    if (point == null) {
      return null;
    }
    final var balance = point.mtm().cloneOnHeap();
    final var threshold =
        SameValueVectorUtils.doubleVector(balance.size(), csaParameters.getCptyThreshold());
    balance.applyAsDouble(threshold, (mtm, limit) -> Math.max(0d, mtm - limit));
    return balance;
  }
}
```

## How to replace a built-in algorithm

An evaluator whose `algoName()` equals the name of a built-in algorithm replaces that algorithm. The built-in names are `Bilateral CSA` and `Unilateral (Bank) CSA`. When two declarations use the same name, the later one replaces the earlier one.

## How to select the algorithm

Every algorithm is a member of the `Collateral Algorithm` hierarchy. The `atoti.solution.model.cubes.<cube>.collateral.default-evaluator` property names the default member. A query that selects no member uses it. The default must be a built-in algorithm or one that the configurer adds, otherwise the application fails at startup with an error that names the cube.

To evaluate another algorithm, select its member in the query. A slicing hierarchy has no `[ALL].[AllMember]` segment in its member path:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  [Measures].[Collateral Balance] ON COLUMNS
FROM [Cube]
WHERE [Collateral Algorithm].[Collateral Algorithm].[Threshold CSA]
```

To compare algorithms, put the hierarchy on an axis:

```mdx theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
SELECT
  [Measures].[Collateral Balance] ON COLUMNS,
  [Collateral Algorithm].[Collateral Algorithm].[Collateral Algorithm].Members ON ROWS
FROM [Cube]
```

The exposure metrics, the inframarginal and incremental contribution measures, and the measures that the consuming cube builds on the collateralized exposure all follow the selected member.

## How to choose the algorithm per CSA

The hidden measure `Collateral Algorithm` returns the selected member, and the collateral measures read it for every cell. An application redefines this measure to choose the algorithm by another rule.

The application does this in its model configurer, the `IModelConfigurer` bean that every application has once, usually named `ModelConfigurer`. Its `configureCubes` method receives the `ICubeManagerConfigurator`. The method calls `updateMeasure` on the measures configurator of the cube, with the name of the measure and a function that receives the measure that selects the algorithm and returns the replacement. The name is `cube.measures().collateralizedMeasures().exposureMeasures().techCollateralMeasures().collateralAlgorithm().getName()`, so the application does not hard-code it.

The following model configurer is written for the PFE cube, which it receives as the cube bean `IPfeCube`. The xVA cube has the same shape with `IXvaCube`. The configurer reads the CSA of each cell. It returns the algorithm `Flat CSA` for one CSA, and the selected algorithm for every other CSA. The constant `FLAT_CSA` is the ID of an application CSA, and `Flat CSA` is the name of an algorithm that the collateral configurer adds.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
static class AlgorithmPerCsa implements IModelConfigurer {
  private final IPfeCube cube;
  AlgorithmPerCsa(final IPfeCube cube) {
    this.cube = cube;
  }
  @Override
  public void configureDatabase(final IDatabaseConfigurator databaseConfigurator) {
    // No database customization.
  }
  @Override
  public void configureCubes(
      final ICubeManagerConfigurator cubeManagerConfigurator,
      final IDatabaseSchema databaseSchema) {
    final var algorithmMeasure =
        cube.measures()
            .collateralizedMeasures()
            .exposureMeasures()
            .techCollateralMeasures()
            .collateralAlgorithm()
            .getName();
    final var csaLevel = cube.levels().specific().csaId();
    cubeManagerConfigurator
        .cube(cube.name())
        .measures()
        .updateMeasure(
            algorithmMeasure,
            selected ->
                Copper.combine(selected, Copper.member(csaLevel))
                    .map(
                        (r, w) -> w.write(FLAT_CSA.equals(r.read(1)) ? "Flat CSA" : r.read(0)),
                        ILiteralType.STRING));
  }
}
```

The algorithm must not be null for a CSA that has an agreement, because the measures then fail with an error that names the missing algorithm.

## Related pages

* [Collateral algorithms](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/collateral-evaluator-framework.md)
* [Cashflow measures](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/cashflows.md)
* [Exposure measures](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/developer-guide/cube/exposure-measures.md)
* [Public API](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/reference/public-api.md)
* [Configuration](https://docs.activeviam.com/solutions/enterprise-risk-suite/1.1/libs/netting-set-analytics/reference/configuration.md)
