How to write LinkingChart indicators and strategies in JavaScript: the script format, every function of the calculation library, strategies and their orders (tested on tick data in the Strategy tab), the rules and limits, the formulas that differ from other platforms, how to convert an indicator written for another platform (with a Pine Script name table), and complete examples.
It is the same documentation as the JS code base panel of JS EDITOR in LinkingChart. For AI agents, all of it is in one text file: llms-full.txt. Updated 2026-11-24.
10. The calculation library: lib↑ Contents
Every calculation of the built-in indicators, public, with the same values to the last decimal.
Before using a function in a conversion, read its formula: some calculations exist elsewhere under the same name with another formula (see Same name, different formula).
Missing a calculation?
If lib does not have it, write it in plain JavaScript in calc — or once in a library, for all your scripts. Never call a lib function that is not listed here: the editor underlines it and the calculation stops.
Prices and utilities
Choose the price a calculation uses, build and adjust series.
lib.price(bars, kind?) → number[]
The price of each bar. Pair it with an input of type "price" to let the user choose (the "Apply to" list).
bars Bars- The bars received by calc().
kind? PriceKind- "close" (default), "open", "high", "low", "median" (high+low)/2, "typical" (high+low+close)/3 or "weighted" (high+low+2×close)/4.
Returns: One price per bar.
const src = lib.price(bars, input.price);
lib.series(n, value?) → any[]
A new series, filled with NaN (no value) or with the given value. The usual start of a calculation bar by bar.
n number- Number of values (usually bars.length).
value? any- Initial value of every element. Default: NaN.
Returns: An array of n values.
const out = lib.series(bars.length);
for (let i = 1; i < bars.length; i++) out[i] = bars.close[i] - bars.close[i - 1];
lib.round(v, digits?) → number
Rounds a number to a number of decimals.
v number- The value.
digits? number- Number of decimals. Default: 0.
Returns: The rounded value.
lib.round(1.23456, 2) // 1.23
lib.sub(a, b) → number[]
Subtracts one series from another, bar by bar.
a Series- The first series.
b Series- The series subtracted from it.
Returns: a[i] - b[i] for each bar.
const spread = lib.sub(lib.ema(bars.close, 12), lib.ema(bars.close, 26));
lib.firstFinite(src) → number
Index of the first bar that has a value (not NaN).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
Returns: The index of the first real value; src.length if there is none.
const start = lib.firstFinite(avg);
lib.hideBefore(arr, index) → number[]
Hides the first values of a series (sets them to NaN): useful when the first bars of a calculation are not meaningful yet.
arr number[]- The series to change (it is modified in place).
index number- Bars before this index lose their value.
Returns: The same array.
return { value: lib.hideBefore(out, input.period) };
lib.shiftedAt(arr, i, shift) → number
The value at bar i of a series drawn shifted by some bars. To draw a shifted line, prefer the plot field shift.
arr Series- The series.
i number- The bar index.
shift number- Shift in bars (positive = to the right, into the future).
Returns: The value, or NaN outside the series.
const jawsNow = lib.shiftedAt(jaws, i, 8);
lib.PRICE_OPTIONS: ReadonlyArray<[PriceKind, string]>
The price choices and their labels, as shown in the "Apply to" list: ["close", "Close"], ["open", "Open"]…
inputs: [{ id: "src", type: "select", options: lib.PRICE_OPTIONS }]
lib.MA_OPTIONS: ReadonlyArray<[MaMethod, string]>
The moving-average methods and their labels: ["sma", "Simple"], ["ema", "Exponential"], ["smma", "Smoothed"], ["lwma", "Linear Weighted"].
inputs: [{ id: "kind", type: "select", options: lib.MA_OPTIONS }]
Moving averages
Averages of a series over a number of bars. A series that starts with NaN values is averaged from its first real value.
lib.sma(src, period) → number[]
Simple moving average: the plain average of the last period values.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const avg = lib.sma(bars.close, 20);
lib.ema(src, period) → number[]
Exponential moving average (smoothing 2 / (period + 1)), started on the first value — the same as MetaTrader 5.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const fast = lib.ema(bars.close, 12);
lib.smma(src, period) → number[]
Smoothed moving average (Wilder's average): the first value is a simple average, then (previous × (period − 1) + value) / period. Also named lib.rma.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const avg = lib.smma(bars.close, 14);
lib.rma(src, period) → number[]
Same as lib.smma (Wilder's average, used by RSI and ATR).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const wilderAtr = lib.rma(lib.tr(bars), 14);
lib.lwma(src, period) → number[]
Linear weighted moving average: the newest value weighs period, the oldest weighs 1. Also named lib.wma.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const avg = lib.lwma(bars.close, 10);
lib.wma(src, period) → number[]
Same as lib.lwma (linear weighted moving average).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const avg = lib.wma(bars.close, 10);
lib.ma(src, period, method?) → number[]
A moving average of the chosen method. Pair it with an input of type "method" to let the user choose.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
method? MaMethod- "sma" (default), "ema", "smma" or "lwma".
Returns: One value per bar; NaN until the period is filled.
const avg = lib.ma(bars.close, input.period, input.method);
lib.vwma(src, volume, period) → number[]
Volume-weighted moving average: each value weighs its bar's volume.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
volume Series- The volumes (bars.volume).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const avg = lib.vwma(bars.close, bars.volume, 20);
lib.hma(src, period) → number[]
Hull moving average: WMA(2 × WMA(period / 2) − WMA(period), √period). Fast and smooth.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const hull = lib.hma(bars.close, 21);
lib.dema(src, period) → number[]
Double exponential moving average: 2 × EMA − EMA(EMA).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const d = lib.dema(bars.close, 14);
lib.tema(src, period) → number[]
Triple exponential moving average: 3 × EMA − 3 × EMA(EMA) + EMA(EMA(EMA)).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const t = lib.tema(bars.close, 14);
lib.ama(src, period, fast, slow) → number[]
Adaptive moving average (Kaufman): fast when the price moves in one direction, slow when it goes sideways.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Bars used to measure efficiency (MetaTrader 5 default: 9).
fast number- Fastest EMA period (default in MetaTrader 5: 2).
slow number- Slowest EMA period (default in MetaTrader 5: 30).
Returns: One value per bar; NaN until the period is filled.
const kama = lib.ama(bars.close, 9, 2, 30);
lib.frama(src, period) → number[]
Fractal adaptive moving average (Ehlers). MetaTrader 5 default period: 14.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const f = lib.frama(bars.close, 14);
lib.vidya(src, cmoPeriod, emaPeriod) → number[]
Variable index dynamic average (Chande): an EMA that speeds up when momentum is strong.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
cmoPeriod number- Period of the Chande momentum that drives the speed (MetaTrader 5 default: 9).
emaPeriod number- Period of the underlying EMA (MetaTrader 5 default: 12).
Returns: One value per bar; NaN until the period is filled.
const v = lib.vidya(bars.close, 9, 12);
Rolling windows
Values measured over the last bars: highest, lowest, sums, changes, statistics.
lib.highest(src, period) → number[]
Highest value of the last period bars (the current bar included).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const top = lib.highest(bars.high, 20);
lib.lowest(src, period) → number[]
Lowest value of the last period bars (the current bar included).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const bottom = lib.lowest(bars.low, 20);
lib.highestBars(src, period) → number[]
How many bars ago the highest value of the window was. Always 0 or more.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: Bars since the highest value: 0 = the current bar.
const age = lib.highestBars(bars.high, 20);
lib.lowestBars(src, period) → number[]
How many bars ago the lowest value of the window was. Always 0 or more.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: Bars since the lowest value: 0 = the current bar.
const age = lib.lowestBars(bars.low, 20);
lib.sum(src, period) → number[]
Sum of the last period values.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const vol20 = lib.sum(bars.volume, 20);
lib.cum(src) → number[]
Running total since the first bar (values that are NaN are skipped).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
Returns: The running total at each bar.
const total = lib.cum(bars.volume);
lib.change(src, length?) → number[]
Difference between the value and the value length bars before.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length? number- Number of bars back. Default: 1.
Returns: src[i] − src[i − length]; NaN on the first bars.
const diff = lib.change(bars.close);
lib.roc(src, length) → number[]
Rate of change in percent: 100 × (value − value length bars before) / value length bars before.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length number- Number of bars back.
Returns: Percent change; NaN on the first bars.
const pct = lib.roc(bars.close, 10);
lib.stdev(src, period, method?) → number[]
Standard deviation of the last period values around their moving average (population formula, as in MetaTrader 5).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
method? MaMethod- Average the deviation is measured from. Default: "sma".
Returns: One value per bar; NaN until the period is filled.
const sd = lib.stdev(bars.close, 20);
lib.stdevAround(src, mean, period) → number[]
Standard deviation of the last period values around a given average.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
mean Series- The average to measure from, one value per bar.
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const sd = lib.stdevAround(bars.close, lib.ema(bars.close, 20), 20);
lib.variance(src, period) → number[]
Variance of the last period values (the square of lib.stdev).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const v = lib.variance(bars.close, 20);
lib.linreg(src, length, offset?) → number[]
Linear regression (least squares) over the last length bars: the value of the fitted line at the current bar.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length number- Number of bars of the regression.
offset? number- Bars back from the end of the line. Default: 0 (the current bar).
Returns: One value per bar; NaN until the period is filled.
const line = lib.linreg(bars.close, 50);
lib.correlation(a, b, length) → number[]
Correlation coefficient (Pearson) of two series over the last length bars.
a Series- The first series.
b Series- The second series.
length number- Number of bars.
Returns: From −1 to 1; NaN until length bars are available.
const c = lib.correlation(bars.close, bars.volume, 20);
lib.percentRank(src, length) → number[]
Percentage of the previous length values that are lower than or equal to the current value.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length number- Number of previous bars compared.
Returns: From 0 to 100.
const rank = lib.percentRank(bars.close, 100);
Conditions and events
Crossings, direction and past events. Conditions are arrays of true / false, one per bar.
lib.crossover(a, b) → boolean[]
True on each bar where a goes from below (or equal) to above b.
a Series- The series that crosses.
b Series | number- The series or the fixed level it crosses.
Returns: True on the bars where a crosses above b.
const up = lib.crossover(fast, slow);
const above70 = lib.crossover(rsi, 70);
lib.crossunder(a, b) → boolean[]
True on each bar where a goes from above (or equal) to below b.
a Series- The series that crosses.
b Series | number- The series or the fixed level it crosses.
Returns: True on the bars where a crosses below b.
const down = lib.crossunder(fast, slow);
lib.cross(a, b) → boolean[]
True on each bar where a crosses b in either direction.
a Series- The first series.
b Series | number- The series or the fixed level.
Returns: True on the bars where a crosses b.
const any = lib.cross(bars.close, avg);
lib.rising(src, length) → boolean[]
True when the value is higher than each of the length previous values.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length number- Number of previous bars.
Returns: True where the value is higher than each of the previous length values.
const up3 = lib.rising(bars.close, 3);
lib.falling(src, length) → boolean[]
True when the value is lower than each of the length previous values.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
length number- Number of previous bars.
Returns: True where the value is lower than each of the previous length values.
const down3 = lib.falling(bars.close, 3);
lib.valueWhen(cond, src, occurrence?) → number[]
The value src had the last time (or an earlier time) the condition was true.
cond ArrayLike<boolean>- A condition, one true / false per bar.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
occurrence? number- 0 = the last time (default), 1 = the time before, and so on.
Returns: NaN before enough occurrences.
const lastCrossPrice = lib.valueWhen(lib.cross(fast, slow), bars.close);
lib.pivotHigh(src, left, right) → number[]
A value higher than the left bars before it and the right bars after it. Placed ON the pivot bar — but it can only be known right bars later: a script that decides with it must wait for that delay, or it sees the future on past bars.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
left number- Bars on the left that must be lower.
right number- Bars on the right that must be lower.
Returns: The pivot value on the pivot bar; NaN elsewhere.
const highs = lib.pivotHigh(bars.high, 5, 5);
lib.pivotLow(src, left, right) → number[]
A value lower than the left bars before it and the right bars after it. Placed ON the pivot bar, known only right bars later (see lib.pivotHigh).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
left number- Bars on the left that must be higher.
right number- Bars on the right that must be higher.
Returns: The pivot value on the pivot bar; NaN elsewhere.
const lows = lib.pivotLow(bars.low, 5, 5);
Volatility and bands
How much the price moves, and the channels built on it.
lib.tr(bars) → number[]
True range: max(high, previous close) − min(low, previous close).
bars Bars- The bars received by calc().
Returns: NaN on the first bar.
const range = lib.tr(bars);
lib.atr(bars, period) → number[]
Average true range, as in MetaTrader 5: a SIMPLE average of lib.tr. For Wilder's version: lib.rma(lib.tr(bars), period).
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const atr = lib.atr(bars, 14);
lib.bands(src, period, deviation) → { middle: number[]; upper: number[]; lower: number[] }
Bollinger bands: a simple average, and that average ± deviation × standard deviation.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
deviation number- Number of standard deviations (usually 2).
Returns: The three lines.
const bb = lib.bands(bars.close, 20, 2);
return { upper: bb.upper, middle: bb.middle, lower: bb.lower };
lib.envelopes(src, period, method, deviation) → { upper: number[]; lower: number[] }
Envelopes: a moving average moved up and down by a percentage.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
method MaMethod- Average method.
deviation number- Distance in percent of the average.
Returns: The two lines.
const env = lib.envelopes(bars.close, 14, "sma", 0.1);
lib.keltner(bars, src, period, mult) → { middle: number[]; upper: number[]; lower: number[] }
Keltner channel: an EMA of the price ± mult × an EMA of the true range.
bars Bars- The bars received by calc().
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
mult number- Width, in average true ranges.
Returns: The three lines.
const kc = lib.keltner(bars, bars.close, 20, 2);
lib.supertrend(bars, factor, atrPeriod) → { supertrend: number[]; direction: number[] }
Supertrend: a line that follows the price at a distance and flips side when the trend changes.
bars Bars- The bars received by calc().
factor number- Distance from the price, in average true ranges (usually 3).
atrPeriod number- Period of the average true range (Wilder's, usually 10).
Returns: supertrend: the line. direction: 1 = up trend (line under the price), −1 = down trend.
const st = lib.supertrend(bars, 3, 10);
const isUp = st.direction[bars.length - 1] === 1;
Trend
Strength and direction of the trend.
lib.adx(bars, period) → { adx: number[]; plusDi: number[]; minusDi: number[] }
Average directional index, as in MetaTrader 5 (lines smoothed by EMA). For Wilder's smoothing: lib.adxWilder.
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: ADX, +DI and −DI, from 0 to 100.
const d = lib.adx(bars, 14);
const strong = d.adx.map((v) => v > 25);
lib.adxWilder(bars, period) → { adx: number[]; plusDi: number[]; minusDi: number[] }
Average directional index with Wilder's smoothing (MetaTrader 5 "ADX Wilder").
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: ADX, +DI and −DI, from 0 to 100.
const d = lib.adxWilder(bars, 14);
lib.ichimoku(bars, tenkanPeriod, kijunPeriod, senkouPeriod) → { tenkan: number[]; kijun: number[]; spanA: number[]; spanB: number[]; chikou: number[] }
Ichimoku lines. They are returned without their shifts: use the plot field shift to draw spans ahead and chikou behind.
bars Bars- The bars received by calc().
tenkanPeriod number- Tenkan-sen period (usually 9).
kijunPeriod number- Kijun-sen period (usually 26).
senkouPeriod number- Senkou span B period (usually 52).
Returns: The five lines, NOT shifted.
const ich = lib.ichimoku(bars, 9, 26, 52);
lib.sar(bars, step, maximum) → number[]
Parabolic SAR, as in MetaTrader 5.
bars Bars- The bars received by calc().
step number- Acceleration step (usually 0.02).
maximum number- Maximum acceleration (usually 0.2).
Returns: One stop value per bar.
const sar = lib.sar(bars, 0.02, 0.2);
Oscillators
Momentum and overbought / oversold measures, usually drawn in their own pane.
lib.rsi(src, period) → number[]
Relative strength index, with Wilder's averages of gains and losses (MetaTrader 5 formula).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: From 0 to 100; NaN on the first period bars.
const rsi = lib.rsi(bars.close, 14);
lib.macd(src, fast, slow, signal) → { macd: number[]; signal: number[]; hist: number[] }
MACD as in MetaTrader 5: the signal line is a SIMPLE average of the MACD line.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
fast number- Fast EMA period (usually 12).
slow number- Slow EMA period (usually 26).
signal number- Signal period (usually 9).
Returns: macd = fast EMA − slow EMA; signal; hist = macd − signal.
const m = lib.macd(bars.close, 12, 26, 9);
return { macd: m.macd, signal: m.signal, hist: m.hist };
lib.stoch(bars, kPeriod, dPeriod, slowing, method?, priceField?) → { main: number[]; signal: number[] }
Stochastic oscillator, as in MetaTrader 5.
bars Bars- The bars received by calc().
kPeriod number- %K period (usually 5).
dPeriod number- Signal (%D) period (usually 3).
slowing number- Slowing (usually 3).
method? MaMethod- Average of the signal line. Default: "sma".
priceField? "lowhigh" | "closeclose"- "lowhigh" (default) uses highs and lows; "closeclose" uses closes.
Returns: main (%K) and signal (%D), from 0 to 100.
const st = lib.stoch(bars, 5, 3, 3);
lib.cci(src, period) → number[]
Commodity channel index. Usually on the typical price.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const cci = lib.cci(lib.price(bars, "typical"), 14);
lib.momentum(src, period) → number[]
Momentum as in MetaTrader 5: 100 × value / value period bars before.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: Around 100.
const mom = lib.momentum(bars.close, 14);
lib.wpr(bars, period) → number[]
Williams' percent range.
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: From −100 to 0.
const w = lib.wpr(bars, 14);
lib.demarker(bars, period) → number[]
DeMarker oscillator.
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: From 0 to 1.
const dm = lib.demarker(bars, 14);
lib.rvi(bars, period) → { rvi: number[]; signal: number[] }
Relative vigor index.
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: The RVI line and its signal line.
const r = lib.rvi(bars, 10);
lib.trix(src, period) → number[]
Rate of change of a triple EMA.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
period number- Number of bars.
Returns: A ratio (multiply by 100 for percent).
const t = lib.trix(bars.close, 14);
lib.force(src, volume, period, method) → number[]
Force index as in MetaTrader 5: volume × change of the moving average of the price.
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
volume Series- The volumes (bars.volume).
period number- Number of bars.
method MaMethod- Average method.
Returns: One value per bar; NaN until the period is filled.
const f = lib.force(bars.close, bars.volume, 13, "sma");
lib.bears(bars, period) → number[]
Bears power: low − EMA(close, period).
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const b = lib.bears(bars, 13);
lib.bulls(bars, period) → number[]
Bulls power: high − EMA(close, period).
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: One value per bar; NaN until the period is filled.
const b = lib.bulls(bars, 13);
Volume
Calculations that use bars.volume (the tick volume of the bars).
lib.obv(bars) → number[]
On-balance volume: adds the volume on an up bar, subtracts it on a down bar.
bars Bars- The bars received by calc().
Returns: The running total.
const obv = lib.obv(bars);
lib.ad(bars) → number[]
Accumulation / distribution line.
bars Bars- The bars received by calc().
Returns: The running total.
const ad = lib.ad(bars);
lib.chaikin(bars, fast, slow, method) → number[]
Chaikin oscillator: difference of two averages of the accumulation / distribution line.
bars Bars- The bars received by calc().
fast number- Fast average period (usually 3).
slow number- Slow average period (usually 10).
method MaMethod- Average method.
Returns: One value per bar; NaN until the period is filled.
const ch = lib.chaikin(bars, 3, 10, "ema");
lib.mfi(bars, period) → number[]
Money flow index (on the typical price).
bars Bars- The bars received by calc().
period number- Number of bars.
Returns: From 0 to 100.
const m = lib.mfi(bars, 14);
lib.vwap(bars, src?) → number[]
Volume-weighted average price, starting again every day (the day of the broker's server, like the bars).
bars Bars- The bars received by calc().
src? Series- Price to average. Default: the typical price.
Returns: One value per bar.
const vwap = lib.vwap(bars);
lib.volumeColors(bars) → number[]
Color index of the volume bars: returned as "<plot id>_color", it colors a two-color histogram.
bars Bars- The bars received by calc().
Returns: 0 when the volume rises, 1 otherwise.
return { vol: bars.volume, vol_color: lib.volumeColors(bars) };
Bill Williams
The Bill Williams tools, as in MetaTrader 5.
lib.ao(bars) → number[]
Awesome oscillator: SMA(5) − SMA(34) of the median price.
bars Bars- The bars received by calc().
Returns: One value per bar; NaN until the period is filled.
const ao = lib.ao(bars);
lib.ac(bars) → number[]
Accelerator oscillator: AO − SMA(AO, 5).
bars Bars- The bars received by calc().
Returns: One value per bar; NaN until the period is filled.
const ac = lib.ac(bars);
lib.alligator(src, jawsPeriod, teethPeriod, lipsPeriod, method) → { jaws: number[]; teeth: number[]; lips: number[] }
Alligator lines, without their shifts: use the plot field shift to draw them ahead (usually 8, 5 and 3 bars).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
jawsPeriod number- Jaws period (usually 13).
teethPeriod number- Teeth period (usually 8).
lipsPeriod number- Lips period (usually 5).
method MaMethod- Average method (usually "smma").
Returns: The three lines, NOT shifted.
const a = lib.alligator(lib.price(bars, "median"), 13, 8, 5, "smma");
lib.gator(src, o) → { upper: number[]; lower: number[]; upperColor: number[]; lowerColor: number[] }
Gator oscillator: the gaps between the Alligator lines as drawn (shifts applied).
src Series- The values to use, one per bar (for example bars.close, or the result of another lib function).
o { jawsPeriod: number; jawsShift: number; teethPeriod: number; teethShift: number; lipsPeriod: number; lipsShift: number; method: MaMethod }- The Alligator settings, shifts included.
Returns: upper = |jaws − teeth|, lower = −|teeth − lips|; colors: 0 when the gap grows, 1 when it narrows.
const g = lib.gator(lib.price(bars, "median"), { jawsPeriod: 13, jawsShift: 8, teethPeriod: 8, teethShift: 5, lipsPeriod: 5, lipsShift: 3, method: "smma" });
lib.fractals(bars) → { up: number[]; down: number[] }
Fractals: a high above the two bars after it and at least as high as the two before it (the reverse for lows). Known two bars later.
bars Bars- The bars received by calc().
Returns: The high (up) or low (down) on fractal bars; NaN elsewhere.
const f = lib.fractals(bars);
lib.bwmfi(bars) → { mfi: number[]; color: number[] }
Market facilitation index: (high − low) / volume, with its four colors.
bars Bars- The bars received by calc().
Returns: color: 0 green, 1 fade, 2 fake, 3 squat.
const m = lib.bwmfi(bars);
lib.upDownColors(values) → number[]
Color index for a two-color histogram (rising / falling). Return it as "<plot id>_color".
values Series- The series to color.
Returns: 0 when the value rises, 1 when it falls; unchanged when it stays.
return { hist: m.hist, hist_color: lib.upDownColors(m.hist) };
22. Complete examples↑ Contents
Complete scripts, ready to paste into a new file and save.
A trend band: settings, colors, a fill, markers and alerts
indicator({
name: "Trend band",
placement: "overlay",
precision: "price",
inputs: [
{ id: "src", label: "Apply to", type: "price", default: "close" },
{ id: "period", label: "Period", type: "int", default: 50, min: 2 },
{ id: "mult", label: "Width (ATR)", type: "float", default: 1.5, min: 0, step: 0.1 }
],
plots: [
{ id: "mid", label: "Average", colors: ["#26A69A", "#EF5350"], colorLabels: ["Rising", "Falling"], width: 2 },
{ id: "upper", label: "Upper", color: "#787B86", style: "dash" },
{ id: "lower", label: "Lower", color: "#787B86", style: "dash" },
{ id: "band", type: "fill", between: ["upper", "lower"], color: "#2962FF", opacity: 0.08 },
{ id: "up", label: "Break up", type: "shape", shape: "triangleUp", location: "belowBar", color: "#26A69A" },
{ id: "down", label: "Break down", type: "shape", shape: "triangleDown", location: "aboveBar", color: "#EF5350" }
],
alerts: [
{ id: "up", title: "Close above the band", message: "{{symbol}} {{tf}}: close above the band" },
{ id: "down", title: "Close below the band" }
],
calc(bars, input, lib) {
const n = bars.length;
const mid = lib.ema(lib.price(bars, input.src), input.period);
const atr = lib.rma(lib.tr(bars), input.period); // Wilder's average true range
const upper = lib.series(n), lower = lib.series(n), color = lib.series(n);
for (let i = 0; i < n; i++) {
upper[i] = mid[i] + input.mult * atr[i];
lower[i] = mid[i] - input.mult * atr[i];
color[i] = i > 0 && mid[i] < mid[i - 1] ? 1 : 0; // 1 = the second color
}
const up = lib.crossover(bars.close, upper), down = lib.crossunder(bars.close, lower);
return { mid, mid_color: color, upper, lower, up, down, alert_up: up, alert_down: down };
}
});
An average cross with its alerts
indicator({
name: "EMA Cross",
placement: "overlay",
plots: [{ id: "fast", color: "#2962FF" }, { id: "slow", color: "#FF6D00" }],
alerts: [
{ id: "bull", title: "Bullish cross", message: "{{symbol}} {{tf}}: fast EMA crossed above slow" },
{ id: "bear", title: "Bearish cross" }
],
calc(bars, input, lib) {
const fast = lib.ema(bars.close, 9), slow = lib.ema(bars.close, 21);
return { fast, slow, alert_bull: lib.crossover(fast, slow), alert_bear: lib.crossunder(fast, slow) };
}
});
The previous day's high and low (requests)
indicator({
name: "Previous day high and low",
placement: "overlay",
precision: "price",
inputs: [{ id: "htf", label: "Timeframe", type: "timeframe", default: "D1" }],
requests: { prev: { tf: "htf" } },
plots: [
{ id: "high", label: "High", type: "step", color: "#26A69A" },
{ id: "low", label: "Low", type: "step", color: "#EF5350" }
],
calc(bars, input, lib, data) {
return { high: data.prev.high, low: data.prev.low };
}
});
An average of the daily closes on any timeframe
indicator({
name: "Daily average",
placement: "overlay",
precision: "price",
inputs: [{ id: "period", label: "Days", type: "int", default: 20, min: 1 }],
requests: { daily: { tf: "D1" } },
plots: [{ id: "avg", label: "Average of the daily closes", type: "step", color: "#FF6D00" }],
calc(bars, input, lib, data) {
const d = data.daily, n = bars.length, avg = lib.series(n), closes = [];
let last = NaN, value = NaN;
for (let i = 0; i < n; i++) {
if (isFinite(d.time[i]) && d.time[i] !== last) { // a new daily bar has closed
last = d.time[i];
closes.push(d.close[i]);
if (closes.length >= input.period) {
let s = 0;
for (let k = closes.length - input.period; k < closes.length; k++) s += closes[k];
value = s / input.period;
}
}
avg[i] = value;
}
return { avg };
}
});
Any calculation on a higher timeframe: the RSI of the daily bars
indicator({
name: "Higher timeframe RSI",
placement: "separate",
range: [0, 100],
levels: [30, 70],
inputs: [
{ id: "htf", label: "Timeframe", type: "timeframe", default: "D1" },
{ id: "period", label: "Period", type: "int", default: 14, min: 2 }
],
requests: { higher: { tf: "htf" } },
plots: [{ id: "rsi", label: "RSI", type: "step", color: "#7E57C2" }],
calc(bars, input, lib, data) {
// The higher-timeframe bars, ONE per bar (not one per chart bar), with the fields of bars.
// h.toChart(values) puts each result back on the chart bars it covers.
function htfBars(d) {
const h = { time: [], open: [], high: [], low: [], close: [], volume: [], length: 0 }, at = [];
for (let i = 0; i < d.time.length; i++) {
if (isFinite(d.time[i]) && d.time[i] !== h.time[h.length - 1]) { // a new bar has closed
for (const k of ["time", "open", "high", "low", "close", "volume"]) h[k].push(d[k][i]);
h.length++;
}
at.push(h.length - 1);
}
h.toChart = (values) => at.map((k) => (k >= 0 ? values[k] : NaN));
return h;
}
const h = htfBars(data.higher);
// Any lib function works the same way: lib.ema(h.close, 50), lib.rma(lib.tr(h), 14)…
return { rsi: h.toChart(lib.rsi(h.close, input.period)) };
}
});
Inside bars counted bar by bar (setup and onBar)
indicator({
name: "Inside bar count",
placement: "separate",
plots: [{ id: "count", label: "Count", type: "histogram", color: "#26A69A" }],
setup(input, lib) { return { count: 0 }; },
onBar(b, state, ctx) {
const inside = b.high <= b.at(1).high && b.low >= b.at(1).low;
state.count = inside ? state.count + 1 : 0;
ctx.plot("count", state.count);
}
});
Labels and lines on pivots (draw)
indicator({
name: "Pivot labels",
placement: "overlay",
inputs: [{ id: "len", label: "Length", type: "int", default: 5, min: 1 }],
calc(bars, input, lib) {
const n = input.len, highs = [];
for (let i = n; i < bars.length - n; i++) {
let top = true;
for (let k = 1; k <= n && top; k++) top = bars.high[i] > bars.high[i - k] && bars.high[i] >= bars.high[i + k];
if (!top) continue;
const prev = highs[highs.length - 1];
draw.label({ bar: i, price: bars.high[i], text: prev && bars.high[i] > bars.high[prev] ? "HH" : "LH", color: "#EF5350" });
if (prev !== undefined) draw.line({ from: [prev, bars.high[prev]], to: [i, bars.high[i]], color: "#EF5350", style: "dash" });
highs.push(i);
}
return {};
}
});
Trading sessions: a rectangle per session, its colors in the Style tab (draw plots)
// Trading sessions: a rectangle over each session, from its high to its low.
// Hours are on the broker's server clock: set them to your broker.
indicator({
name: "Trading sessions",
description: "A rectangle over the London, New York and Tokyo sessions, from their high to their low (server hours).",
placement: "overlay",
// Inputs: what changes the calculation — the hours. A start right before its end.
inputs: [
{ id: "londonStart", label: "London: start (server hour)", type: "int", default: 10, min: 0, max: 23 },
{ id: "londonEnd", label: "London: end (server hour)", type: "int", default: 19, min: 0, max: 24 },
{ id: "newYorkStart", label: "New York: start (server hour)", type: "int", default: 15, min: 0, max: 23 },
{ id: "newYorkEnd", label: "New York: end (server hour)", type: "int", default: 24, min: 0, max: 24 },
{ id: "tokyoStart", label: "Tokyo: start (server hour)", type: "int", default: 2, min: 0, max: 23 },
{ id: "tokyoEnd", label: "Tokyo: end (server hour)", type: "int", default: 11, min: 0, max: 24 }
],
// Plots: one draw plot per session — the Style entry of its rectangles: color, opacity of the fill, border width,
// line style and check box. Never inputs.
plots: [
{ id: "london", label: "London", type: "draw", color: "#26A69A", opacity: 0.15 },
{ id: "newYork", label: "New York", type: "draw", color: "#EF5350", opacity: 0.15 },
{ id: "tokyo", label: "Tokyo", type: "draw", color: "#FFB300", opacity: 0.15 }
],
calc(bars, input, lib) {
const n = bars.length, hour = lib.series(n);
for (let i = 0; i < n; i++) hour[i] = new Date(bars.time[i]).getUTCHours(); // the server hour of the bar
// One rectangle per session: from its first bar to its last, over its high and its low so far.
// The newest session is still open: its rectangle grows with each bar. A session past midnight (start > end) wraps.
function sessionBoxes(start, end, plot) {
let from = -1, hi = -Infinity, lo = Infinity;
for (let i = 0; i < n; i++) {
const inside = start < end ? (hour[i] >= start && hour[i] < end) : (hour[i] >= start || hour[i] < end);
if (inside) {
if (from < 0) { from = i; hi = bars.high[i]; lo = bars.low[i]; }
hi = Math.max(hi, bars.high[i]); lo = Math.min(lo, bars.low[i]);
}
if (from >= 0 && (!inside || i === n - 1)) {
draw.box({ from: [from, hi], to: [inside ? i : i - 1, lo], plot });
from = -1;
}
}
}
sessionBoxes(input.londonStart, input.londonEnd, "london");
sessionBoxes(input.newYorkStart, input.newYorkEnd, "newYork");
sessionBoxes(input.tokyoStart, input.tokyoEnd, "tokyo");
return {}; // draw plots take no values
}
});
A library and a script that uses it
// File "My tools.js"
library({
name: "My tools",
exports: {
// Middle of each bar.
mid(bars) { return bars.high.map((h, i) => (h + bars.low[i]) / 2); },
// Distance to an average, in %.
gapPct(src, period) {
const avg = lib.sma(src, period);
return src.map((v, i) => (v - avg[i]) / avg[i] * 100);
}
}
});
// File "Mid gap.js"
indicator({
name: "Mid gap",
uses: ["My tools"],
plots: [{ id: "gap", type: "histogram" }],
calc(bars, input, lib, data, use) {
const t = use["My tools"];
return { gap: t.gapPct(t.mid(bars), 20) };
}
});
A strategy: an EMA cross with a stop and a target (strategy, ctx.entry)
strategy({
name: "EMA cross strategy",
placement: "overlay",
inputs: [
{ id: "fast", label: "Fast EMA", type: "int", default: 9, min: 2, max: 100 },
{ id: "slow", label: "Slow EMA", type: "int", default: 21, min: 3, max: 400 },
{ id: "slPips", label: "Stop loss (pips)", type: "float", default: 20, min: 1 },
{ id: "tpX", label: "Take profit (x the stop)", type: "float", default: 2, min: 0.1, step: 0.1 }
],
plots: [{ id: "fast", label: "Fast EMA", color: "#2962FF" }, { id: "slow", label: "Slow EMA", color: "#FF6D00" }],
properties: { lots: 0.1, pyramiding: 0 },
setup(input, lib, bars) {
// Once, on the whole series: the state that onBar reads.
const fast = lib.ema(bars.close, input.fast), slow = lib.ema(bars.close, input.slow);
return { fast, slow, up: lib.crossover(fast, slow), down: lib.crossunder(fast, slow) };
},
onBar(b, state, ctx) {
// Once per closed bar. An order fills at the first tick after the close.
const i = b.index;
ctx.plot("fast", state.fast[i]);
ctx.plot("slow", state.slow[i]);
// A position the other way is closed first; the stop is in pips, the target at tpX times the stop.
if (state.up[i]) ctx.entry("Long", "long", { slPips: ctx.input.slPips, tpX: ctx.input.tpX });
if (state.down[i]) ctx.entry("Short", "short", { slPips: ctx.input.slPips, tpX: ctx.input.tpX });
}
});