> ## 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.

# Worked example

## Custom side store and custom post-processor

This is a worked example showing how to extend Atoti Market Data with a custom market data type - Dividends. It shows how to define the new store, how to
retrieve data from the store, and how to configure new measures. Finally we show you how use this new market data type in a DirectQuery application.

### Step 1: Define the Custom Store

The custom store will contain the fields:

* `AsOfDate` (`LocalDate`) - key
* `MarketDataSet` (`String`) - key
* `InstrumentId` (`String`) - key
* `ExecutionDate` (`LocalDate`) - key
* `Quote` (`Double`)

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
public class DividendReportingStoreConfig {
    public static final String DIVIDEND_REPORTING_MARKET_DATA_STORE = "DividendReportingMarketDataStore";
    public static final String EXECUTION_DATE = "ExecutionDate";
    @Bean
    public IStoreDescription dividendReportingMarketDataStore() {
        return StoreDescription.builder()
                .withStoreName(DIVIDEND_REPORTING_MARKET_DATA_STORE)
                .withField(AS_OF_DATE, LOCAL_DATE, LocalDate.MIN).asKeyField()
                .withField(MARKET_DATA_SET, STRING).asKeyField()
                .withField(INSTRUMENT_ID, STRING).asKeyField()
                .withField(EXECUTION_DATE, LOCAL_DATE, LocalDate.MIN).asKeyField()
                .withField(QUOTE, DOUBLE, 0.0)
                .build();
    }
}
```

The snippets of this example import these names statically:

* `AS_OF_DATE`, `MARKET_DATA_SET`, `INSTRUMENT_ID` and `QUOTE` from `MarketDataConstants`
* `LOCAL_DATE`, `STRING` and `DOUBLE` from `ILiteralType`
* `and`, `equal` and `lessOrEqual` from `BaseConditions`
* `DIVIDEND_REPORTING_MARKET_DATA_STORE` and `EXECUTION_DATE` from `DividendReportingStoreConfig`
* `DIVIDEND_REPORTING_MARKET_DATA_RETRIEVER` from `DividendReportingMarketDataRetrievalConfig`

The application adds this description to its datastore schema with the Atoti Market Data store descriptions. An application that builds its datastore with DaSH adds this description to its configurator from one of its own `IConfigurableSchema` beans, with `configurator.addStore(description)`.

The retrieval configuration of Step 2 imports this configuration class.

### Step 2: Retrieval Configuration & Post-Processor

In order to retrieve the data from the custom side store, we need to:

* Create a retriever class and the associated configuration class.
* Create a post-processor injection configuration so that the retriever can be used in our post-processor.
* Implement the `IDirectQueryCachingPostProcessor` interface to use the cache.

Create the retrieval interface to be called in the post-processor which we will create later:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
public interface IDividendsReportingMarketDataRetriever {
    Double getDividendsUntil(LocalDate asOfDate, String marketDataSet, String instrumentId, LocalDate executionDate);
}
```

Implement the retrieval interface in a class that extends `SingleTableMarketDataRetriever`:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
public class DividendsReportingTableMarketDataRetriever extends SingleTableMarketDataRetriever implements IDividendsReportingMarketDataRetriever {
    private final IPreparedListQuery dividendsCompiledQuery;
    public DividendsReportingTableMarketDataRetriever(IDatabase database, String table) {
        super(database, table);
        dividendsCompiledQuery = database.getQueryManager()
                .listQuery()
                .forTable(table)
                .withCondition(and(
                        equal(FieldPath.of(AS_OF_DATE)).as(AS_OF_DATE),
                        equal(FieldPath.of(MARKET_DATA_SET)).as(MARKET_DATA_SET),
                        equal(FieldPath.of(INSTRUMENT_ID)).as(INSTRUMENT_ID),
                        lessOrEqual(FieldPath.of(EXECUTION_DATE))
                                .as(EXECUTION_DATE)))
                .withFieldsWithoutAlias(FieldPath.of(QUOTE))
                .compile();
    }
    @Override
    public Double getDividendsUntil(LocalDate asOfDate, String marketDataSet, String instrumentId, LocalDate executionDate) {
        var div = 0D;
        try (var cursor = database.getMasterHead()
                .getQueryRunner()
                .listQuery(dividendsCompiledQuery)
                .withParameters(Map.of(
                        AS_OF_DATE,
                        asOfDate,
                        MARKET_DATA_SET,
                        marketDataSet,
                        INSTRUMENT_ID,
                        instrumentId,
                        EXECUTION_DATE,
                        executionDate))
                .runCurrentThread()) {
            while (cursor.next()) {
                div += cursor.getRecord().readDouble(0);
            }
        }
        return div;
    }
}
```

Create the injection configuration class, which injects the `IMarketDataRetrievalContainerService` and the dividends retriever into our post-processor:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@AllArgsConstructor
public class DividendReportingPostProcessorInjectionConfig {
    private final IMarketDataRetrievalContainerService<IDefaultMarketDataRetriever> containerService;
    private final IDividendsReportingMarketDataRetriever dividendsReportingMarketDataRetriever;
    @EventListener
    @Order(MarketDataPostProcessorInjectionConstants.DEFAULT_ORDER)
    public void injectIntoDividendsReportingPostProcessor(final ContextRefreshedEvent ignored) {
        ExtendedPluginInjector.inject(IPostProcessor.class, DividendsReportingPostProcessor.PLUGIN_KEY,
                IMarketDataRetrievalContainerServiceAware.PROPERTY_NAME, containerService);
        ExtendedPluginInjector.inject(IPostProcessor.class, DividendsReportingPostProcessor.PLUGIN_KEY,
                "dividendsReportingMarketDataRetriever", dividendsReportingMarketDataRetriever);
    }
}
```

