# Technical-analysis helpers

`@chart-on/ta` is a small library of technical-analysis functions for indicator authors. Custom indicators combine a few helpers instead of hand-written loops, and the built-in indicators use the same helpers, so both run at the same speed and give the same values.

```bash
pnpm add @chart-on/ta
```

It has no dependencies, does not import `@chart-on/core`, and is tree-shakeable: importing `sma` alone adds about 1 kB.

## Conventions

Every helper follows the same rules:

- **Columns in, columns out.** Inputs are columns of numbers, one per bar (`Float64Array` is the fast path; plain arrays work too). Outputs are `Float64Array`s of the same length.
- **Warmup is NaN.** Bars before the first value are `NaN`. `<name>Lookback(...)` returns how many bars that is, e.g. `smaLookback(20)` is 19. Helpers with several outputs report their slowest output.
- **NaN breaks the series.** A window function reads `NaN` while a `NaN` input is inside its window. Recursive helpers (exponential averages, running totals, RSI, OBV, VWAP) read `NaN` on that bar and warm up again after it. Chained helpers therefore work on each other's output, warmup included: `ema(macdLine, 9)` starts where the MACD line does.
- **Inputs are never mutated.** Pass an `out` array (or an object of arrays for multi-output helpers) to reuse buffers instead of allocating. It must not be one of the inputs.
- **Single-bar forms.** `<name>At(...)` computes bar `i` from earlier bars, for an indicator's live `update`. It gives the same values as the array form, up to floating-point rounding: rolling window sums are rebuilt every `length` bars so the difference stays tiny. Recursive ones read bar `i - 1` of their `out` (and `state`) arrays and write bar `i`.
- **Lengths are validated.** A length that is not an integer of at least 1 throws a `RangeError`, in the array and single-bar forms alike, as do inputs of different lengths.

```ts
import { ema, emaAt, rsi, rsiAt } from '@chart-on/ta';

const out = ema(close, 20);   // full series
close[close.length - 1] = 105; // the last bar ticks
emaAt(close, close.length - 1, 20, out); // update it in place
```

Helpers whose running state is more than their output take an optional `state` argument (`rsi`, `macd`, `vwap`). Fill it in the array form and pass it to the single-bar form:

```ts
const n = close.length;
const state = { avgGain: new Float64Array(n), avgLoss: new Float64Array(n) };
const values = rsi(close, 14, undefined, state);
// later, for the last bar:
rsiAt(close, n - 1, 14, values, state);
```

## Helpers

### Averages

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `sma(values, length)` | `smaAt(values, i, length)` | `length - 1` | Mean of the last `length` values. |
| `ema(values, length)` | `emaAt(values, i, length, out)` | `length - 1` | Smoothing `2 / (length + 1)`, seeded by the SMA of the first `length` values. |
| `rma(values, length)` | `rmaAt(values, i, length, out)` | `length - 1` | Wilder's average, smoothing `1 / length`, seeded like `ema`. |
| `wma(values, length)` | `wmaAt(values, i, length)` | `length - 1` | Linear weights: newest `length`, oldest 1. |
| `vwma(values, volume, length)` | `vwmaAt(values, volume, i, length)` | `length - 1` | `sum(value × volume) / sum(volume)`; NaN when the window has no volume. |
| `hma(values, length)` | `hmaAt(values, i, length)` | `length + floor(sqrt(length)) - 2` | Hull: `wma` over `floor(sqrt(length))` of `2 * wma(length / 2) - wma(length)`. |
| `dema(values, length, out?, state?)` | `demaAt(values, i, length, out, state)` | `2 * (length - 1)` | `2 * ema - ema(ema)`. `state` is `{ ema1, ema2 }`. |
| `tema(values, length, out?, state?)` | `temaAt(values, i, length, out, state)` | `3 * (length - 1)` | `3 * ema - 3 * ema(ema) + ema(ema(ema))`. `state` is `{ ema1, ema2, ema3 }`. |
| `alma(values, length, offset, sigma)` | `almaAt(values, i, length, offset, sigma)` | `length - 1` | Gaussian weights centred `offset` along the window (0 oldest, 1 newest), width `length / sigma`. |
| `lsma(values, length)` | `lsmaAt(values, i, length)` | `length - 1` | End point of the least-squares line through the window. |
| `zlema(values, length)` | `zlemaAt(values, i, length, out)` | `floor((length - 1) / 2) + length - 1` | Zero-lag EMA: the `ema` of `2 * x - x[lag]` with `lag = floor((length - 1) / 2)`. |
| `mcginley(values, length)` | `mcginleyAt(values, i, length, out)` | `length - 1` | `md + (price - md) / (length * (price / md)^4)`, seeded by the first window's mean. |

