# Relative Change Expressions

Canonical page: https://www.adaptabletools.com/docs/adaptable-ql-expression-relative-change

- Relative Change Expressions evaluate the type of change made to a cell's data
- `ANY_CHANGE` returns a boolean; `ABSOLUTE_CHANGE` and `PERCENT_CHANGE` return the size of the change, which is compared to give a boolean rule
- They are only available in the Flashing Cell and Alert Modules (which evaluate against a data change)

Relative Change Expressions examine the nature of changes made to a cell's data.

They are a specialist form of [Standard Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression-standard/index.md) — still evaluated per row, but against the **change** rather than the current cell value

AdapTableQL provides 3 [Relative Change Expression Functions](https://www.adaptabletools.com/docs/adaptable-ql-expression-functions/index.md) to deal with different use cases:
- `ANY_CHANGE`
- `ABSOLUTE_CHANGE`
- `PERCENT_CHANGE`

**Example: AdapTableQL: Relative Change Expressions**

Using all 3 Relative Change Functions on a ticking price feed

- A price feed updates `Last` and `Volume` - occasionally `Last` jumps by 1.5% - 3% and `Volume` sees a block trade
- 2 [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) are configured:
  - `Last` flashes green or red only for a big move - `PERCENT_CHANGE($SCOPE) > 1`
  - `Volume` flashes on every update - `ANY_CHANGE($SCOPE)`
- A Relative Change [Alert](https://www.adaptabletools.com/docs/handbook-alerting-relative-change/index.md) fires for a block trade - `ABSOLUTE_CHANGE([volume], 'INCREASE') > 50000`

- Watch `Last` - most ticks are small and do not flash; only moves of more than 1% flash
- See the `Block Trade` Alert in the Status Bar (and the highlighted `Volume` cell)
- Edit the Flashing Cell Rule to `PERCENT_CHANGE($SCOPE, 'DECREASE') > 1` so that only falls flash

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
  priceFeed.ts
  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} from '@adaptabletools/adaptable';
import {Quote} from './rowData';

export const adaptableOptions: AdaptableOptions<Quote> = {
  primaryKey: 'id',
  adaptableId: 'Relative Change Expressions',
  initialState: {
    Dashboard: {
      ModuleButtons: ['FlashingCell', 'Alert'],
      Tabs: [{Name: 'Alerts', Toolbars: ['Alert']}],
    },
    StatusBar: {
      StatusBars: [{Key: 'Center Panel', StatusBarPanels: ['Alert']}],
    },
    Theme: {CurrentTheme: 'dark'},
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'big-price-move',
          Type: 'Change',
          Scope: {ColumnIds: ['last']},
          Rule: 'PERCENT_CHANGE($SCOPE) > 1',
          UpChangeStyle: {BackColor: '#2e7d32', ForeColor: 'var(--ab-color-palette-14)'},
          DownChangeStyle: {BackColor: '#c62828', ForeColor: 'var(--ab-color-palette-14)'},
          FlashDuration: 1500,
        },
        {
          Name: 'volume-tick',
          Type: 'Change',
          Scope: {ColumnIds: ['volume']},
          Rule: 'ANY_CHANGE($SCOPE)',
          UpChangeStyle: {BackColor: '#37474f', ForeColor: 'var(--ab-color-palette-14)'},
          FlashDuration: 300,
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'block-trade',
          Type: 'RelativeChange',
          MessageType: 'Info',
          MessageHeader: 'Block Trade',
          MessageText: 'Volume jumped by more than 50,000',
          Scope: {ColumnIds: ['volume']},
          Rule: "ABSOLUTE_CHANGE([volume], 'INCREASE') > 50000",
          AlertProperties: {DisplayNotification: false, HighlightCell: true},
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'price-format',
          Scope: {ColumnIds: ['last']},
          DisplayFormat: {Formatter: 'NumberFormatter', Options: {FractionDigits: 2}},
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Quotes',
      Layouts: [
        {
          Name: 'Quotes',
          TableColumns: ['symbol', 'name', 'sector', 'last', 'volume'],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/priceFeed.ts`**

```ts
import {AdaptableApi} from '@adaptabletools/adaptable';
import {Quote} from './rowData';

const TICK_MS = 300;
// 1 in 8 price ticks is a jump of 1.5% - 3%; 1 in 10 volume ticks is a block trade
const JUMP_CHANCE = 0.125;
const BLOCK_TRADE_CHANCE = 0.1;

let intervalId: ReturnType<typeof setInterval> | undefined;

const randomBetween = (min: number, max: number) => Math.random() * (max - min) + min;

const nextPrice = (last: number) => {
  const move =
    Math.random() < JUMP_CHANCE
      ? randomBetween(0.015, 0.03) * (Math.random() < 0.5 ? -1 : 1)
      : randomBetween(-0.003, 0.003);
  return Math.round(last * (1 + move) * 100) / 100;
};

const nextVolume = (volume: number) =>
  volume +
  Math.round(
    Math.random() < BLOCK_TRADE_CHANCE ? randomBetween(60_000, 120_000) : randomBetween(500, 20_000)
  );

const tickOnce = (api: AdaptableApi) => {
  const rows = api.gridApi
    .getVisibleRowNodes()
    .map((node) => node.data as Quote)
    .filter(Boolean);
  if (!rows.length) {
    return;
  }
  const row = rows[Math.floor(Math.random() * rows.length)];
  const update =
    Math.random() < 0.5 ? {...row, last: nextPrice(row.last)} : {...row, volume: nextVolume(row.volume)};
  api.gridApi.updateGridData([update]);
};

export const startPriceFeed = (api: AdaptableApi) => {
  stopPriceFeed();
  intervalId = setInterval(() => tickOnce(api), TICK_MS);
};

export const stopPriceFeed = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = undefined;
  }
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {startPriceFeed} from './priceFeed';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  startPriceFeed(adaptableApi);
};
```

**`src/rowData.ts`**

```ts
export interface Quote {
  id: number;
  symbol: string;
  name: string;
  sector: string;
  last: number;
  volume: number;
}

export const rowData: Quote[] = [
  {id: 1, symbol: 'AAPL', name: 'Apple', sector: 'Technology', last: 189.2, volume: 1_250_000},
  {id: 2, symbol: 'MSFT', name: 'Microsoft', sector: 'Technology', last: 415.5, volume: 980_000},
  {id: 3, symbol: 'NVDA', name: 'NVIDIA', sector: 'Technology', last: 875.0, volume: 2_400_000},
  {id: 4, symbol: 'AMZN', name: 'Amazon', sector: 'Consumer', last: 178.6, volume: 1_100_000},
  {id: 5, symbol: 'TSLA', name: 'Tesla', sector: 'Consumer', last: 248.3, volume: 1_900_000},
  {id: 6, symbol: 'JPM', name: 'JPMorgan Chase', sector: 'Financials', last: 198.7, volume: 640_000},
  {id: 7, symbol: 'GS', name: 'Goldman Sachs', sector: 'Financials', last: 452.3, volume: 310_000},
  {id: 8, symbol: 'XOM', name: 'Exxon Mobil', sector: 'Energy', last: 118.2, volume: 720_000},
  {id: 9, symbol: 'CVX', name: 'Chevron', sector: 'Energy', last: 156.4, volume: 540_000},
  {id: 10, symbol: 'UNH', name: 'UnitedHealth', sector: 'Healthcare', last: 528.0, volume: 410_000},
];
```

**`src/columnDefs.ts`**

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

export const columnDefs: ColDef<Quote>[] = [
  {field: 'id', hide: true, cellDataType: 'number'},
  {field: 'symbol', headerName: 'Symbol', cellDataType: 'text'},
  {field: 'name', headerName: 'Name', cellDataType: 'text'},
  {field: 'sector', headerName: 'Sector', cellDataType: 'text'},
  {field: 'last', headerName: 'Last', cellDataType: 'number', type: 'rightAligned'},
  {field: 'volume', headerName: 'Volume', cellDataType: 'number', type: 'rightAligned'},
];
```

**`src/gridOptions.ts`**

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

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

export const gridOptions: GridOptions<Quote> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: false,
    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',
      },
    ],
  },
};
```

## Any Change

The `ANY_CHANGE` function checks if any change whatsoever has been made to a cell's value.

This is commonly used when setting up [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md)

```ts [[2, 2, "ANY_CHANGE"], [1, 2, "PRICE"]]
 // A data change of any value has been made to the Price Column
 ANY_CHANGE([PRICE])