Create the retrieval configuration class. It imports the store configuration and the injection configuration:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@Import({ DividendReportingStoreConfig.class, DividendReportingPostProcessorInjectionConfig.class })
public class DividendReportingMarketDataRetrievalConfig {
    public static final String DIVIDEND_REPORTING_MARKET_DATA_RETRIEVER = "DividendReportingMarketDataRetriever";
    @Bean
    public IDateRetriever dividendReportingDateRetriever(IDatabase database) {
        return new TableDateRetriever(database, DIVIDEND_REPORTING_MARKET_DATA_STORE);
    }
    @Bean
    public IContextualDateRetriever dividendReportingDateShiftingDateRetriever(IDatabase database) {
        return new DateShiftingDateRetriever(dividendReportingDateRetriever(database));
    }
    @Bean
    public IMarketDataCoordinateTranslator<Object[]> dividendReportingDateShiftingCoordinateTranslator(IDatabase database) {
        return new DateShiftTranslator(database, DIVIDEND_REPORTING_MARKET_DATA_STORE, dividendReportingDateShiftingDateRetriever(database));
    }
    @Bean
    public DividendsReportingTableMarketDataRetriever dividendsReportingMarketDataRetriever(IDatabase database) {
        return new DividendsReportingTableMarketDataRetriever(database, DIVIDEND_REPORTING_MARKET_DATA_STORE);
    }
    @Bean
    public IMarketDataRetrievalContainer<DividendsReportingTableMarketDataRetriever> dividendsReportingRetrievalContainer(IDatabase database) {
        return new MarketDataRetrievalContainer<>(
                DIVIDEND_REPORTING_MARKET_DATA_RETRIEVER,
                dividendsReportingMarketDataRetriever(database),
                dividendReportingDateShiftingCoordinateTranslator(database));
    }
}
```

We now import the retrieval configuration in our application config class, for example `ApplicationConfig`. It brings the store and the injection configuration with it:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
@Import(DividendReportingMarketDataRetrievalConfig.class)
public class ApplicationConfig {
}
```

The injection configuration uses the application's `IMarketDataRetrievalContainerService`, which `MarketDataRetrievalContainerServiceConfig` publishes.

Create the postprocessor that will use the retriever we have configured.

Use the abstract class `ADirectQueryCachingMarketDataPostProcessor` which conforms to design patterns laid out by Atoti Market Data. Note that this will provide built-in support for DirectQuery caching.

In this example, we extend `SingleMarketDataPostProcessor` (which itself extends `ADirectQueryCachingMarketDataPostProcessor`).