### Volatility

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `tr(high, low, close)` | `trAt(high, low, close, i)` | 0 | True range; the first bar uses `high - low`. |
| `atr(high, low, close, length)` | `atrAt(high, low, close, i, length, out)` | `length - 1` | `rma` of `tr`. |
| `stdev(values, length)` | `stdevAt(values, i, length)` | `length - 1` | Population standard deviation. |
| `correlation(x, y, length)` | `correlationAt(x, y, i, length)` | `length - 1` | Pearson correlation of `x` and `y` over the window, -1 to 1; NaN where either is flat. |
| `bbands(values, length, mult)` | `bbandsAt(values, i, length, mult, out)` | `length - 1` | Returns `{ middle, upper, lower }`. |
| `volatilityStop(high, low, close, length, mult, out?, state?)` | `volatilityStopAt(high, low, close, i, length, mult, out, state)` | 0 | Returns `{ stop, trend }`: a stop `mult` `atr`s from the trend's extreme close that only moves with the trend, trend 1 up and -1 down. A close past the stop, once it has moved with the bar, flips the trend. It starts up on the first bar with the stop at the close, and the true range stands in for `mult` ATRs until the ATR has a value. `state` is `{ atr, extreme }`. |
| `relativeVolatility(values, length, smoothing, out?, state?)` | `relativeVolatilityAt(values, i, length, smoothing, state)` | `max(length, 2) + smoothing - 2` | Relative volatility index, 0 to 100: `rsi`'s formula on the `stdev` of `length` values, credited to rising bars or to the others (an unchanged value counts as down), each side smoothed by an `ema`. `state` is `{ up, down }`. |
| `massIndex(high, low, length, sum, out?, state?)` | `massIndexAt(high, low, i, length, sum, state)` | `2 * (length - 1) + sum - 1` | `ema` of the range over an `ema` of that, summed over `sum` bars. A bar without range counts a ratio of 1. `state` is `{ single, double, ratio }`. |
| `chandeKrollStop(high, low, close, length, mult, stopLength, out?, state?)` | `chandeKrollStopAt(high, low, close, i, length, mult, stopLength, out, state)` | `length + stopLength - 2` | Returns `{ long, short }`: the highest over `stopLength` of `highest(high, length) - mult * atr`, and the lowest of `lowest(low, length) + mult * atr`. `state` is `{ atr, firstLong, firstShort }`. |
| `chandelierExit(high, low, close, length, mult, useClose?, out?, state?)` | `chandelierExitAt(high, low, close, i, length, mult, useClose, out, state)` | `length - 1` | Returns `{ long, short, direction }`: `highest(high, length) - mult * atr` and `lowest(low, length) + mult * atr` (closes with `useClose`), each only tightening while the previous close stayed past it, and 1 or -1 for the side a close past the other side's previous stop turns to (starting at 1). `state` is `{ atr }`. |
| `historicalVolatility(values, length, periodsPerYear, out?, returns?)` | `historicalVolatilityAt(values, i, length, periodsPerYear, returns)` | `length` | `stdev` of the last `length` log returns, times `100 * sqrt(periodsPerYear)`: annualized volatility in percent. `returns` keeps the log returns for the single-bar form. |
| `keltner(high, low, close, length, mult, atrLength, out?, state?)` | `keltnerAt(high, low, close, i, length, mult, atrLength, out, state)` | `max(length, atrLength) - 1` | `ema` of the close ± `mult` × `atr`. Returns `{ middle, upper, lower }`; `state` is `{ atr }`. |
| `donchian(high, low, length)` | `donchianAt(high, low, i, length, out)` | `length - 1` | Returns `{ upper, lower, middle }`: highest high, lowest low, midpoint. |