```

When used with [Column Scope](https://www.adaptabletools.com/docs/dev-guide-columns-scope/index.md) (in an Alert or Flashing Cell), `$SCOPE` refers to the column that changed:

```ts [[2, 2, "ANY_CHANGE"], [1, 2, "$SCOPE"]]
 // Same rule, using the Alert / Flashing Cell Column Scope
 ANY_CHANGE($SCOPE)
```

## Absolute Change

The `ABSOLUTE_CHANGE` function is used when you want to check if the change is of a certain amount.

It most commonly takes a (numeric) Column as the first argument (or `$SCOPE` for the scoped / changed column).

The Column must be numeric as the evaluation only works on numeric values

```ts [[2, 2, "ABSOLUTE_CHANGE"], [1, 2, "PRICE"], [2, 2, ">"], [4, 2, "10"]]
 // Value in the Price Column has changed by more than 10
 ABSOLUTE_CHANGE([PRICE]) > 10
```

```ts [[2, 2, "ABSOLUTE_CHANGE"], [1, 2, "$SCOPE"], [2, 2, ">"], [4, 2, "10"]]
 // Same rule, using the Alert / Flashing Cell Column Scope
 ABSOLUTE_CHANGE($SCOPE) > 10
```

It is possible to use "INCREASE" to limit the evaluation to changes where new value goes up...

```ts [[2, 2, "ABSOLUTE_CHANGE"], [1, 2, "PRICE"], [4, 2, "'INCREASE'"], [2, 2, ">"], [4, 2, "10"]]
 // Value in the Price Column has increased by more than 10
 ABSOLUTE_CHANGE([PRICE], 'INCREASE') > 10