In addition, we have an internal class which extends `ADefaultContextualMarketDataRetriever`. [Market data retrieval implementations](https://docs.activeviam.com/solutions/libraries/market-data/1.5/retrieval.md#market-data-retrieval-implementations)

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@AtotiExtendedPluginValue(intf = IPostProcessor.class, key = DividendsReportingPostProcessor.PLUGIN_KEY)
public class DividendsReportingPostProcessor extends SingleMarketDataPostProcessor {
    public static final String PLUGIN_KEY = "DividendsReportingPostProcessor";
    protected IDividendsReportingMarketDataRetriever dividendsReportingMarketDataRetriever;
    public DividendsReportingPostProcessor(String name, IPostProcessorCreationContext creationContext) {
        super(name, creationContext);
    }
    @Override
    protected IDefaultContextualMarketDataRetriever getMarketDataRetriever(ILocation location) {
        return new EquityDividendMarketDataRetriever(getMarketDataRetrievalContainer().name(),
                getMarketDataRetrievalContainer().coordinateTranslator());
    }
    @Override
    public String getType() {
        return PLUGIN_KEY;
    }
    public void setDividendsReportingMarketDataRetriever(
            IDividendsReportingMarketDataRetriever dividendsReportingMarketDataRetriever) {
        this.dividendsReportingMarketDataRetriever = dividendsReportingMarketDataRetriever;
    }
    protected class EquityDividendMarketDataRetriever extends ADefaultContextualMarketDataRetriever {
        public EquityDividendMarketDataRetriever(String name, IMarketDataCoordinateTranslator<Object[]> coordinateTranslator) {
            super(name, coordinateTranslator);
        }
        @Override
        public Double doGetMarketData(Object[] translatedCoordinates) {
            var asOfDate = (LocalDate) translatedCoordinates[0];
            var marketDataSet = (String) translatedCoordinates[1];
            var instrumentId = (String) translatedCoordinates[2];
            var executionDate = (LocalDate) translatedCoordinates[3];
            return dividendsReportingMarketDataRetriever.getDividendsUntil(asOfDate, marketDataSet, instrumentId, executionDate);
        }
    }
}
```

### Step 3: the Measure configuration

Using Copper and `MarketDataMeasureBuilderHelper` create the measure in your measure configuration.

Read more about [MarketDataMeasureBuilderHelper](https://docs.activeviam.com/solutions/libraries/market-data/1.5/postprocessors.md#marketdatameasurebuilderhelper)

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
private static final LevelIdentifier AS_OF_DATE_LEVEL = new LevelIdentifier("Dates", "Date", "AsOfDate");
private static final LevelIdentifier MARKET_DATA_SET_LEVEL = new LevelIdentifier("MarketData", "MarketDataSets", "MarketDataSet");
private static final LevelIdentifier INSTRUMENT_ID_LEVEL = new LevelIdentifier("InstrumentId", "InstrumentId", "InstrumentId");
private static final LevelIdentifier EXECUTION_DATE_LEVEL = new LevelIdentifier("ExecutionDate", "ExecutionDate", "ExecutionDate");
```

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
CopperMeasure dividendMeasure = new MarketDataMeasureBuilderHelper<>(
        DividendsReportingPostProcessor.PLUGIN_KEY,
        DIVIDEND_REPORTING_MARKET_DATA_RETRIEVER)
        .startBuilding(List.of(AS_OF_DATE_LEVEL, MARKET_DATA_SET_LEVEL, INSTRUMENT_ID_LEVEL, EXECUTION_DATE_LEVEL), MarketDataDateShift.CURRENT_DAY)
        .as("DividendMeasure");
```

## Usage in a DirectQuery application

### Defining a DQ cache

In a DirectQuery application, defining a cache will allow us to retrieve the data efficiently.

In order to define the cache, we need to:

* Specify the side store for which the caching is used (it will be the custom store we defined in our worked example).
* Specify the partitioning fields (here we will use the `AsOfDate` and `MarketDataSet` fields).
* Specify the capacity of the cache (we will set it to 6 partitions here as an example).

The postprocessor we created in the worked example extends `ADirectQueryCachingMarketDataPostProcessor` which implements `IDirectQueryCachingPostProcessor`,
which means that it will automatically work with our configured cache.

We will create the cache description in a `@Configuration` class:

Note: The cache size is being set to 6 just as an example, in a real project the size will depend on the specific needs of the project.

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Configuration
public class DividendReportingStoreCacheConfig {
    @Bean
    public SingleTableCacheDescription dividendReportingStoreCacheDescription() {
        return SingleTableCacheDescription.builder()
                .tableName(DIVIDEND_REPORTING_MARKET_DATA_STORE)
                .cachePartitioningFields(List.of(AS_OF_DATE, MARKET_DATA_SET))
                .capacity(CacheCapacity.MaxPartitionsCount.of(6))
                .build();
    }
}
```

We also need to import `DividendReportingStoreCacheConfig` in the `ApplicationConfig` class.

### Populating the database table

Here we take the example of a Databricks database in which we want to create our custom table and populate some sample data in it.
We use the following SQL script:

```sql theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
CREATE OR REPLACE TABLE DividendReportingMarketDataStore (
    AsOfDate DATE NOT NULL,
    MarketDataSet STRING NOT NULL,
    InstrumentId STRING NOT NULL,
    ExecutionDate DATE NOT NULL,
    Quote DOUBLE NOT NULL,
    PRIMARY KEY (AsOfDate, MarketDataSet, InstrumentId, ExecutionDate)
);

INSERT INTO DividendReportingMarketDataStore (AsOfDate, MarketDataSet, InstrumentId, ExecutionDate, Quote)
VALUES
    ('2018-09-28', 'MarketDataSet1', 'Stock1', '2024-01-01', 1.0),
    ('2018-09-28', 'MarketDataSet1', 'Stock1', '2024-02-01', 2.0),
    ('2018-09-28', 'MarketDataSet1', 'Stock1', '2024-03-01', 3.0);
```

The way you populate your database may be specific to your project, so the actions you need to take to create and
populate the custom table in the database may vary compared to this example.