### Momentum

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `rsi(values, length, out?, state?)` | `rsiAt(values, i, length, out, state)` | `length` | Wilder's RSI. 100 with no losses, 50 on a flat run. |
| `macd(values, fast, slow, signal, out?, state?)` | `macdAt(values, i, fast, slow, signal, out, state)` | `max(fast, slow) + signal - 2` | Returns `{ macd, signal, histogram }`; `state` is `{ fast, slow }`. |
| `stoch(high, low, close, kLength, kSmooth, dLength)` | `stochAt(high, low, close, i, kLength, kSmooth, dLength, out)` | `kLength + kSmooth + dLength - 3` | Returns `{ k, d }`. A zero range reads 50. |
| `stochRsi(values, rsiLength, stochLength, kSmooth, dLength, out?, state?)` | `stochRsiAt(values, i, rsiLength, stochLength, kSmooth, dLength, out, state)` | `rsiLength + stochLength + kSmooth + dLength - 3` | `stoch` applied to an `rsi`. Returns `{ k, d }`; `state` is `{ rsi, avgGain, avgLoss }`. A zero range reads 50. |
| `kdj(high, low, close, length, kSmooth, dSmooth)` | `kdjAt(high, low, close, i, length, kSmooth, dSmooth, out)` | `length - 1` | Returns `{ k, d, j }`: RSV (close in the `length`-bar range, 0 to 100, 50 for a zero range) smoothed by `1 / kSmooth` into K, K by `1 / dSmooth` into D, J = 3K - 2D. K and D start from 50. |
| `psy(values, length)` | `psyAt(values, i, length)` | `length` | Psychological line: percent of the last `length` bars that rose. |
| `roc(values, length)` | `rocAt(values, i, length)` | `length` | Percent change; NaN on a zero base. |
| `dpo(values, length)` | `dpoAt(values, i, length)` | `length - 1 + floor(length / 2) + 1` | Detrended price oscillator: the value minus the `sma` from `floor(length / 2) + 1` bars back. |
| `kst(values, rocLengths, smaLengths, signal)` | `kstAt(values, i, rocLengths, smaLengths, signal, out)` | slowest `roc + sma - 1`, plus `signal - 1` | Know sure thing: four `roc`s, each smoothed by an `sma`, weighted 1 to 4 by position (list the shortest first). Lengths are 4-tuples. Returns `{ kst, signal }`. |
| `coppock(values, length, longRoc, shortRoc)` | `coppockAt(values, i, length, longRoc, shortRoc)` | `max(longRoc, shortRoc) + length - 1` | `wma` of the sum of two `roc`s. |
| `connorsRsi(values, rsiLength, streakLength, rankLength, out?, state?)` | `connorsRsiAt(values, i, rsiLength, streakLength, rankLength, out, state)` | `max(rsiLength, streakLength, rankLength + 1)` | Average of an `rsi`, an `rsi` of the up/down streak (+n after n higher closes, -n after n lower, 0 unchanged) and the percent of the last `rankLength` one-bar changes strictly below the latest; NaN while that window holds a change from a zero close. `state` is `{ rsi, price, streak, streakRsi, streakState }`. |
| `ppo(values, fast, slow, signal, out?, state?)` | `ppoAt(values, i, fast, slow, signal, out, state)` | `max(fast, slow) + signal - 2` | `macd` in percent of the slow `ema`. Returns `{ ppo, signal, histogram }`; `state` is `{ fast, slow }`. NaN on a zero slow average. |
| `tsi(values, long, short, signal, out?, state?)` | `tsiAt(values, i, long, short, signal, out, state)` | `long + short + signal - 2` | True strength index, -100 to 100: the change smoothed by an `ema` over `long` then `short`, over the absolute change smoothed alike. Returns `{ tsi, signal }`; `state` is `{ change1, change2, abs1, abs2 }`. 0 when nothing moved. |
| `cmo(values, length)` | `cmoAt(values, i, length)` | `length` | Chande momentum oscillator, -100 to 100: gains minus losses over their total. 0 when nothing moved. |
| `ultimateOscillator(high, low, close, fast, middle, slow)` | `ultimateOscillatorAt(high, low, close, i, fast, middle, slow)` | `max(fast, middle, slow)` | 0 to 100: buying pressure over true range in three windows, weighted 4, 2 and 1. NaN while a window has no range. |
| `balanceOfPower(open, high, low, close, length)` | `balanceOfPowerBar(open, high, low, close, i)` (one bar, unsmoothed) | `length - 1` | `(close - open) / (high - low)`, -1 to 1, smoothed by an `sma` of `length`; 0 for a bar without range. |
| `cci(values, length)` | `cciAt(values, i, length)` | `length - 1` | Commodity channel index: distance from the `sma` in units of 0.015 mean absolute deviations. Usually on hlc3. A window with no deviation reads 0. |
| `williamsR(high, low, close, length)` | `williamsRAt(high, low, close, i, length)` | `length - 1` | Williams %R, -100 at the lowest low to 0 at the highest high. A zero range reads -50. |
| `trix(values, length, out?, state?)` | `trixAt(values, i, length, state)` | `3 * (length - 1) + 1` | 10000 times the one-bar change of a triple `ema` of the logarithm of the values. `state` is `{ ema1, ema2, ema3 }` (averages of the logarithms). NaN for a value at or below 0. |
| `fisher(high, low, length, out?, state?)` | `fisherAt(high, low, i, length, out, state)` | `length` | Fisher transform of the median price placed in its `length`-bar range, smoothed `0.33 * 2 * position + 0.67 * previous` and snapped to ±0.999 beyond ±0.99. Returns `{ fisher, trigger }`; the trigger is the previous bar's value. A zero range reads as the middle. `state` is `{ value }`. |
| `rvi(open, high, low, close, length)` | `rviAt(open, high, low, close, i, length, out)` | `length + 5` | Relative vigor index: `sma` of the 1, 2, 2, 1 weighted `close - open` over the same of `high - low`, with that weighting of it as the signal. Returns `{ rvi, signal }`. NaN on a zero range. |
| `smiErgodic(values, long, short, signal, out?, state?)` | `smiErgodicAt(values, i, long, short, signal, out, state)` | `long + short + signal - 2` | The one-bar change double-smoothed by `ema`s (`long`, then `short`) over the same of its size, as a ratio from -1 to 1, with an `ema` signal. Returns `{ smi, signal }`; 0 when nothing moved. `state` is `{ long, short, absLong, absShort }`. |
| `schaffTrendCycle(values, fast, slow, cycle, out?, state?)` | `schaffTrendCycleAt(values, i, fast, slow, cycle, out, state)` | `max(fast, slow) + 2 * cycle - 3` | Stochastic of the MACD line over `cycle` bars, moved halfway from its previous value each bar, then the same again, 0 to 100. Each smoothing takes the raw value on its first bar. A zero range keeps the previous value, or reads 50 with none. `state` is `{ fast, slow, macd, stoch }`. |