```

...or "DECREASE" to limit the evaluation to changes where new values goes down

```ts [[2, 2, "ABSOLUTE_CHANGE"], [1, 2, "PRICE"], [4, 2, "'DECREASE'"], [2, 2, "="], [4, 2, "5"]]
 // Value in the Price Column has decreased by 5
 ABSOLUTE_CHANGE([PRICE], 'DECREASE') = 5
```

## Percent Change

The `PERCENT_CHANGE` function is similar to `ABSOLUTE_CHANGE`, but used to evaluate the relative change in value.

It most commonly takes a (numeric) Column as the first argument (or `$SCOPE` for the scoped / changed column).

The Column must be numeric as the evaluation only works on numeric values

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "PRICE"], [2, 2, ">"], [4, 2, "10"]]
 // Value in the Price Column has changed by more than 10%
 PERCENT_CHANGE([PRICE]) > 10
```

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "$SCOPE"], [2, 2, ">"], [4, 2, "10"]]
 // Same rule, using the Alert / Flashing Cell Column Scope
 PERCENT_CHANGE($SCOPE) > 10
```

Again, you can use "INCREASE" to limit the evaluation to upward percentage changes...

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "PRICE"], [4, 2, "'INCREASE'"], [2, 2, ">"], [4, 2, "50"]]
 // Value in the Price Column has increased by more than 50%
 PERCENT_CHANGE([PRICE], 'INCREASE') > 50
```

...or "DECREASE" to limit the evaluation to downward percentage changes

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "PRICE"], [4, 2, "'DECREASE'"], [2, 2, "="], [4, 2, "10"]]
 // Value in the Price Column has decreased by 10%
 PERCENT_CHANGE([PRICE], 'DECREASE') = 10
```

- See [Relative Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-relative-change/index.md) for more details and a demo
- See the [Guide to Writing Expressions](https://www.adaptabletools.com/docs/adaptable-ql-expression-writing/index.md) for how these Functions sit in a Boolean Expression
