# Observable Expressions

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

- Observable Expressions read **change history** (and time) and return a **value** 
- The value can be a number, date, duration, or something you compare in a boolean rule
- Observable Functions always use **curly braces** (never parentheses)
- They compose like all other expressions, e.g. arithmetic, comparisons, `CASE`, other Functions etc
- Available in [Alerts](https://www.adaptabletools.com/docs/handbook-alerting-observables/index.md), [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md), [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) and [Conditional Styles](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions-observable/index.md)

Observable Expressions watch **how** data has changed in AG Grid over time.

They work by leveraging AdapTable's recorded cell / row history.

- **Questions about time, in 1 line**: *ticked 10 times in 10 sec*, *highest price in last 5 mins*, *moved 2% in last minute*
- **Detect silence**: spot a stale price or a feed that has stopped - something no single data change can tell you
- **No event-handling code**: no timers, buffers or subscriptions to write & maintain; AdapTable records history for you
- **Use the answer anywhere**: show it in a Calculated Column, style or flash a cell with it, or fire an Alert on it
- **Built for live data**: a natural fit for ticking prices, positions and order books

- Observable Expressions are also ideal for detecting **silence** or lack of changes
- e.g. `NO_CHANGES{[price], WITHIN(20s)}` is true when price has been quiet for 20 seconds

Observable Expressions are used in 4 AdapTable Modules:

| Module                                                                                                  | Typical use                                     |
| ------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| [Observable Alerts](https://www.adaptabletools.com/docs/handbook-alerting-observables/index.md)                           | Fire when a live boolean rule becomes true      |
| [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md)                  | Display a live value (e.g. highest price today) |
| [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md)                                     | Flash while an Observable Condition is true     |
| [Format Column Conditions](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions-observable/index.md) | Style a cell while a live Condition is true     |

AG Grid keeps no cell history: it can flash a cell when it changes, but cannot say how often or how far it has moved

**Example: AdapTableQL: Observable Expressions**

Watching a ticking price feed with Observable Expressions

- A price feed updates `Last` 4 times a second - `NVDA` ticks far more often than the rest, while `XOM` and `CVX` never tick
- 4 Observable [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-observable/index.md) show live values for each row:
  - `Ticks (1m)` - `CHANGE_COUNT{[last], WITHIN(1m)}`
  - `Move % (1m)` - `PERCENT_CHANGE{[last], WITHIN(1m)}`
  - `High (5m)` and `Low (5m)` - `HIGHEST{[last], WITHIN(5m)}` and `LOWEST{[last], WITHIN(5m)}`
- 2 [Conditional Styles](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions-observable/index.md) style the `Last` Column:
  - **stale** (grey) - `NO_CHANGES{[last], WITHIN(15s)}`
  - **at the 5 minute high** (green) - `[last] = HIGHEST{[last], WITHIN(5m)}`
- An Observable [Alert](https://www.adaptabletools.com/docs/handbook-alerting-observables/index.md) fires for a busy symbol - `CHANGE_COUNT{[last], WITHIN(10s)} >= 10`

- Watch `XOM` and `CVX` turn grey after 15 seconds — they never tick, so `NO_CHANGES` becomes true
- See the `Busy Symbol` Alert fire for `NVDA` in the Status Bar
- Click **Pause Feed** - after 15 seconds every row turns grey; click **Resume Feed** to restart it

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';
import {startPriceFeed, stopPriceFeed} from './priceFeed';

export const adaptableOptions: AdaptableOptions<Quote> = {
  primaryKey: 'id',
  adaptableId: 'Observable Expressions',
  expressionOptions: {
    liveRefreshIntervalMs: 1000,
  },
  dashboardOptions: {
    customToolbars: [
      {
        name: 'priceFeed',
        title: 'Price Feed',
        toolbarButtons: [
          {
            label: 'Pause Feed',
            onClick: () => stopPriceFeed(),
            buttonStyle: {tone: 'warning', variant: 'raised'},
          },
          {
            label: 'Resume Feed',
            onClick: (_button, context) => startPriceFeed(context.adaptableApi),
            buttonStyle: {tone: 'success', variant: 'raised'},
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn', 'FormatColumn', 'Alert'],
      Tabs: [{Name: 'Toolbars', Toolbars: ['priceFeed', 'Alert']}],
    },
    StatusBar: {
      StatusBars: [{Key: 'Center Panel', StatusBarPanels: ['Alert']}],
    },
    Theme: {CurrentTheme: 'dark'},
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'ticks-1m',
          FriendlyName: 'Ticks (1m)',
          Type: 'Observable',
          Expression: 'CHANGE_COUNT{[last], WITHIN(1m)}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'move-1m',
          FriendlyName: 'Move % (1m)',
          Type: 'Observable',
          Expression: 'PERCENT_CHANGE{[last], WITHIN(1m)}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'high-5m',
          FriendlyName: 'High (5m)',
          Type: 'Observable',
          Expression: 'HIGHEST{[last], WITHIN(5m)}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
        {
          ColumnId: 'low-5m',
          FriendlyName: 'Low (5m)',
          Type: 'Observable',
          Expression: 'LOWEST{[last], WITHIN(5m)}',
          CalculatedColumnSettings: {DataType: 'number'},
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'stale-price',
          Scope: {ColumnIds: ['symbol', 'last']},
          Rule: 'NO_CHANGES{[last], WITHIN(15s)}',
          Style: {BackColor: '#5f6368', ForeColor: '#e0e0e0', FontStyle: 'Italic'},
        },
        {
          Name: 'at-5m-high',
          Scope: {ColumnIds: ['last']},
          Rule: '[last] = HIGHEST{[last], WITHIN(5m)}',
          Style: {ForeColor: '#2e7d32', FontWeight: 'Bold'},
        },
        {
          Name: 'price-format',
          Scope: {ColumnIds: ['last', 'high-5m', 'low-5m']},
          DisplayFormat: {Formatter: 'NumberFormatter', Options: {FractionDigits: 2}},
        },
        {
          Name: 'move-format',
          Scope: {ColumnIds: ['move-1m']},
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {FractionDigits: 2, Suffix: '%'},
          },
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'busy-symbol',
          Type: 'Observable',
          MessageType: 'Warning',
          MessageHeader: 'Busy Symbol',
          MessageText: 'Last has ticked 10 or more times in 10 seconds',
          Scope: {All: true},
          Rule: 'CHANGE_COUNT{[last], WITHIN(10s)} >= 10',
          AlertProperties: {DisplayNotification: false},
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Live Prices',
      Layouts: [
        {
          Name: 'Live Prices',
          TableColumns: [
            'symbol',
            'name',
            'sector',
            'last',
            'ticks-1m',
            'move-1m',
            'high-5m',
            'low-5m',
            'volume',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/priceFeed.ts`**

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

const TICK_MS = 250;
// NVDA is a "hot" symbol; XOM and CVX never tick, so they go stale
const HOT_SYMBOL = 'NVDA';
const SILENT_SYMBOLS = ['XOM', 'CVX'];

let intervalId: ReturnType<typeof setInterval> | undefined;

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

const tickOnce = (api: AdaptableApi) => {
  const rows = api.gridApi
    .getVisibleRowNodes()
    .map((node) => node.data as Quote)
    .filter((row) => row && !SILENT_SYMBOLS.includes(row.symbol));
  if (!rows.length) {
    return;
  }
  const hot = rows.find((row) => row.symbol === HOT_SYMBOL);
  const row =
    hot && Math.random() < 0.4 ? hot : rows[Math.floor(Math.random() * rows.length)];

  const last = Math.round(row.last * (1 + randomBetween(-0.004, 0.004)) * 100) / 100;
  const volume = row.volume + Math.round(randomBetween(500, 20_000));
  api.gridApi.updateGridData([{...row, last, volume}]);
};

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',
      },
    ],
  },
};
```

## Observable Functions

There are a large range of Observable Functions provided by AdapTable.

- Write Observable Functions with **curly braces** (as with Aggregations); use parentheses for Standard Functions
- e.g. `PERCENT_CHANGE([bid])` is Standard function; `PERCENT_CHANGE{[bid], WITHIN(1h)}` is Observable function

Each Observable Function returns a **value**:

| Function         | Description                                  |
| ---------------- | -------------------------------------------- |
| `CHANGE_COUNT`   | How many times a cell has changed            |
| `NO_CHANGES`     | True when nothing changed in the timeframe   |
| `SINCE_CHANGE`   | How long ago the last change was             |
| `CHANGED_AT`     | When the last change happened                |
| `NET_CHANGE`     | Current value minus start-of-timeframe value |
| `PERCENT_CHANGE` | Percent move over the timeframe              |
| `HIGHEST`        | Highest value in the timeframe               |
| `LOWEST`         | Lowest value in the timeframe                |
| `PREVIOUS`       | Value before the last change (or _n_ ago)    |
| `ROW_AGE`        | How long ago this row was added              |
| `ADDED_AT`       | When this row was added                      |
| `ROWS_ADDED`     | How many rows were added (grid-wide)         |
| `ROWS_REMOVED`   | How many rows were removed (grid-wide)       |

- You can turn an Observable into a boolean rule by using standard comparison functions
- This allows you to create Observable Alerts or Observable Conditional Styles:

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "5m"]]
 // Alert if at least 3 changes to this row's price in the last 5 minutes
 CHANGE_COUNT{[price], WITHIN(5m)} >= 3
```

```ts [[1, 2, "price", 0], [2, 2, "HIGHEST"], [1, 2, "price", 20], [2, 2, "WITHIN"], [4, 2, "1h"]]
 // Style cells where Price is at its highest value in the last hour
 [price] = HIGHEST{[price], WITHIN(1h)}
```

Timeframe and clock-based Expressions continually re-evaluate as time passes.

Make sure that the `liveRefreshIntervalMs` property in [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md) is greater than `0` (default `1000`)

### `CHANGE_COUNT`

The `CHANGE_COUNT` function is most commonly used Observable function.

It returns how many times a cell has changed in a given time period.

This can be either in a sliding timeframe, or since the Grid loaded

The function returns a **number**.

- The function evaluates per row by default; add `ALL_ROWS()` to count changes of the column across all rows
- Additionally, use `ANY_COL()` to count changes of any column instead of a specified one

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "5m"]]
 // Changes to this row's price in the last 5 minutes
 CHANGE_COUNT{[price], WITHIN(5m)}
```

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "5m"]]
 // Alert / Format when the cell has moved at least 3 times in 5 minutes
 CHANGE_COUNT{[price], WITHIN(5m)} >= 3
```

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1m"], [2, 2, "ALL_ROWS"]]
 // Grid-wide: how many times price changed (any row) in the last minute
 CHANGE_COUNT{[price], WITHIN(1m), ALL_ROWS()}
```

```ts [[2, 2, "CHANGE_COUNT"], [2, 2, "ANY_COL"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Changes to any column on this row in the last minute
 CHANGE_COUNT{ANY_COL(), WITHIN(1m)}
```

### `NO_CHANGES`

`NO_CHANGES` is the other most commonly used Expression Function - and it checks for **silence**.

The function returns a **boolean** — true when nothing in the watched column (or, with `ANY_COL()`, in any column) changed during the whole window.

Prefer `NO_CHANGES` over `CHANGE_COUNT{…} = 0` for “has this gone quiet?” rules

The WITHIN clause sets the timeframe for the lack of changes.

- The window must have fully elapsed since Grid loaded, so is *false* at startup and *true* only after full silent window
- Without `WITHIN`, the value remains true while the cell has never changed

```ts [[2, 2, "NO_CHANGES"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "20s"]]
 // This row's price has been quiet for 20 seconds
 NO_CHANGES{[price], WITHIN(20s)}
```

```ts [[2, 2, "NO_CHANGES"], [2, 2, "ANY_COL"], [2, 2, "WITHIN"], [4, 2, "10s"], [2, 2, "ALL_ROWS"]]
 // Nothing has changed anywhere in the Grid for 10 seconds
 NO_CHANGES{ANY_COL(), WITHIN(10s), ALL_ROWS()}
```

`NO_CHANGES` accepts `WITHIN`, but not `LAST_N`.

### `SINCE_CHANGE`

`SINCE_CHANGE` returns how long ago the cell (or, with `ANY_COL()`, any column) last changed, as a **duration**.

The value keeps growing on the clock.

The value is `null` until the first change since the Grid loaded

```ts [[2, 2, "SINCE_CHANGE"], [1, 2, "price"]]
 // How long since this row's price last moved
 SINCE_CHANGE{[price]}
```

```ts [[2, 2, "SINCE_CHANGE"], [1, 2, "price"]]
 // Last tick was more than 30 seconds ago
 SINCE_CHANGE{[price]} > 30s
```

- For “no changes for x” rules prefer `NO_CHANGES{…}`
- `SINCE_CHANGE` is preferable when you wish to use a growing clock

### `CHANGED_AT`

`CHANGED_AT` returns the instant the cell (or, with `ANY_COL()`, any column) last changed, as a **date**.

The value is `null` until the first change since the Grid loaded

```ts [[2, 2, "CHANGED_AT"], [1, 2, "price"]]
 // When this row's price last moved
 CHANGED_AT{[price]}
```

```ts [[2, 2, "IS_TODAY"], [2, 2, "CHANGED_AT"], [1, 2, "price"]]
 // Last change was today
 IS_TODAY(CHANGED_AT{[price]})
```

### `NET_CHANGE`

`NET_CHANGE` returns the current value minus the value at the start of the timeframe (or when the grid loaded).

It returns a **number** (positive when the cell went up).

The value is `null` until the cell has changed

```ts [[2, 2, "NET_CHANGE"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1h"]]
 // Net move in price over the last hour
 NET_CHANGE{[price], WITHIN(1h)}
```

```ts [[2, 2, "NET_CHANGE"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1h"]]
 // Price has risen by more than 10 in the last hour
 NET_CHANGE{[price], WITHIN(1h)} > 10
```

```ts [[2, 2, "ABS"], [2, 2, "NET_CHANGE"], [1, 2, "price"], [2, 2, "LAST_N"]]
 // Absolute net move over the last 5 change events
 ABS(NET_CHANGE{[price], LAST_N(5)})
```

### `PERCENT_CHANGE`

`PERCENT_CHANGE` tracks the percentage move over the timeframe: `(current − start) / start × 100`.

The function returns a **number**.

- This is the **brace** (Observable) form
- See [Relative Change](https://www.adaptabletools.com/docs/adaptable-ql-expression-relative-change/index.md) for the Standard Function used in Alert / Flashing Cell change rules

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1h"]]
 // Percent move of this row's price over the last hour
 PERCENT_CHANGE{[price], WITHIN(1h)}
```

```ts [[2, 2, "PERCENT_CHANGE"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1h"]]
 // Price is up more than 5% in the last hour
 PERCENT_CHANGE{[price], WITHIN(1h)} > 5
```

### `HIGHEST`

`HIGHEST` returns the highest value the cell has taken in the timeframe (or since load).

It returns the same type as the watched column (`number` or `date`).

The value is `null` until the cell has changed

```ts [[2, 2, "HIGHEST"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "8h"]]
 // Highest price in the last 8 hours
 HIGHEST{[price], WITHIN(8h)}
```

```ts [[1, 2, "price", 0], [2, 2, "HIGHEST"], [1, 2, "price", 20], [2, 2, "WITHIN"], [4, 2, "8h"]]
 // At the high of the last 8 hours
 [price] = HIGHEST{[price], WITHIN(8h)}
```

```ts [[2, 2, "HIGHEST"], [1, 2, "price", 0], [2, 2, "LAST_N"], [1, 2, "price", 33]]
 // Distance from the high of the last 20 ticks
 HIGHEST{[price], LAST_N(20)} - [price]
```

### `LOWEST`

`LOWEST` returns the lowest value the cell has taken in the timeframe (or since load).

It has the same return behaviour as `HIGHEST`.

```ts [[2, 2, "LOWEST"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "8h"]]
 // Lowest price in the last 8 hours
 LOWEST{[price], WITHIN(8h)}
```

```ts [[1, 2, "price", 0], [2, 2, "LOWEST"], [1, 2, "price", 19], [2, 2, "WITHIN"], [4, 2, "8h"]]
 // At the low of the last 8 hours
 [price] = LOWEST{[price], WITHIN(8h)}
```

### `PREVIOUS`

`PREVIOUS` returns the value the cell had before its last change (or before its last _n_ changes).

It returns the same type as the watched column.

The value is `null` until enough changes have occurred

```ts [[2, 2, "PREVIOUS"], [1, 2, "price"]]
 // Previous price for this row
 PREVIOUS{[price]}
```

```ts [[1, 2, "price", 0], [2, 2, "PREVIOUS"], [1, 2, "price", 21]]
 // Move versus the previous tick (useful in Calculated Columns)
 [price] - PREVIOUS{[price]}
```

Unlike most observable functions, `PREVIOUS` does **not** take `WITHIN` or `LAST_N`.

Instead, pass a number as a "lookback" to go back more than one change:

```ts [[1, 2, "price", 0], [2, 2, "PREVIOUS"], [1, 2, "price", 21]]
 // Higher than three changes ago
 [price] > PREVIOUS{[price], 3}
```

`PREVIOUS` does accept the `ALL_ROWS()`, `TRIGGER` and `WHERE` clauses (see Timeframes & Clauses below):

```ts [[2, 2, "PREVIOUS"], [1, 2, "price"], [2, 2, "TRIGGER"]]
 // Price before the last user edit (ignores streaming ticks)
 PREVIOUS{[price], TRIGGER('edit')}
```

```ts [[2, 2, "PREVIOUS"], [1, 2, "price"], [2, 2, "ALL_ROWS"]]
 // Previous price change anywhere in the grid (same value on every row)
 PREVIOUS{[price], ALL_ROWS()}
```

### `ROW_AGE`

`ROW_AGE` tracks how long ago the row was added to the grid, as a **duration**.

The value keeps growing on the clock.

The value is `null` for rows already present when the grid loaded

There is no column input and no timeframe clauses.

```ts [[2, 2, "ROW_AGE"]]
 // Age of this row
 ROW_AGE{}
```

```ts [[2, 2, "ROW_AGE"]]
 // Row added in the last 30 seconds
 ROW_AGE{} < 30s
```

```ts [[2, 2, "ROW_AGE"]]
 // Stale row — present for more than an hour
 ROW_AGE{} > 1h
```

### `ADDED_AT`

`ADDED_AT` returns the instant the row was added, as a **date**.

The value is `null` for rows already present when the grid loaded

```ts [[2, 2, "ADDED_AT"]]
 // When this row was added
 ADDED_AT{}
```

```ts [[2, 2, "ADDED_AT"], [2, 2, "DATE"]]
 // Added after a given date
 ADDED_AT{} > DATE('2026-01-01')
```

```ts [[2, 2, "IS_TODAY"], [2, 2, "ADDED_AT"]]
 // Added today
 IS_TODAY(ADDED_AT{})
```

### `ROWS_ADDED`

`ROWS_ADDED` returns how many rows were **added** to the grid in the timeframe (or since load).

This function is **always grid-scoped**, so there is no need to pass `ALL_ROWS()` as it is not required

```ts [[2, 2, "ROWS_ADDED"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Rows added in the last minute
 ROWS_ADDED{WITHIN(1m)}
```

```ts [[2, 2, "ROWS_ADDED"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Burst of adds
 ROWS_ADDED{WITHIN(1m)} > 10
```

```ts [[2, 2, "ROWS_ADDED"], [1, 2, "status"], [2, 2, "WITHIN"], [4, 2, "10s"]]
 // At least one Active row added in the last 10 seconds
 ROWS_ADDED{WHERE [status] = 'Active', WITHIN(10s)} >= 1
```

This function (and `ROWS_REMOVED` below) is often used when creating [Row Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md)

### `ROWS_REMOVED`

`ROWS_REMOVED` returns how many rows were **removed** from the grid in the timeframe (or since load).

```ts [[2, 2, "ROWS_REMOVED"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Removals in the last minute
 ROWS_REMOVED{WITHIN(1m)}
```

Like with `ROWS_ADDED`, this is always grid-scoped and often used in [Row Change Alerts](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md).

```ts [[2, 2, "ROWS_REMOVED"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Any removal in the last minute
 ROWS_REMOVED{WITHIN(1m)} > 0
```

## Timeframes & Clauses

Most Observable Expression Functions accept an optional timeframe.

Omit it to mean **since the grid loaded** (see Change History below)

There are 2 timeframes and 4 other clauses available:

| Clause       | Description                                         |
| ------------ | --------------------------------------------------- |
| `WITHIN`     | Sliding timeframe (e.g. last 5 minutes)             |
| `LAST_N`     | Sliding count timeframe (last _n_ change events)    |
| `ANY_COL()`  | Watch every column (or a listed set) instead of one |
| `ALL_ROWS()` | Shared history across all rows (not per row)        |
| `TRIGGER`    | Limit which change origins count (edit, tick, …)    |
| `WHERE`      | Filter which rows / changes enter the history       |

### `WITHIN`

`WITHIN` provides a sliding **timeframe**.

- Only changes in the last duration count
- Old changes age out, so the value can change on the clock even when the grid is quiet

It is possible to use duration literals.

There are 5 literals available:

| Literal | Example |
| ------- | ------- |
| 'ms'    | `250ms` |
| 's'     | `30s`   |
| 'm'     | `5m`    |
| 'h'     | `1h`    |
| 'd'     | `1d`    |

- A `WITHIN` timeframe cannot be longer than the `maxTimeframeSize` Expression Option (default 8 hours)
- A longer timeframe (e.g. `WITHIN(1d)`) **is reported as invalid** unless `maxTimeframeSize` is raised

```ts [[2, 2, "WITHIN"], [4, 2, "5m"]]
 // Changes to this row's price in the last 5 minutes
 CHANGE_COUNT{[price], WITHIN(5m)}
```

```ts [[2, 2, "WITHIN"], [4, 2, "8h"]]
 // Highest price in the last 8 hours
 HIGHEST{[price], WITHIN(8h)}
```

```ts [[2, 2, "WITHIN"], [4, 2, "10s"]]
 // Rows added in the last 10 seconds
 ROWS_ADDED{WITHIN(10s)}
```

### `LAST_N`

`LAST_N` provides a sliding **count** timeframe.

When this is used, only the last _n_ change events count, however old they might be.

- The value does not expire on the clock (unlike `WITHIN`)
- `WITHIN` and `LAST_N` are mutually exclusive on the same call

```ts [[2, 2, "LOWEST"], [1, 2, "price"], [2, 2, "LAST_N"]]
 // Lowest price among the last 50 changes
 LOWEST{[price], LAST_N(50)}
```

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "LAST_N"]]
 // How many times this row's price changed in the last 20 events
 CHANGE_COUNT{[price], LAST_N(20)}
```

### `ALL_ROWS()`

`ALL_ROWS()` is used when you desire one shared history across all rows (instead of one per row).

The value is the same on every row.

`ALL_ROWS()` cannot be used with `ROWS_ADDED` / `ROWS_REMOVED` as they are always grid-scoped

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1m"], [2, 2, "ALL_ROWS"]]
 // Grid-wide: how many times price changed (any row) in the last minute
 CHANGE_COUNT{[price], WITHIN(1m), ALL_ROWS()}
```

```ts [[2, 2, "NET_CHANGE"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "15m"], [2, 2, "ALL_ROWS"]]
 // Grid-wide net move in price over the last 15 minutes
 NET_CHANGE{[price], WITHIN(15m), ALL_ROWS()}
```

### `ANY_COL()`

`ANY_COL()` watches **every column** on the row (or the whole Grid with `ALL_ROWS()`), instead of a named column.

Pass column references to limit the set: `ANY_COL([bid], [ask])`.

- `ANY_COL()` **replaces** `[col]` — do not use both in the same call
- It is accepted by `CHANGE_COUNT`, `NO_CHANGES`, `SINCE_CHANGE` and `CHANGED_AT` only
- Calculated Column recomputations never count

```ts [[2, 2, "NO_CHANGES"], [2, 2, "ANY_COL"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // This row is quiet across every column
 NO_CHANGES{ANY_COL(), WITHIN(1m)}
```

```ts [[2, 2, "NO_CHANGES"], [2, 2, "ANY_COL"], [2, 2, "WITHIN"], [4, 2, "5h"], [2, 2, "ALL_ROWS"]]
 // The whole Grid is quiet
 NO_CHANGES{ANY_COL(), WITHIN(5h), ALL_ROWS()}
```

```ts [[2, 2, "CHANGE_COUNT"], [2, 2, "ANY_COL"], [1, 2, "bid"], [1, 2, "ask"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Ticks on bid or ask only
 CHANGE_COUNT{ANY_COL([bid], [ask]), WITHIN(1m)}
```

### `TRIGGER`

The `TRIGGER` clause limits which change **origins** count.

Omit it to count every change

There are 4 possible origins:

| Origin         | Changes Counted                                                             |
| -------------- | --------------------------------------------------------------------------- |
| `'edit'`       | Edits made in the grid (including Smart Edit, Bulk Update and Plus / Minus) |
| `'tick'`       | Row data updated from outside the grid (e.g. streaming updates)             |
| `'undo'`       | An edit being undone                                                        |
| `'calculated'` | A Calculated Column value being recalculated                                |

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "TRIGGER"]]
 // Only user edits
 CHANGE_COUNT{[price], TRIGGER('edit')}
```

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "1m"], [2, 2, "TRIGGER"]]
 // Only streaming ticks in the last minute
 CHANGE_COUNT{[price], WITHIN(1m), TRIGGER('tick')}
```

To count more than one origin, pass them all to the same `TRIGGER`:

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "price"], [2, 2, "TRIGGER"]]
 // User edits and undos (but not streaming ticks)
 CHANGE_COUNT{[price], TRIGGER('edit', 'undo')}
```

### `WHERE`

The `WHERE` clause narrows which changes (or which added / removed rows) enter the history.

`WHERE` is always put **inside** braces

```ts [[2, 2, "CHANGE_COUNT"], [1, 2, "orderCost"], [1, 2, "customer"], [2, 2, "WITHIN"], [4, 2, "1h"], [2, 2, "ALL_ROWS"]]
 // Grid-wide changes to orderCost, only for one customer
 CHANGE_COUNT{[orderCost] WHERE [customer] = 'TRADH', WITHIN(1h), ALL_ROWS()} >= 10
```

```ts [[2, 2, "ROWS_REMOVED"], [1, 2, "instrument"], [2, 2, "WITHIN"], [4, 2, "10s"]]
 // At least one Oracle row removed in the last 10 seconds
 ROWS_REMOVED{WHERE [instrument] = 'ORACLE', WITHIN(10s)} >= 1
```

The clause is evaluated on the row at change time.

## Durations

Observable timeframes and `ROW_AGE{}` use a **duration** type.

Compare durations to duration literals (`30s`, `1h`) — not bare numbers:

```ts [[2, 2, "ROW_AGE"]]
 // Correct
 ROW_AGE{} > 30s

// Invalid — use 30s (or another duration literal)
// ROW_AGE{} > 30
```

## Change History

AdapTable records change history only for what an active Observable Expression is watching:

- Recording starts when the Expression becomes active - when the grid loads (for Expressions already in State) or when the Expression is created (e.g. a new Alert)
- So "since the grid loaded" really means since the Expression started watching
- Expressions that watch the same Column (with the same `WHERE` and `ALL_ROWS()` settings) share one history, so a new Expression can immediately see changes already recorded
- When no Expression watches a Column any more (e.g. its Alert is deleted), that history is discarded

- Change history is held **in memory** only - it is not saved with AdapTable State
- When the page reloads, every Observable Expression starts again with no history

How much history is kept is capped by the `maxTimeframeSize` and `maxHistoryPerCell` Expression Options (see below)

## Configuring Observables

All are configured using [Expression Options](https://www.adaptabletools.com/docs/technical-reference-expression/index.md).

### `maxTimeframeSize`

Maximum time (in milliseconds) allowed for a WITHIN timeframe

Caps `WITHIN` in Observable Expressions. 

Hard ceiling is 86400000 (24 hours).

```ts {3}
expressionOptions: {
  maxTimeframeSize: 43200000, // 12 hours
}
```

### `maxHistoryPerCell`

Maximum change events retained per cell for LAST_N / history readers

Limits how many change events are kept per cell (affects `LAST_N` and related readers).

```ts {3}
expressionOptions: {
  maxHistoryPerCell: 500,
}
```

### `liveRefreshIntervalMs`

Repaint cadence for timeframe / clock-based Expressions

How often AdapTable repaints cells whose Expressions depend on the clock or a sliding `WITHIN` timeframe. 

`0` disables live refresh — those cells only update on data changes (or when they scroll into view).

```ts {3}
expressionOptions: {
  liveRefreshIntervalMs: 1000,
}
```