### Trend

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `dmi(high, low, close, length, adxLength, out?, state?)` | `dmiAt(high, low, close, i, length, adxLength, out, state)` | `length + adxLength - 1` | Returns `{ plus, minus, adx }` (the DIs start at `length`); `state` is `{ plusDm, minusDm, tr }`. Wilder's smoothing throughout. |
| `aroon(high, low, length)` | `aroonAt(high, low, i, length, out)` | `length` | Returns `{ up, down }`, 0 to 100: how many bars ago the highest high and lowest low of the last `length + 1` bars were. The newest bar wins a tie. |
| `supertrend(high, low, close, length, mult, out?, state?)` | `supertrendAt(high, low, close, i, length, mult, out, state)` | `length - 1` | Returns `{ line, direction }`, direction 1 up and -1 down; `state` is `{ atr, upper, lower }`. Each run starts down. |
| `vortex(high, low, close, length)` | `vortexAt(high, low, close, i, length, out)` | `length` | Returns `{ plus, minus }`: `|high - previous low|` and `|low - previous high|` summed over `length` bars, over the summed true range. |
| `choppiness(high, low, close, length)` | `choppinessAt(high, low, close, i, length)` | `length - 1` | 0 to 100: `100 * log10(sum of true range / (highest high - lowest low)) / log10(length)`. `length` at least 2. |
| `ichimoku(high, low, conversionLength, baseLength, spanBLength)` | `ichimokuAt(high, low, i, conversionLength, baseLength, spanBLength, out)` | `max(...lengths) - 1` | Returns `{ conversion, base, spanA, spanB }`, each at the bar it is computed on; shift the spans forward yourself. |
| `psar(high, low, close, start, step, max, out?, state?)` | `psarAt(high, low, close, i, start, step, max, out, state)` | 1 | Parabolic SAR: the stop in force during each bar. `state` is `{ trend, extreme, factor }`, trend 1 up and -1 down. A run's second bar starts up when its close is above the first's, from the first bar's low (high when down), and can reverse at once. Each bar the stop moves, a reversal is tested (the new stop is the old extreme or the bar's own extreme, whichever is further), and then the stop is kept outside the run's bars before it (one on the second bar, else two). |

