# Aggregated Custom Expression Functions

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom-aggregation

- Aggregated Custom Expression Functions work across many rows
- A **Basic** function folds the rows into a single value with `initialValue` + `reducer`
- An **Advanced** function also post-processes that value, and can return a different value on each row
- They are available in Calculated Column Aggregated and Alert Aggregated Expressions

Developers can add Custom **Aggregation** Expression Functions to AdapTableQL.

These functions operate on a set of rows — typically on one Column.

- It also possible to optionally split the aggregation by using `GROUP_BY`
- And you can narrow the aggregation function by using `WHERE`

Custom Aggregation Functions are registered in `expressionOptions.customAggregatedFunctions`.

AdapTableQL then lists them in the Aggregated [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md) for [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) and [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md).

- **Your own maths, first-class**: VWAP, running totals, Kth largest, custom risk measures, used like `SUM` or `AVG`
- **Declare capability, get feature**: `cumulative: true` gives running value per row; `weight:true` gives `WEIGHT([col])`
- **Grouping and filtering for free**: every Custom Aggregation accepts `GROUP_BY` and `WHERE`
- **Available to Users**: listed in Expression Editor with your description, signatures and examples
- **One small object**: an `initialValue` and a `reducer` - with optional hooks only when you need them
  

AG Grid's custom `aggFunc`s only fill group and total rows; a Custom Aggregation gives a value on every row

**Example: AdapTableQL: Custom Aggregation Capabilities**

Custom Aggregations which declare `cumulative` and `weight`

- This demo defines 2 Custom Aggregated Functions (explained in [Declared Capabilities](#declared-capabilities) below):
  - `RUNNING_SUM` - declares `cumulative: true`
  - `VWAP` - declares `weight: true` and `cumulative: true`
- They are used in 4 Aggregated [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-aggregated/index.md):
  - `Running Notional` - `RUNNING_SUM{[notional], CUMULATIVE([tradeDate])}`
  - `Desk Running Notional` - `RUNNING_SUM{[notional], GROUP_BY([desk]), CUMULATIVE([tradeDate])}`
  - `Ticker VWAP` - `VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker])}`
  - `Running Ticker VWAP` - `VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker]), CUMULATIVE([tradeDate])}`

- Sort by `Trade Date` (the default) and see `Running Notional` build up trade by trade
- Change the `Quantity` of an `AAPL` trade and watch both VWAP Columns move for every `AAPL` trade
- Open the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md) for a Calculated Column to see `RUNNING_SUM` and `VWAP` listed with their clauses

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions, AggregatedExpressionFunction} from '@adaptabletools/adaptable';
import {Trade} from './rowData';

export const customAggregatedFunctions: Record<string, AggregatedExpressionFunction> = {
  RUNNING_SUM: {
    cumulative: true,
    initialValue: 0,
    reducer: (context) =>
      typeof context.currentValue === 'number'
        ? context.accumulator + context.currentValue
        : context.accumulator,
    returnType: 'number',
    inputTypes: ['number'],
    description: 'Sum of a numeric Column - use CUMULATIVE for a running total',
    signatures: ['RUNNING_SUM{[numericColumn], CUMULATIVE([orderColumn])}'],
    examples: ['RUNNING_SUM{[notional], CUMULATIVE([tradeDate])}'],
  },
  VWAP: {
    // Σ(price · quantity) / Σ(quantity)
    initialValue: () => ({weighted: 0, weights: 0}),
    reducer: (context) => {
      if (typeof context.currentValue !== 'number') {
        return context.accumulator;
      }
      const weight = typeof context.weightValue === 'number' ? context.weightValue : 1;
      context.accumulator.weighted += context.currentValue * weight;
      context.accumulator.weights += weight;
      return context.accumulator;
    },
    processAggregatedValue: (context) =>
      context.aggregatedValue.weights
        ? context.aggregatedValue.weighted / context.aggregatedValue.weights
        : undefined,
    weight: true,
    cumulative: true,
    returnType: 'number',
    inputTypes: ['number'],
    description: 'Volume Weighted Average Price - use WEIGHT for the volume',
    signatures: ['VWAP{[price], WEIGHT([quantity])}'],
    examples: [
      'VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker])}',
      'VWAP{[price], WEIGHT([quantity]), CUMULATIVE([tradeDate])}',
    ],
  },
};