### Volume

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `vwap(price, volume, newSession?, out?, state?)` | `vwapAt(price, volume, i, out, state, newSession?)` | 0 | Restarts where `newSession(i)` is true; `state` is `{ priceVolume, volume }`. |
| `obv(close, volume)` | `obvAt(close, volume, i, out)` | 0 | Starts at 0. |
| `brar(open, high, low, close, length)` | `brarAt(open, high, low, close, i, length, out)` | `length` (AR from `length - 1`) | Returns `{ ar, br }` in percent: rises above the open against falls below it (AR), and the same against the previous close (BR), summed over `length` bars. NaN on a zero downside sum. |
| `cr(high, low, length)` | `crAt(high, low, i, length)` | `length` | Highs above the previous bar's midpoint against lows below it, summed, in percent. NaN on a zero downside sum. |
| `vr(close, volume, length)` | `vrAt(close, volume, i, length)` | `length` | Volume ratio: volume on rising bars plus half the unchanged, against falling plus the other half, in percent. NaN on zero downside volume. |
| `pvt(close, volume)` | `pvtAt(close, volume, i, out)` | 0 | Price volume trend: running total of volume times the close's fractional change. Starts at 0; a previous close of 0 adds nothing. |
| `forceIndex(close, volume, length)` | `forceIndexAt(close, volume, i, length, out)` | `length` | Elder's force index: `ema` of close change times volume. |
| `easeOfMovement(high, low, volume, length, divisor)` | `easeOfMovementAt(high, low, volume, i, length, divisor)` | `length` | `sma` of midpoint move times range, over volume in units of `divisor`. NaN with a bar without volume in the window. |
| `klinger(high, low, close, volume, fast, slow, signal, out?, state?)` | `klingerAt(high, low, close, volume, i, fast, slow, signal, out, state)` | `max(fast, slow) + signal - 1` | Klinger volume oscillator, simpler signed-volume form: volume signed by the typical price direction (unchanged counts as up), fast minus slow `ema` of it. Returns `{ kvo, signal }`; `state` is `{ fast, slow }`. |
| `accDist(high, low, close, volume)` | `accDistAt(high, low, close, volume, i, out)` | 0 | Accumulation/distribution line: running total of `moneyFlowVolumeAt`. A NaN input restarts the total. |
| `cmf(high, low, close, volume, length)` | `cmfAt(high, low, close, volume, i, length)` | `length - 1` | Chaikin money flow, -1 to 1: window flow over window volume. NaN without volume. |
| `mfi(high, low, close, volume, length)` | `mfiAt(high, low, close, volume, i, length)` | `length` | Money flow index, 0 to 100: `rsi`'s formula on typical price times volume. |
| | `moneyFlowVolumeAt(high, low, close, volume, i)` | 0 | One bar's volume times its close location, -1 at the low to 1 at the high; 0 for a bar without range. |