export const adaptableOptions: AdaptableOptions<Trade> = {
  primaryKey: 'id',
  adaptableId: 'Custom Aggregation Capabilities',
  expressionOptions: {
    customAggregatedFunctions,
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'runningNotional',
          FriendlyName: 'Running Notional',
          Expression: 'RUNNING_SUM{[notional], CUMULATIVE([tradeDate])}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'deskRunningNotional',
          FriendlyName: 'Desk Running Notional',
          Expression: 'RUNNING_SUM{[notional], GROUP_BY([desk]), CUMULATIVE([tradeDate])}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'tickerVwap',
          FriendlyName: 'Ticker VWAP',
          Expression: 'VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker])}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'runningVwap',
          FriendlyName: 'Running Ticker VWAP',
          Expression:
            'VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker]), CUMULATIVE([tradeDate])}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'two-decimals',
          Scope: {
            ColumnIds: [
              'price',
              'notional',
              'runningNotional',
              'deskRunningNotional',
              'tickerVwap',
              'runningVwap',
            ],
          },
          DisplayFormat: {Formatter: 'NumberFormatter', Options: {FractionDigits: 2}},
        },
        {
          Name: 'trade-date',
          Scope: {ColumnIds: ['tradeDate']},
          DisplayFormat: {Formatter: 'DateFormatter', Options: {Pattern: 'dd MMM yyyy'}},
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Trades',
      Layouts: [
        {
          Name: 'Trades',
          TableColumns: [
            'tradeDate',
            'ticker',
            'desk',
            'quantity',
            'price',
            'notional',
            'runningNotional',
            'deskRunningNotional',
            'tickerVwap',
            'runningVwap',
          ],
          ColumnSorts: [{ColumnId: 'tradeDate', SortOrder: 'Asc'}],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/rowData.ts`**

```ts
export interface Trade {
  id: number;
  tradeDate: Date;
  ticker: string;
  desk: string;
  side: 'Buy' | 'Sell';
  quantity: number;
  price: number;
  notional: number;
  pnl: number;
  status: 'Open' | 'Closed';
}

type TradeInput = Omit<Trade, 'tradeDate' | 'notional'>;

const trades: TradeInput[] = [
  {id: 1, ticker: 'AAPL', desk: 'Tech', side: 'Buy', quantity: 500, price: 189.2, pnl: 1200, status: 'Open'},
  {id: 2, ticker: 'MSFT', desk: 'Tech', side: 'Buy', quantity: 200, price: 415.5, pnl: 850, status: 'Closed'},
  {id: 3, ticker: 'NVDA', desk: 'Tech', side: 'Sell', quantity: 100, price: 875.0, pnl: -2100, status: 'Open'},
  {id: 4, ticker: 'JPM', desk: 'Financials', side: 'Buy', quantity: 400, price: 198.7, pnl: 640, status: 'Open'},
  {id: 5, ticker: 'XOM', desk: 'Energy', side: 'Buy', quantity: 800, price: 118.2, pnl: -320, status: 'Closed'},
  {id: 6, ticker: 'AAPL', desk: 'Tech', side: 'Sell', quantity: 300, price: 190.1, pnl: 270, status: 'Closed'},
  {id: 7, ticker: 'GS', desk: 'Financials', side: 'Sell', quantity: 150, price: 452.3, pnl: -950, status: 'Open'},
  {id: 8, ticker: 'CVX', desk: 'Energy', side: 'Buy', quantity: 350, price: 156.4, pnl: 410, status: 'Open'},
  {id: 9, ticker: 'NVDA', desk: 'Tech', side: 'Buy', quantity: 250, price: 868.4, pnl: 25000, status: 'Open'},
  {id: 10, ticker: 'JPM', desk: 'Financials', side: 'Sell', quantity: 200, price: 199.9, pnl: 240, status: 'Closed'},
  {id: 11, ticker: 'XOM', desk: 'Energy', side: 'Sell', quantity: 600, price: 119.0, pnl: 480, status: 'Open'},
  {id: 12, ticker: 'MSFT', desk: 'Tech', side: 'Buy', quantity: 150, price: 417.2, pnl: -380, status: 'Open'},
  {id: 13, ticker: 'GS', desk: 'Financials', side: 'Buy', quantity: 100, price: 449.8, pnl: 520, status: 'Closed'},
  {id: 14, ticker: 'CVX', desk: 'Energy', side: 'Sell', quantity: 250, price: 157.1, pnl: -175, status: 'Closed'},
  {id: 15, ticker: 'AAPL', desk: 'Tech', side: 'Buy', quantity: 400, price: 188.7, pnl: 900, status: 'Open'},
  {id: 16, ticker: 'JPM', desk: 'Financials', side: 'Buy', quantity: 300, price: 197.6, pnl: -460, status: 'Open'},
];

// One trade a day from 1 September, each at a different time
export const rowData: Trade[] = trades.map((trade, index) => ({
  ...trade,
  tradeDate: new Date(2026, 8, index + 1, 9, 30 + index * 7),
  notional: Math.round(trade.quantity * trade.price * 100) / 100,
}));
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Trade} from './rowData';

export const columnDefs: ColDef<Trade>[] = [
  {field: 'id', headerName: 'Trade Id', cellDataType: 'number'},
  {field: 'tradeDate', headerName: 'Trade Date', cellDataType: 'date'},
  {field: 'ticker', headerName: 'Ticker', cellDataType: 'text'},
  {field: 'desk', headerName: 'Desk', cellDataType: 'text', enableRowGroup: true},
  {field: 'side', headerName: 'Side', cellDataType: 'text'},
  {field: 'quantity', headerName: 'Quantity', cellDataType: 'number', type: 'rightAligned'},
  {field: 'price', headerName: 'Price', cellDataType: 'number', type: 'rightAligned'},
  {field: 'notional', headerName: 'Notional', cellDataType: 'number', type: 'rightAligned'},
  {field: 'pnl', headerName: 'P&L', cellDataType: 'number', type: 'rightAligned'},
  {field: 'status', headerName: 'Status', cellDataType: 'text'},
];
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';
import {rowData, Trade} from './rowData';

export const gridOptions: GridOptions<Trade> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  columnMenu: 'new',
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

- The first argument in an aggregation function is typically a Column, e.g. `SUMSQ{[rating]}`
- However, extra arguments are also allowed, e.g. `LARGE{[amount], 2}`

There are 2 levels of Custom Aggregated Function:

| Level                         | Properties                                                      | Returns                                   |
| ----------------------------- | --------------------------------------------------------------- | ----------------------------------------- |
| **Basic**                     | `initialValue`, `reducer`                                       | One value for the set (or for each group) |
| **Advanced** | Basic, plus `processAggregatedValue` and / or `prepareRowValue` | One value for the set, or a value per row |

Start with a Basic function; only reach for the Advanced hooks when the reducer result is not the final answer

## Basic Aggregations

A Basic Aggregation Function needs just 2 properties:

- `initialValue` — the starting value of the accumulator
- `reducer` — called once per row, returning the new accumulator

The value the `reducer` returns for the last row is the result of the function.

### Defining a Basic Custom Aggregated Function

This example creates 2 Basic functions:

- `SUMSQ` — the sum of squares of a numeric Column (like Excel's `SUMSQ`)
- `COUNT_ABOVE` — how many values in the Column are greater than a threshold passed as a second argument

Add each function to `expressionOptions.customAggregatedFunctions`.

This is a Record (or a callback that returns one):

- keys: custom function names (CAPITAL LETTERS by convention)
- values: of type [`AggregatedExpressionFunction`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md)

The starting value for the accumulator.

Here its `0` in both cases (a running total and a running count).

If the reducer mutates its accumulator, supply a **factory** instead — e.g. `initialValue:()=>[]` — so each aggregation (and group) starts fresh

Called for **each** row in the set; returns the new accumulator.

The [`AggregatedExpressionReducerContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md) includes:

- `accumulator` — previous return value, or `initialValue` on the first call
- `currentValue` — the aggregated Column's value in this row
- `index` — position in the Column data
- `args` — any extra args, e.g. threshold in `COUNT_ABOVE{[amount], 1000}`
- `aggColumnId`, `getValueForColId`, `rowNode`, `groupByColumnIds`

Shown in the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md):

- `inputTypes` — optional argument types (helps editor cue suitable Columns)
- `description` — what the Function does
- `signatures` — how it should be called
- `examples` — small Expressions that use it
- `category` — Functions-menu section; omit for the Aggregation section

```ts [[1,2, "customAggregatedFunctions"], [1,3, "SUMSQ"], [1,17, "COUNT_ABOVE"], [2,4, "initialValue"], [2,18, "initialValue"], [3,5, "reducer"], [3,6, "currentValue"], [3,10, "accumulator"], [3,19, "reducer"], [3,20, "context.args[0]"], [3,21, "currentValue"], [3,22, "accumulator"], [4,12, "inputTypes"], [4,13, "description"], [4,14, "signatures"], [4,15, "examples"], [4,25, "inputTypes"], [4,26, "description"], [4,27, "signatures"], [4,28, "examples"]]
expressionOptions: {
  customAggregatedFunctions: {
    SUMSQ: {
      initialValue: 0,
      reducer: (context) => {
        const value = context.currentValue;
        if (value == null || Number.isNaN(Number(value))) {
          return context.accumulator;
        }
        return context.accumulator + value * value;
      },
      inputTypes: ['number'],
      description: 'Mimics SUMSQ in Excel - the sum of squares of the values',
      signatures: ['SUMSQ{[numericColumn]}'],
      examples: ['SUMSQ{[rating]}', 'SUMSQ{[rating], GROUP_BY([currency])}'],
    },
    COUNT_ABOVE: {
      initialValue: 0,
      reducer: (context) => {
        const threshold = context.args[0];
        return context.currentValue > threshold
          ? context.accumulator + 1
          : context.accumulator;
      },
      inputTypes: ['number', 'number'],
      description: 'Counts the values greater than the given threshold',
      signatures: ['COUNT_ABOVE{[numericColumn], threshold: number}'],
      examples: ['COUNT_ABOVE{[amount], 1000}'],
    },
  },
}
```

## Advanced Aggregations

Sometimes the reducer result is not the final answer and more is required.

For example the function needs sorting, or a Kth value picked out, or a different result shown on each row.

Advanced Aggregation functions can include 2 optional hooks, which run in this order:

`filterRow` (optional) → `reducer` per row → `processAggregatedValue` once → `prepareRowValue` per row

| Hook                                      | Runs                                        | Use it to                                                                     | Example |
| ----------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------- | ------- |
| `processAggregatedValue` | **Once**, after every row has been reduced  | Turn the reducer result into the final value (sort, pick Kth, build a lookup) | `LARGE` |
| `prepareRowValue`                         | **Per row**, after `processAggregatedValue` | Return a different value on each row (rank, percentage, "in the top K")       | `RANK`  |

- This is a very common pattern when using a Custom Aggregation Function:
- Collect values in the `reducer`, i.e.  do the expensive work (e.g. sorting) **once** in `processAggregatedValue`
- Then build a `Map` / `Set` so `prepareRowValue` is a cheap lookup per row

### Defining Advanced Custom Aggregated Functions

This example creates 2 functions:

- `LARGE` — the Kth largest value (like Excel's `LARGE`); uses `processAggregatedValue`
- `RANK` — the rank of each row's value (1 = smallest); uses `processAggregatedValue` **and** `prepareRowValue`

Both functions just collect the values; the real work happens afterwards.

Note the factory `initialValue: () => []`, because the reducer mutates the array.

`processAggregatedValue` runs **once**, after every row has been reduced. Whatever it returns becomes the aggregated value.

- `LARGE` sorts once and returns the Kth value (`K` arrives in `context.args`)
- `RANK` sorts once and returns a `Map` of value → rank

[`AggregatedExpressionProcessAggValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md) includes `aggregatedValue` (the reducer result), `rowNodes` (the rows in this set / group) and `args`.

`prepareRowValue` runs for **each** row, after `processAggregatedValue`. Use it when the result differs per row.

`RANK` reads the row's own value and looks up its rank in the `Map`.

[`AggregatedExpressionPrepareRowValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md) includes the current `rowNode`, `aggregatedValue`, `aggColumnId` and `getValueForColId`.

`filterRow` runs **before** the reducer; return `false` to leave a row out of the aggregation.

It receives [`AggregatedExpressionFilterRowContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md).

```ts [[1,4, "initialValue: () => []"], [1,24, "initialValue: () => []"], [2,11, "processAggregatedValue"], [2,12, "context.args[0]"], [2,31, "processAggregatedValue"], [2,35, "return rankMap"], [3,37, "prepareRowValue"], [3,38, "getValueForColId"], [3,39, "aggregatedValue.get"]]
expressionOptions: {
  customAggregatedFunctions: {
    LARGE: {
      initialValue: () => [],
      reducer: (context) => {
        if (context.currentValue != undefined) {
          context.accumulator.push(context.currentValue);
        }
        return context.accumulator;
      },
      processAggregatedValue: (context) => {
        const k = context.args[0];
        const values = context.aggregatedValue;
        if (k == undefined || k <= 0 || k > values.length) {
          return undefined;
        }
        return [...values].sort((a, b) => b - a)[k - 1];
      },
      description: 'Mimics LARGE in Excel - the Kth largest value',
      signatures: ['LARGE{[numericColumn], K: number}'],
      examples: ['LARGE{[amount], 2}'],
    },
    RANK: {
      initialValue: () => [],
      reducer: (context) => {
        if (context.currentValue != undefined) {
          context.accumulator.push(context.currentValue);
        }
        return context.accumulator;
      },
      processAggregatedValue: (context) => {
        const sorted = [...context.aggregatedValue].sort((a, b) => a - b);
        const rankMap = new Map();
        sorted.forEach((value, index) => rankMap.set(value, index + 1));
        return rankMap;
      },
      prepareRowValue: (context) => {
        const rowValue = context.getValueForColId(context.aggColumnId);
        return context.aggregatedValue.get(rowValue);
      },
      description: 'The rank of each row value in the list (1 = smallest)',
      signatures: ['RANK{[numericColumn]}'],
      examples: ['RANK{[amount]}'],
    },
  },
}
```

- `prepareRowValue` can also return a **boolean** - see the demo's `TOP` function
- it returns `true` when a row's value is among the K largest, for use in a boolean expression

## Declared Capabilities

Every custom aggregation accepts `GROUP_BY` and `WHERE`. 

The remaining clauses are **capabilities the definition declares** — validation and the Expression Editor both pick them up automatically, exactly as they do for shipped aggregations like `SUM`.

Capabilities apply to both levels: below, `RUNNING_SUM` is a Basic function and `VWAP` an Advanced one.

| Property                       | Enables                                            | Notes                                                                                                                                                                                                              |
| ------------------------------ | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `cumulative: true`             | `CUMULATIVE([orderCol])` — a running value per row | The rows are walked in `orderCol` order (restarting per `GROUP_BY` partition) and each row receives the accumulator **so far**. `processAggregatedValue` and `prepareRowValue` apply to that running value.        |
| `cumulative: { currentValue }` | Same, with a custom per-row projection             | Use when the running value is not simply the accumulator (e.g. a running average kept as `{ sum, count }`). `currentValue` receives the accumulator so far plus `rowNode`, `index` and `weightValue`.              |
| `weight: true`                 | `WEIGHT([weightCol])`                              | The weight Column's value for the current row arrives as `weightValue` in the `reducer`, `prepareRowValue`, `filterRow` and `cumulative.currentValue` contexts.                                                    |
| `returnType`                   | Static result type                                 | `'number'`, `'text'`, `'date'`, `'boolean'` or `'input'` (same type as the aggregated Column). Drives the Calculated Column data type and static type checks; without it a Calculated Column defaults to `number`. |

- Using `CUMULATIVE` or `WEIGHT` on a custom function that does **not** declare the capability is a validation error
- So the definition is the single source of truth for what an Expression may say

```ts [[1,3, "cumulative: true"], [2,16, "weight: true"], [2,11, "weightValue"], [3,21, "returnType: 'number'"]]
customAggregatedFunctions: {
  RUNNING_SUM: {
    cumulative: true,
    initialValue: 0,
    reducer: (context) => context.accumulator + (context.currentValue ?? 0),
  },
  VWAP: {
    // Σ(price · weight) / Σ(weight)
    initialValue: () => ({ weighted: 0, weights: 0 }),
    reducer: (context) => {
      const weight = context.weightValue ?? 1;
      context.accumulator.weighted += context.currentValue * weight;
      context.accumulator.weights += weight;
      return context.accumulator;
    },
    weight: true,
    processAggregatedValue: (context) =>
      context.aggregatedValue.weights
        ? context.aggregatedValue.weighted / context.aggregatedValue.weights
        : undefined,
    returnType: 'number',
    signatures: ['VWAP{[price], WEIGHT([quantity])}'],
  },
}
```

With those definitions all of the following are valid Aggregated Expressions:

```
RUNNING_SUM{[notional], CUMULATIVE([tradeDate])}
RUNNING_SUM{[notional], GROUP_BY([book]), CUMULATIVE([tradeDate])}
VWAP{[price], WEIGHT([quantity])}
VWAP{[price], WEIGHT([quantity]), GROUP_BY([ticker])} WHERE [status] = 'Filled'
```

- A `VWAP` that also declares `cumulative: true` yields a running VWAP per row:
- e.g. `VWAP{[price], WEIGHT([quantity]), CUMULATIVE([tradeDate])}`

- The running variant hands each row the accumulator so far and runs `processAggregatedValue` on it
- As a result, no extra code is required

The demo at the top of this page uses these `RUNNING_SUM` and `VWAP` definitions

**Example: AdapTableQL: Custom Aggregation Functions**

Using Basic and Advanced Custom Aggregated Expression Functions

- This example uses 4 Custom Aggregated Functions in [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md):
  - **Basic** — `SUMSQ`: sum of squares of `Rating` — `Sum Sq Rating` (whole grid) and `Ccy Sum Sq` (grouped by `Currency`)
  - **Advanced** — `LARGE`: Kth largest `Amount` — `2nd Large Amt` (uses `processAggregatedValue`)
  - **Advanced** — `RANK`: rank of each `Amount` — `Amt Rank` (uses `processAggregatedValue` and `prepareRowValue`)
  - **Advanced** — `TOP`: true if the row's `Amount` is among the K largest — `Top 5 Amt` (and a hidden `Top 3 Amt` used by a Format Column)

- Open the [Expression Editor](https://www.adaptabletools.com/docs/ui-expression-editor/index.md) for those Calculated Columns to see the Aggregated Functions
- Sort the `Amount` column and note that `2nd Large Amt`, `Amt Rank` and `Top 5 Amt` stay correct

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  AggregatedExpressionPrepareRowValueContext,
  AggregatedExpressionProcessAggValueContext,
  AggregatedExpressionReducerContext,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom Aggregation Expression Functions',
  expressionOptions: {
    customAggregatedFunctions: {
      SUMSQ: {
        initialValue: 0,
        reducer: (context: AggregatedExpressionReducerContext) => {
          const value = context.currentValue;
          if (value == null || Number.isNaN(Number(value))) {
            return context.accumulator;
          }
          return context.accumulator + value * value;
        },
        inputTypes: ['number'],
        description:
          'Mimics SUMSQ in Excel - returning the sum of squares of the arguments',
        signatures: ['SUMSQ{[numericColumn]}'],
        examples: ['SUMSQ{[rating]}'],
      },
      LARGE: {
        initialValue: () => [],
        reducer: (context: AggregatedExpressionReducerContext) => {
          // collect values only; sort once in processAggregatedValue
          if (context.currentValue != undefined) {
            context.accumulator.push(context.currentValue);
          }
          return context.accumulator;
        },
        processAggregatedValue: (
          context: AggregatedExpressionProcessAggValueContext
        ) => {
          const k = context.args[0];
          const values = context.aggregatedValue;
          if (k == undefined || k <= 0 || k > values.length) {
            console.log('Invalid K value for LARGE function: ', k);
            return;
          }

          const sorted = [...values].sort((a: any, b: any) => b - a);
          // k-1 because of 0-based index
          return sorted[k - 1];
        },
        inputTypes: ['number', 'number'],
        description:
          'Mimics LARGE in Excel - Returns the K-th largest value in a data set',
        signatures: ['LARGE{[numericColumn], K: number}'],
        examples: ['LARGE{[amount], 2}'],
      },
      RANK: {
        description:
          'Mimics RANK in Excel - Returns the rank of a number in a list of numbers',
        signatures: ['RANK{[amount]}'],
        examples: ['RANK{[amount]}'],
        initialValue: () => [],
        reducer: (context: AggregatedExpressionReducerContext) => {
          // sorting an array is an O(n log n) operation, and doing it for every element would result in an O(n^2 log n) operation
          // a more efficient way is to sort the array after all elements have been added, in the processAggregatedValue() function
          if (context.currentValue != undefined) {
            context.accumulator.push(context.currentValue);
          }
          return context.accumulator;
        },
        processAggregatedValue: (
          context: AggregatedExpressionProcessAggValueContext
        ) => {
          // 1. sort the array and populate the rank map
          const sortedDataCollection = context.aggregatedValue.sort(
            (firstValue: any, secondValue: any) => firstValue - secondValue
          );

          // 2. map sorted array to a rank map
          const rankMap = new Map<any, number>();
          sortedDataCollection.forEach((value: any, index: any) => {
            rankMap.set(value, index + 1);
          });

          // this aggregatedValue will be passed to prepareRowValue() function
          return rankMap;
        },
        prepareRowValue: (
          context: AggregatedExpressionPrepareRowValueContext
        ) => {
          // this function will be called for each row after the reducer() and processAggregatedValue() functions
          // because the aggregated value is a map, we can get the rank of the current row value with a single lookup (O(1) complexity)
          const rowValue = context.getValueForColId(context.aggColumnId);

          return context.aggregatedValue.get(rowValue) as number;
        },
        inputTypes: ['number'],
      },
      TOP: {
        inputTypes: ['number', 'number'],
        description:
          'Returns true if the row value is among the K largest values in the list (ties at the boundary are all included)',
        signatures: ['TOP{[numericColumn], K: number}'],
        examples: ['TOP{[amount], 5}'],
        initialValue: () => [],
        reducer: (context: AggregatedExpressionReducerContext) => {
          // collect every non-empty value; sort once in processAggregatedValue
          // for O(n log n) instead of O(n^2 log n) per-row sorting
          if (context.currentValue != undefined) {
            context.accumulator.push(context.currentValue);
          }
          return context.accumulator;
        },
        processAggregatedValue: (
          context: AggregatedExpressionProcessAggValueContext
        ) => {
          const k = context.args[0];
          if (k == undefined || k <= 0) {
            console.log('Invalid K value for TOP function: ', k);
            return new Set();
          }

          // sort descending; the threshold is the K-th largest value
          const sorted = [...context.aggregatedValue].sort(
            (a: any, b: any) => b - a
          );
          const threshold = sorted[Math.min(k, sorted.length) - 1];

          // build a Set of every value at-or-above the threshold so
          // prepareRowValue can do an O(1) lookup per row. Including
          // every value tied with the threshold matches the natural
          // meaning of "in the top K".
          const topSet = new Set<any>();
          for (const v of sorted) {
            if (v >= threshold) {
              topSet.add(v);
            } else {
              break;
            }
          }
          return topSet;
        },
        prepareRowValue: (
          context: AggregatedExpressionPrepareRowValueContext
        ) => {
          const rowValue = context.getValueForColId(context.aggColumnId);
          return (context.aggregatedValue as Set<any>).has(rowValue);
        },
      },
    },
  },

  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn', 'FormatColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'sum_square_rating',
          Expression: 'SUMSQ{[rating]}',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
          FriendlyName: 'Sum Sq Rating',
        },
        {
          ColumnId: 'sum_square_rating_ccy',
          Expression: 'SUMSQ{[rating], GROUP_BY([currency])}',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
          FriendlyName: 'Ccy Sum Sq',
        },
        {
          ColumnId: '2nd_largest_amount',
          Expression: 'LARGE{[amount], 2}',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
          FriendlyName: '2nd Large Amt',
        },
        {
          ColumnId: 'rank_amount',
          Expression: 'RANK{[amount]}',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
          FriendlyName: 'Amt Rank',
        },
        {
          ColumnId: 'top5_amount',
          Expression: 'TOP{[amount], 5}',
          CalculatedColumnSettings: {
            DataType: 'boolean',
          },
          FriendlyName: 'Top 5 Amt',
        },
        {
          // Helper boolean column used by the `Top 3 Amt` Format Column
          // below. Hidden from the visible layout — its only purpose is
          // to expose the aggregated `TOP{[amount], 3}` result as a
          // per-row boolean that a (non-aggregated) `Expression`
          // rule can reference.
          ColumnId: 'top3_amount',
          Expression: 'TOP{[amount], 3}',
          CalculatedColumnSettings: {
            DataType: 'boolean',
          },
          FriendlyName: 'Top 3 Amt',
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-top3-amount',
          Scope: {
            ColumnIds: ['amount'],
          },
          // Highlight the `amount` cell whenever its value is in the
          // top 3 — driven by the `top3_amount` calculated column,
          // which itself uses the custom `TOP` aggregation function.
          // Ties at the 3rd-largest value are all included.
          //
          // Note: AdapTableQL boolean literals here must be uppercase
          // (`TRUE` / `FALSE`); lowercase `true` and a bare column
          // reference are not currently accepted by the parser.
          Rule: '[top3_amount] = TRUE',
          Style: {
            ForeColor: 'var(--ab-color-palette-24)',
            FontWeight: 'Bold',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'item',
            'amount',
            'rank_amount',
            '2nd_largest_amount',
            'top5_amount',
            'currency',
            'rating',
            'sum_square_rating',
            'sum_square_rating_ccy',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    headerName: 'id',
    field: 'Id',
    filter: true,
    editable: false,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Item',
    field: 'item',
    filter: true,
    editable: false,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Amount',
    field: 'amount',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'number',
  },
  {
    headerName: 'Currency',
    field: 'currency',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Purchased',
    field: 'purchased',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'date',
  },
  {
    headerName: 'Rating',
    field: 'rating',
    filter: true,
    editable: true,
    sortable: true,
    cellDataType: 'number',
  },
];
```

**`src/rowData.ts`**

```ts
export const rowData = [
  {
    id: 1,
    item: 'Washing Machine',
    amount: 500.35,
    currency: 'EUR',
    purchased: new Date(2023, 5, 11),
    rating: 2,
  },
  {
    id: 2,
    item: 'Football',
    amount: 2.7,
    currency: 'GBP',
    purchased: new Date(2022, 7, 19),
    rating: 4,
  },
  {
    id: 3,
    item: 'Fridge',
    amount: 385.75,
    currency: 'USD',
    purchased: new Date(2021, 4, 5),
    rating: 3,
  },
  {
    id: 4,
    item: 'Food',
    amount: 195,
    currency: 'CHF',
    purchased: new Date(2021, 3, 15),
    rating: 2,
  },
  {
    id: 5,
    item: 'Holiday',
    amount: 1187.5,
    currency: 'GBP',
    purchased: new Date(2019, 8, 7),
    rating: 1,
  },
  {
    id: 6,
    item: 'Misc',
    amount: 56.23,
    currency: 'EUR',
    purchased: new Date(2023, 4, 5),
    rating: 8,
  },
  {
    id: 7,
    item: 'Laptop',
    amount: 2500,
    currency: 'EUR',
    purchased: new Date(2022, 8, 3),
    rating: 7,
  },
  {
    id: 8,
    item: 'Sport Tickets',
    amount: 904,
    currency: 'EUR',
    purchased: new Date(2019, 2, 24),
    rating: 3,
  },
  {
    id: 9,
    item: 'Clothes',
    amount: 480.25,
    currency: 'USD',
    purchased: new Date(2023, 5, 29),
    rating: 6,
  },
  {
    id: 10,
    item: 'Concert Ticket',
    amount: 235.45,
    currency: 'USD',
    purchased: new Date(2023, 7, 15),
    rating: 4,
  },
  {
    id: 11,
    item: 'Rent',
    amount: 652.75,
    currency: 'GBP',
    purchased: new Date(2021, 4, 23),
    rating: 4,
  },
];
```

## Reference

Custom Aggregation Functions are defined using the `customAggregatedFunctions` property in Expression Options.

### `customAggregatedFunctions`

Custom Aggregated Expression Functions available in AdapTableQL

Lists Custom Aggregated Expression Functions to add to AdapTableQL.

The property is either:

- a Record of function name → [`AggregatedExpressionFunction`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md)
- a JavaScript function which returns the same

```ts
  customAggregatedFunctions?:
    | Record<string, AggregatedExpressionFunction>
    | ((
        context: GlobalExpressionFunctionsContext<string>
      ) => Record<string, AggregatedExpressionFunction>);
```

To limit which of the two Aggregated Modules (`'Alert'` | `'CalculatedColumn'`) can use a function, set `isAvailable` — see [Custom Expression Function Scope](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom-scope/index.md).

Each Aggregated Custom Function is an [`AggregatedExpressionFunction`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md). 

This is a **different** authoring shape from Standard customs (`handler` / `operands` / `extends` do not apply here).

### Understanding Authoring properties

| Area                | Properties                                               | Role                                                                                                                                                       |
| ------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic (required)    | `initialValue`, `reducer`                                | Start the accumulator and fold each row value                                                                                                              |
| Advanced (optional) | `processAggregatedValue`, `prepareRowValue`, `filterRow` | Post-process once, derive a per-row result, or exclude rows before the reducer                                                                             |
| Capabilities        | `cumulative`, `weight`, `returnType`                     | Accept `CUMULATIVE(...)` / `WEIGHT(...)` clauses; declare the static result type — see [Declared Capabilities](#declared-capabilities)                     |
| Editor docs         | `description`, `signatures`, `examples`, `category`      | Expression Editor help and Functions-menu grouping                                                                                                         |
| Argument types      | `inputTypes`                                             | Optional types for editor Column cues                                                                                                                      |
| Availability        | `isAvailable`                                            | `Alert` and/or `CalculatedColumn` only — see [Custom Expression Function Scope](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions-custom-scope/index.md) |

Toolbar chips are separate: add them with `expressionOptions.expressionEditorButtons`.

| Property | Type | Description |
| --- | --- | --- |
| [category](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#category) | `string` | Freeform Functions-menu section for Alert Aggregated / Calculated Column<br/>Aggregated editors. Omit (or use `'Aggregation'`) to list under Aggregation;<br/>any other string becomes its own section label. |
| [cumulative](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#cumulative) | `boolean \| \{ currentValue: (context: `[`AggregatedExpressionCumulativeValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressioncumulativevaluecontext.md)`) => any; \}` | Accept a `CUMULATIVE([orderColumn])` clause, e.g.<br/>`MY_AGG{[notional], CUMULATIVE([tradeDate])}`.<br/><br/>- `true` — generic running variant: rows are visited in `CUMULATIVE`<br/> order (per `GROUP_BY` partition when grouped), `reducer` accumulates,<br/> and the value recorded for each row is `processAggregatedValue` (or<br/> the accumulator when absent) evaluated on the prefix so far.<br/>- object — override the per-row read with `currentValue` when<br/> `processAggregatedValue` is too expensive to run per row or the<br/> running value is not a function of the accumulator alone.<br/><br/>Declaring the capability also makes the clause known to validation, the<br/>Expression Editor clause chips / Cumulative editor and the Query Builder. |
| [description](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#description) | `string` | What the aggregation evaluates to (outcome), shown in editor<br/>documentation. Often starts with &quot;Returns …&quot;. |
| [examples](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#examples) | `string[]` | Examples to use the Aggregated Expression Function |
| [filterRow](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#filterrow) | `(context: `[`AggregatedExpressionFilterRowContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md)`) => boolean` | Optional filter which is applied to each row before the reducer is called. If the filter returns false, the row is NOT included in the aggregation. |
| [initialValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#initialvalue) | `any` | Mandatory Initial Value for the aggregation.<br/><br/>May be a plain value or a factory function returning a fresh value.<br/>Use a factory when the reducer mutates its accumulator (objects, arrays,<br/>Maps, Sets) — plain object values are deep-cloned per aggregation run<br/>(and per group) for backward compatibility, which is slower. |
| [inputTypes](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#inputtypes) | `ExpressionFunctionInputType[]` | Optional argument types. |
| [isAvailable](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#isavailable) | [`AdaptableAggregatedExpressionModule`](https://www.adaptabletools.com/docs/reference/adaptableaggregatedexpressionmodule.md)`[] \| ((context: `[`ExpressionFunctionAvailabilityContext`](https://www.adaptabletools.com/docs/reference/expressionfunctionavailabilitycontext.md)`) => boolean)` | Where the function is available — same semantics as standard<br/>`isAvailable`, but restricted to <br/>(Alert Aggregated and Calculated Column Aggregated).<br/>`undefined` means both aggregated expression modules. |
| [prepareRowValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#preparerowvalue) | `(context: `[`AggregatedExpressionPrepareRowValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md)`) => number \| string \| boolean \| Date \| undefined` | Called for each row AFTER the reducer() and processAggregatedValue() functions<br/>Can be used when each row has a different aggregated value (e.g. percentage = row value / aggregated value).<br/>Returns return value for each individual row (a boolean suits a boolean Calculated Column, e.g. &quot;is in the top K&quot;) |
| [processAggregatedValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#processaggregatedvalue) | `(context: `[`AggregatedExpressionProcessAggValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md)`) => any` | Called AFTER the reducer() has processed all values / rows<br/>Can be used to change result of reducer based on the values array (e.g. average = aggregated value / count) |
| [reducer](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#reducer) | `(context: `[`AggregatedExpressionReducerContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md)`) => any` | Mandatory Reducer function which is called for each value(row) in the Column Data |
| [returnType](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#returntype) | [`AggregatedExpressionReturnType`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreturntype.md) | Static result type of the aggregation. Drives the Calculated Column data<br/>type, the outer expression type check and editor documentation.<br/>`'input'` = same type as the aggregated column (MIN / MAX style). When<br/>omitted the result type is unknown (Calculated Columns default to number). |
| [signatures](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#signatures) | `string[]` | Example Signatures for the Aggregated Expression Function |
| [weight](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfunction.md#weight) | `boolean` | Accept a `WEIGHT([column])` clause, e.g.<br/>`MY_VWAP{[price], WEIGHT([quantity])}`. The resolved weight of the<br/>current row is delivered as `weightValue` on the `reducer`,<br/>`prepareRowValue` and `filterRow` contexts (and on the cumulative<br/>`currentValue` context). |

There are a range of Contexts passed to each Hook.

### Digging into the Contexts passed to each hook

Unlike Standard `handler`s, these callbacks still receive an AG Grid `rowNode`. 

Prefer `getValueForColId` and `aggColumnId` over calling `gridApi` yourself.

**`reducer`** — [`AggregatedExpressionReducerContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md):

| Property | Type | Description |
| --- | --- | --- |
| [accumulator](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#accumulator) | `any` | Value returned by the previous call to the reducer function, or the initialValue if this is the first call. You return the new accumulator value from this function. |
| [aggColumnId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#aggcolumnid) | `string` | Column Id of the column being aggregated |
| [args](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#args) | `any[]` | Arguments passed to the function |
| [currentValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#currentvalue) | `any` | Current value being processed in the Column Data |
| [getValueForColId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#getvalueforcolid) | `(colId: string) => any` | Helper function to get the value of a column |
| [groupByColumnIds](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#groupbycolumnids) | `string[]` | Column Id(s) of the column(s) being grouped by |
| [index](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#index) | `number` | Index of the current value in the Column Data |
| [rowNode](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#rownode) | `IRowNode` | Current row node |
| [weightValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#weightvalue) | `any` | Resolved `WEIGHT([column])` value for the current row.<br/>Only present when the function declares `weight: true` and the call<br/>supplies a WEIGHT clause. |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/aggregatedexpressionreducercontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**`processAggregatedValue`** — [`AggregatedExpressionProcessAggValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md):

| Property | Type | Description |
| --- | --- | --- |
| [aggColumnId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#aggcolumnid) | `string` | Column Id of the column being aggregated |
| [aggregatedValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#aggregatedvalue) | `any` | Result of the reducer |
| [args](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#args) | `any[]` | Arguments passed to the function |
| [groupByColumnIds](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#groupbycolumnids) | `string[]` | Column Id(s) of the column(s) being grouped by |
| [rowNodes](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#rownodes) | `IRowNode[]` | Array of row nodes; if aggregation is grouped, this will be the array of row nodes for the group |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/aggregatedexpressionprocessaggvaluecontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**`prepareRowValue`** — [`AggregatedExpressionPrepareRowValueContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md):

| Property | Type | Description |
| --- | --- | --- |
| [aggColumnId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#aggcolumnid) | `string` | Column Id of the column being aggregated |
| [aggregatedValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#aggregatedvalue) | `any` | Result of the reducer (for `CUMULATIVE` calls: the running value<br/>recorded for this row) |
| [args](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#args) | `any[]` | Arguments passed to the function |
| [getValueForColId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#getvalueforcolid) | `(colId: string) => any` | Helper function to get the value of a column |
| [groupByColumnIds](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#groupbycolumnids) | `string[]` | Column Id(s) of the column(s) being grouped by |
| [rowNode](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#rownode) | `IRowNode` | Current Row Node |
| [weightValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#weightvalue) | `any` | Resolved `WEIGHT([column])` value for the current row (see `weight`). |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/aggregatedexpressionpreparerowvaluecontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

**`filterRow`** — [`AggregatedExpressionFilterRowContext`](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md) (runs **before** the reducer; return `false` to skip the row):

| Property | Type | Description |
| --- | --- | --- |
| [aggColumnId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#aggcolumnid) | `string` | Column Id of the column being aggregated<br/>Usually the first Col argument, e.g. [colId] |
| [args](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#args) | `any[]` | Arguments passed to the function |
| [getValueForColId](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#getvalueforcolid) | `(colId: string) => any` | Utility function to get the value of a column |
| [groupByColumnIds](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#groupbycolumnids) | `string[]` | Column Id(s) of the column(s) being grouped by |
| [rowNode](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#rownode) | `IRowNode` | Current row node |
| [weightValue](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#weightvalue) | `any` | Resolved `WEIGHT([column])` value for the current row (see `weight`). |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/aggregatedexpressionfilterrowcontext.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |

All of these contexts include `args`. Column arguments are already resolved to values, except the aggregation Column and any `GROUP_BY` Columns, which arrive as `aggColumnId` / `groupByColumnIds`.

`prepareRowValue` can return a `number`, `string`, `boolean` or `Date` (or `undefined`); return a boolean for a boolean Calculated Column (see `TOP` in the demo).

### FAQ

**Does the Custom Expression Function's name have to be capitalised?**
No, it is not mandatory, but it is a convention we encourage, as it makes the Expression more readable.

**Can I use a custom aggregation in a Row Summary?**
No. Custom aggregations are Calculated Column Aggregated and Alert Aggregated only.

**Is this the same object as a Standard custom function?**
No. Standard customs are `AdaptableCustomExpressionFunction` (`handler`, `returnType`, `operands`). 
Aggregated customs are `AggregatedExpressionFunction` (`initialValue`, `reducer`, …).