### Levels and swings

`pivotPoints(high, low, close)` returns `{ pivot, r1, s1, r2, s2, r3, s3 }`, the standard (floor) pivot points of each bar, usually a day, week or month: pivot `(high + low + close) / 3`, `r1 = 2 * pivot - low`, `s1 = 2 * pivot - high`, `r2`/`s2` the pivot plus or minus the range, `r3 = high + 2 * (pivot - low)`, `s3 = low - 2 * (high - pivot)`. Put them on the chart's bars with `alignSteps(..., { closedOnly: true })`, so each period shows the levels of the one before.

`zigzag(high, low, deviation)` returns the swing points of the series: each swing's price at its bar (the high for a swing high, the low for a swing low) and NaN elsewhere. A swing is confirmed once price moves `deviation` percent the other way. The latest extreme ends the last, unconfirmed leg and moves with new bars, so it has no single-bar form: recompute over every bar.

### Fractals

`fractals(high, low, wing)` returns `{ up, down }`: the high of each bar whose high is strictly above the `wing` bars on each side, and the low of each bar whose low is strictly below theirs; NaN elsewhere. A tie is no fractal. The newest `wing` bars have none yet, since their right side has not formed, so there is no single-bar form: recompute over every bar.

### Cycles

`moonPhase(time)` takes one time in unix seconds and returns `{ age, illumination }`: days since the last new moon (0 up to `SYNODIC_MONTH`, about 29.53, with the full moon at half of that) and the lit fraction of the disc from 0 to 1. It uses the mean lunar cycle, so true new and full moons fall within about 15 hours of where it puts them.

`newSession` decides where VWAP restarts. For daily sessions in UTC, with `time` in Unix seconds:

```ts
const day = (t: number) => Math.floor(t / 86400);
const daily = (i: number) => i > 0 && day(time[i]!) !== day(time[i - 1]!);
const values = vwap(hlc3, volume, daily);
```

### Helpers

| Function | Single bar | Lookback | Notes |
| --- | --- | --- | --- |
| `highest(values, length)` | `highestAt(values, i, length)` | `length - 1` | |
| `lowest(values, length)` | `lowestAt(values, i, length)` | `length - 1` | |
| `change(values, length = 1)` | `changeAt(values, i, length)` | `length` | `value - value[length bars back]`. |
| `sum(values, length)` | `sumAt(values, i, length)` | `length - 1` | |
| `cum(values)` | `cumAt(values, i, out)` | 0 | Running total. |
| `crossOver(a, b)` | `crossOverAt(a, b, i)` | 1 | 1 where `a` crosses above `b`, else 0. `b` may be a number. |
| `crossUnder(a, b)` | `crossUnderAt(a, b, i)` | 1 | 1 where `a` crosses below `b`, else 0. |
