# LinkingChart JS code base > 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. Web page: https://linkingchart.com/docs/scripts/ The same documentation as the "JS code base" panel of JS EDITOR in LinkingChart. Updated 2026-11-24. ## Contents 1. Start here 2. How a script is organized 3. Series, bar indexes and NaN 4. The declaration: indicator({ ... }) 5. Inputs: the settings 6. Plots: what the indicator draws 7. calc: all the bars at once 8. setup and onBar: bar by bar 9. bars, time and sessions 10. The calculation library: lib 11. Other timeframes and symbols: requests 12. Drawing objects: labels, lines, boxes, tables 13. Alerts 14. Libraries: library and uses 15. Strategies: strategy({ ... }), orders and the Strategy tab 16. Logs: log() 17. Rules and limits 18. Same name, different formula 19. Converting a script from another platform 20. Porting from Pine Script, name by name 21. Checklist before you deliver 22. Complete examples ## 1. Start here Everything you need to write a LinkingChart script - or to convert a script written for another charting platform - in one place, in order: the basics first, then the full reference, then conversions. Search finds words anywhere in this code base. Type several words to narrow the results: only the parts that contain all of them stay. ### What a script is A script is an ordinary JavaScript file (.js) in your scripts folder. One file declares one script: an indicator with `indicator({ ... })`, a strategy with `strategy({ ... })` (orders, tested in the Strategy tab), or a library of shared functions with `library({ ... })`. The file is yours: open it in any editor, copy it, share it. The menu of the script title (v) has Open scripts folder. ### A script in 30 seconds A script is a .js file in the scripts folder. It calls indicator({...}) once. The declaration says what the indicator is (name, placement), what the user can change (inputs) and what it draws (plots). calc(bars, input, lib) receives all the bars and returns one array of values per plot. ```js indicator({ id: "my.k3x9q2", name: "Close above average", placement: "separate", inputs: [{ id: "period", label: "Period", type: "int", default: 20, min: 1 }], plots: [{ id: "gap", label: "Gap", type: "histogram", color: "#26A69A" }], calc(bars, input, lib) { const avg = lib.sma(bars.close, input.period); return { gap: lib.sub(bars.close, avg) }; } }); ``` ### Write, check, add to the chart - Open v > New starts an indicator on the price chart or in its own pane. - Save (Ctrl+S) always writes the file - even with errors - then checks it: the syntax, the declaration, then a test calculation on the active chart. Problems appear in the Errors tab with their line: a click goes there. - Add to chart (Ctrl+Enter) adds the script to the active chart. Once it is there, the button becomes Update on chart: every chart that shows it recalculates and keeps its settings. - A built-in indicator opens read-only. Make a copy gives you your own file to change. ### When Save shows a warning The test calculation runs on the bars of the ACTIVE chart, so its warnings describe that chart. The Logs tab names it and counts its bars, for example "EURUSD ; M5 (5000 bars)". The usual warnings: - Plot "x" has no value on any bar: that plot draws nothing on this chart. For a line, its warm-up is longer than the bars of the chart (see How many bars a script receives). For a marker (shape, char), its condition never happened on these bars: check it on another symbol or a higher timeframe before you change the code. - calc() returned nothing for plot "x": return every plot id (a fill excepted). - Plot "x" has n values for m bars: return exactly `bars.length` values. - calc() returned "x", but no plot has that id: a key with no plot is ignored. Check its spelling against plots. ## 2. How a script is organized Every script follows the same plan, so that a reader - or an AI - knows where each thing goes, and so that the settings window looks the same for every indicator: the Inputs tab for what changes the calculation, the Style tab for how it is drawn. The plan is the one scripters know from other charting platforms, in the words of this code base. ### The order of a file 1. A comment header: what the script does, in one or two lines. For a conversion, what could not be converted and why. 2. Constants, in UPPER_CASE: fixed numbers, and the colors of the draw objects (`const BOX_FILL = "#2962FF22";`). 3. Helper functions: plain JavaScript functions the calculation uses. 4. The declaration, once: `indicator({ ... })`, `strategy({ ... })` or `library({ ... })`, with its parts in this order: name (then shortName, description, category...), placement and precision, uses, requests, inputs, plots, levels and range, alerts, properties (a strategy), then calc - or setup and onBar. 5. Inside calc: the inputs read into short names first, then the calculations, then the markers and the draw objects, and at the end the return with every plot id. ```js // Trend band: an average with a band of ATRs around it, markers on the breaks. const BREAK_LABEL = "#787B86"; // constants first function atrWilder(bars, period, lib) { // then the helper functions return lib.rma(lib.tr(bars), period); } indicator({ // then the declaration, once name: "Trend band", placement: "overlay", precision: "price", inputs: [ /* what changes the calculation */ ], plots: [ /* what is drawn: its colors, widths and check boxes are in the Style tab */ ], alerts: [ /* the conditions the user can pick */ ], calc(bars, input, lib) { const period = input.period; // inputs read first // ... calculations ... // ... markers, draw objects ... return { /* every plot id */ }; // the return at the end } }); ``` ### Inputs tab or Style tab: where a setting goes The settings window has fixed tabs; the declaration fills them. A setting belongs to the tab where the user will look for it, the same tab as in every other indicator: | The user wants to change... | Where it goes | | --- | --- | | A period, a multiplier, a source, an hour, a threshold, a mode - anything that changes the CALCULATION | an input (Inputs tab) | | The color, the opacity, the thickness or the line style of what is drawn | the plot itself: color, opacity, width, style. The user changes them in the Style tab. Never an input - never a select of color names. A draw object (a box, a line, a label) gets this through a plot of type draw that it names with plot: "". | | Showing or hiding an element | the check box of its plot, in the Style tab. Never a bool input "Show ...". | | A horizontal line at a fixed value, the scale of the pane | levels and range (Levels and Scale tabs) | | The timeframes on which the indicator shows | nothing: the Visibility tab belongs to the program | ### One plot per element the user may color or hide Each thing the user may want in another color, or without, is its own plot with its own label: three session rectangles are three draw plots (London, New York, Tokyo), two bands are two line plots, a signal is a shape plot. A single plot with a "color" select, or a bool input per element, puts in the Inputs tab what every other indicator has in the Style tab. The complete script is in Complete examples: Trading sessions. ```js // Three sessions drawn as rectangles: three draw plots. Each has its color, its opacity, its border and its check box in the Style tab. 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 } ], // in calc: each rectangle names its plot draw.box({ from: [first, high], to: [last, low], plot: "london" }); // NOT this: a color in the Inputs tab, chosen by its name. // inputs: [{ id: "londonColor", label: "London: color", type: "select", options: ["Green", "Red"] }] ``` ### A plot or a draw object? When one value per bar says it, it is a plot: a value on the scale (line, step, histogram...), a mark on a bar (shape, char, arrow), the background of a bar (bgcolor), the color of a candle (barcolor), a band between two plots (fill). draw is for what a plot cannot do: a text at one point (label), a line between two chosen bars (line), a rectangle between two corners (box), a table in a corner. A draw object has its Style entry too: declare a plot of type draw for each group of objects the user may color or hide on its own (one per session, one for the support lines, one for the resistance lines), and name it on every object with plot: "". Its color, the opacity of the fill, the width, the line style and the check box are then in the Style tab, like any plot. An object without plot keeps the colors written in the code, and the user cannot change them: give plot to every object the user may want in another color or without. ### Names - ids: short, in camelCase (`fastPeriod`, `londonStart`): letters, digits and _. An id is stable: templates and alerts keep it. - Labels: the words of the user, first letter capitalized, the unit in parentheses: "Fast period", "Stop loss (pips)", "London: start (server hour)". The label of a plot names what is drawn ("London", "Upper band"), not how. - Related inputs follow one another, in the order the user reads them: the source first, then the periods, then the options; a start right before its end. - Defaults: the usual values of the indicator; min and max where a value outside them has no meaning (an hour: 0 to 23). - Constants in UPPER_CASE, functions and variables in camelCase. Short comments say what each part does, in plain English. ## 3. Series, bar indexes and NaN Every value of a script is a series: an array with one value per bar. ### Oldest first Index 0 is the OLDEST bar; `bars.length - 1` is the newest. In calc, the value n bars before bar i is `src[i - n]`. In onBar, the bar n bars back is `b.at(n)`. ### The newest bar is still forming The newest bar changes with every price until it closes. Every bar before it is closed and never changes: the last closed bar is `bars.length - 2`. ### NaN means no value NaN is "no value": nothing is drawn there, and any comparison with NaN is false. lib functions give NaN until they have enough bars (the first 19 bars of a 20-bar average). A series that starts with NaN - the result of another lib function, or `data.` - is calculated from its first value, so calculations chain: `lib.rsi(lib.ema(bars.close, 20), 14)`. A NaN in the MIDDLE of a series is another matter: the averages, stdev, the ATR, the MACD and most other lib functions then stay NaN to the end. It happens with a division by zero, for example by `high - low` on a bar where they are equal. Calculate on the valid values only (onValid below), or replace the gap first (`isFinite(v) ? v : previous`). Test it with `Number.isNaN(v)` or `!isFinite(v)` - never with `v === NaN`, which is always false. To use 0 instead of no value: `isFinite(v) ? v : 0`. ```js // Calculates f on the valid values only, then puts each result back on its bar; // a bar without a value keeps the previous result. function onValid(src, f) { const idx = [], vals = []; for (let i = 0; i < src.length; i++) if (isFinite(src[i])) { idx.push(i); vals.push(src[i]); } const res = f(vals), out = lib.series(src.length); let k = 0, last = NaN; for (let i = 0; i < src.length; i++) { if (k < idx.length && idx[k] === i) last = res[k++]; out[i] = last; } return out; } const ratio = bars.volume.map((v, i) => v / (bars.high[i] - bars.low[i])); // NaN or Infinity when high = low const avg = onValid(ratio, (v) => lib.sma(v, 14)); ``` ### Never read ahead A script must never use a bar after the one it calculates (`src[i + 1]`). On the history it would know the future, and its live result would differ from what the history shows. onBar cannot read ahead at all: `b.at(n)` only goes back. ### Arrays you build Start from `lib.series(bars.length)` and fill it in a loop. Return arrays of exactly `bars.length` values. ```js const diff = lib.series(bars.length); // all NaN const flags = lib.series(bars.length, false); // all false for (let i = 1; i < bars.length; i++) { diff[i] = bars.close[i] - bars.close[i - 1]; flags[i] = diff[i] > 0; } ``` ## 4. The declaration: indicator({ ... }) Every indicator file calls `indicator({ ... })` exactly once: its name, its settings (inputs), what it draws (plots) and its calculation (calc, or setup and onBar). ### id Leave id out in a new script: Save adds a stable one ("my...."). Templates and alerts use it, so renaming the file changes nothing. Never copy the id of another script. ### placement and precision `placement: "overlay"` draws on the price chart (an average, levels); `"separate"`, the default, gives the indicator its own pane (an oscillator). `precision: "price"` shows values with the decimals of the symbol; a number fixes them (0 to 10). ### Levels and a fixed scale `levels: [30, 70]` draws horizontal lines at fixed values; `range: [0, 100]` fixes the scale of a separate pane. ### All the fields - `id` (`string`): A stable identifier, for example "my.k3x9q2". Templates and alerts use it: renaming the file changes nothing. Make a copy gives the copy a new one. - `name` (`string`, required): The name shown in the indicator list and on the legend. - `shortName` (`string`): Shorter title for the legend. Default: name. - `abbr` (`string`): Abbreviation shown in the indicator list. - `description` (`string`): What the indicator does, in a sentence. - `category` (`string`): Folder in the indicator list (for example "Trend"). - `author` (`string`): Who wrote it. - `version` (`string`): Version of the script, for example "1.2". - `license` (`string`): License of the script, for example "MIT". - `placement` (`"overlay" | "separate"`): "overlay" = on the price chart; "separate" (default) = in its own pane below. - `precision` (`number | "price"`): Decimals of the values (0 to 10), or "price" for the decimals of the symbol. - `inputs` (`Input[]`): The settings the user can change (Inputs tab of the indicator settings). - `plots` (`Plot[]`): What is drawn from the values calc returns: lines, steps, areas, histograms, markers, shapes, characters, backgrounds, candle colors or fills. Objects placed on single bars (labels, lines, boxes, tables) are drawn with draw. - `levels` (`number[]`): Horizontal levels, for example [30, 70]. - `range` (`[number, number]`): Fixed scale of the pane, for example [0, 100]. - `alerts` (`AlertCondition[]`): Alert conditions the user can pick in Create alert, for example [{ id: "bullCross", title: "Bullish cross" }]. calc returns "alert_": true or false on each bar. - `calc` (`(bars: Bars, input: Inputs, lib: Lib, data: Data, use: Uses) => Output`): The calculation. Receives all the bars, returns one array per plot: { plotId: values }. Add "_color" (one color number per bar) to color a plot bar by bar. data holds the bars of requests, use the libraries of uses. Write either calc or onBar. - `setup` (`(input: Inputs, lib: Lib, bars: Bars, data: Data, use: Uses) => object`): With onBar: called once before the first bar; returns the state kept from bar to bar, for example { count: 0 }. It also receives all the bars, to prepare a series once (lib.ema...). - `onBar` (`(b: Bar, state: any, ctx: BarContext) => void`): Bar by bar: called once per bar, oldest first. b is the bar (b.close, b.at(1).close...), state what setup returned, ctx.plot(id, value) draws. Write either calc or onBar. - `requests` (`{ [name: string]: Request }`): Bars of other timeframes or symbols, for example { daily: { tf: "D1" } }. They reach calc as data.daily (one value per chart bar), never ahead of time: a D1 bar is seen from the first chart bar that opens after it closed. - `uses` (`string[]`): Libraries of the scripts folder, by name, for example ["My tools"]. Their functions are in use["My tools"]. ## 5. Inputs: the settings Each entry of inputs is a setting the user can change (Inputs tab of the indicator settings). Its value is `input.` in calc and `ctx.input.` in onBar. ### The fields of an input - `id` (`string`, required): The name used in calc: input.. Letters, digits and _. - `label` (`string`): The text shown in the settings. Default: the id. - `type` (`InputType`): The kind of setting (see Inputs). Default: guessed from default. - `default` (`any`): The starting value. - `min` (`number`): Smallest value (int and float). - `max` (`number`): Largest value (int and float). - `step` (`number`): Step of the arrows (int and float). - `options` (`Array`): The choices of a select: values, or [value, label] pairs. - `tooltip` (`string`): Help shown when the pointer rests on the setting. ### type: "int" A whole number (a period, a shift...). ```js { id: "period", label: "Period", type: "int", default: 14, min: 1 } ``` ### type: "float" A number with decimals. ```js { id: "mult", label: "Multiplier", type: "float", default: 2.5, step: 0.1 } ``` ### type: "bool" A check box: true or false. ```js { id: "showArrows", label: "Show arrows", type: "bool", default: true } ``` ### type: "select" A list of choices. ```js { id: "mode", label: "Mode", type: "select", options: [["fast", "Fast"], ["slow", "Slow"]], default: "fast" } ``` ### type: "price" The price to apply the calculation to (the "Apply to" list). Use it with lib.price(bars, input.). ```js { id: "price", label: "Apply to", type: "price", default: "close" } ``` ### type: "method" A moving-average method. Use it with lib.ma(src, period, input.). ```js { id: "method", label: "Method", type: "method", default: "ema" } ``` ### type: "timeframe" A timeframe: "same" (the chart's, default), M1 ... MN1, or a timeframe of your own in minutes, hours or days (M7, H5, D2). A request can use it: requests: { htf: { tf: "" } }. ```js { id: "htf", label: "Higher timeframe", type: "timeframe", default: "D1" } ``` ### type: "symbol" A symbol of the broker; empty = the chart's symbol. A request can use it: requests: { other: { symbol: "" } }. ```js { id: "other", label: "Compare with", type: "symbol", default: "GBPUSD" } ``` ### The settings window comes with every indicator You never build a settings window: LinkingChart gives the same one to every indicator, whatever it is, from its declaration - the tabs Inputs, Style, Levels and Scale (for an indicator in its own pane) and Visibility. On the chart, the name of the indicator is followed by its input values; the values of its plots are written after them only when the user checks Show the values on the chart, at the bottom of Visibility (unchecked by default, for every indicator and strategy). Every change the user makes in the window shows on the chart at once (a typed value when the field is left or on Enter); its buttons are always the same: Defaults, Apply on layout, Cancel and OK. Apply on layout applies the settings to the same indicator on every chart of the layout; a chart that does not have the indicator receives it. OK keeps the settings, Cancel undoes everything changed since the window opened. A script cannot add, remove or rename these buttons. ### No color, show / hide or text setting Colors are not inputs: every plot already has its color, opacity, thickness and check box in the Style tab of the settings - never a select of color names, never a bool input to show or hide an element: give that element its own plot (see How a script is organized). There is no free text setting: offer the choices in a select. A time of day is set with int inputs (hour, minute). ## 6. Plots: what the indicator draws ### How plots work Each entry of plots is drawn from the array calc returns under its id, one value per bar. The user can change its color, thickness and visibility in the settings. shape, char, bgcolor and barcolor take true or false per bar (a number other than 0 counts as true): they do not change the scale, show no value in the legend and cannot be compared in an alert - use alerts for that. ### The fields of a plot - `id` (`string`, required): The key calc returns the values under. Letters, digits and _. - `label` (`string`): The name on the legend and in the settings. Default: the id. - `type` (`PlotType`): How the values are drawn (see Plots). Default: "line". - `color` (`string`): A hex color, for example "#2962FF"; "#2962FF80" adds an opacity (80 = 50%). - `colors` (`string[]`): Several colors, picked bar by bar with "_color" (0 = first color). Every type except area and fill; for a fill: [color when the first one is above, color when it is below]. - `colorLabels` (`string[]`): Names of the colors in the settings, for example ["Rising", "Falling"]. - `width` (`number`): Thickness, from 1 to 5 (line width, column width or marker size). A line, step or area plot also takes 0.5, or 0: no line (an area keeps its fill). - `style` (`LineStyle`): Line style of a line, step or area. - `direction` (`"up" | "down"`): Direction of an arrow plot. - `base` (`number`): Value a histogram starts from (default 0), or an area is filled down to (default: the bottom of the pane). - `shift` (`number | string`): Draw the plot shifted by a number of bars (positive = to the right). Or the id of an int input ("-id" to shift back). - `between` (`[string | number, string | number]`): For a fill: two plot ids, two levels (numbers, for example [30, 70]) or a plot and a level. A number that is one of levels follows that level when the user moves it. - `opacity` (`number`): From 0 to 1: a fill (default 0.3), the surface of an area (0.2), a background (0.15) or the fill of the boxes of a draw plot (0.2). - `shape` (`ShapeStyle`): For a shape plot: "xcross" (default), "cross", "circle", "triangleUp", "triangleDown", "arrowUp", "arrowDown", "square", "diamond", "flag", "labelUp" or "labelDown" (a bubble holding the text). - `char` (`string`): For a char plot: the character or emoji drawn, for example "*". - `location` (`Location`): Where a shape or char is drawn: "aboveBar" (default) or "belowBar" the candle, "top" or "bottom" of the pane, or "absolute" at the value as a price. In a separate pane, above and below the bar mean the top and the bottom. - `size` (`Size`): Size of a shape or char: "tiny", "small" (default), "normal", "large" or "huge". The user can change it in the settings. - `text` (`string`): Text written with a shape or char ("\n" starts a new line). - `textColor` (`string`): Color of that text. Default: the color of the plot (white inside a label bubble). ### The types of plots - `"line"`: A line through the values. A NaN value leaves a gap. - `"step"`: A line in steps: the value holds until the next bar, then jumps. - `"area"`: A line with its surface filled down to base (default: the bottom of the pane). - `"histogram"`: Vertical bars from base (0) to each value. - `"dots"`: A dot on each value. - `"cross"`: A small + on each value. - `"circles"`: A hollow circle on each value. - `"arrow"`: An arrow on each bar that has a value (use NaN for no arrow). direction: "up" or "down". - `"shape"`: A shape on each bar where the value is true (or a number other than 0): arrows, triangles, circles, crosses, flags, label bubbles, with an optional text. With location "absolute", the value is the price where it is drawn. - `"char"`: A character or an emoji on each bar where the value is true, placed like a shape. - `"bgcolor"`: Colors the background of the bar's column where the value is true. On the price chart, the candles stay in front. - `"barcolor"`: Colors the candle itself where the value is true. Only in an overlay script (placement: "overlay"). - `"fill"`: A colored band between two plots, two levels or a plot and a level (between: ["a", "b"] or [30, 70]). calc returns nothing for it. - `"draw"`: No values: the Style entry of draw objects. The labels, lines and boxes that name it with plot: "" take from it, in the Style tab, their color (the fill of a box at its opacity), their width, their line style and their check box. calc returns nothing for it. ### A color per bar Give the plot `colors: [...]` and return `"_color"` from calc: one color number per bar, 0 = the first color. In onBar: `ctx.color(id, n)`. ```js plots: [{ id: "hist", type: "histogram", colors: ["#26A69A", "#EF5350"] }], calc(bars, input, lib) { const h = lib.macd(bars.close, 12, 26, 9).hist; return { hist: h, hist_color: lib.upDownColors(h) }; } ``` ### Shifted plots `shift: 26` draws a plot 26 bars to the right (ahead); a negative number draws it to the left. `shift: "kijun"` takes the value of the int input kijun, `"-kijun"` its opposite. ### Fills A fill colors the band between two plots, two levels or a plot and a level: `{ id: "band", type: "fill", between: ["upper", "lower"] }`. calc returns nothing for it. With `colors: [a, b]` it takes a where the first one is above, b where it is below. ### The Style entry of draw objects: a plot of type draw A plot of type draw has no values: it is the row of the Style tab for the labels, lines and boxes that name it with plot: "" - their color (the fill of a box at its opacity), their width, their line style and their check box. One per group of objects the user may color or hide on its own. ```js plots: [{ id: "zones", label: "Zones", type: "draw", color: "#26A69A", opacity: 0.15 }], calc(bars, input, lib) { draw.box({ from: [i1, high], to: [i2, low], plot: "zones" }); // colored in the Style tab return {}; } ``` ### Markers, backgrounds and candle colors shape, char, bgcolor and barcolor plots take true or false per bar; an arrow takes a number, or NaN for no arrow. They do not move the scale and cannot be compared in an alert: declare alerts for that. ## 7. calc: all the bars at once `calc(bars, input, lib, data, use)` receives every bar at once and returns one array per plot: `{ plotId: values }`. ### Its arguments - `bars`: The candles: `bars.open`, `bars.high`, `bars.low`, `bars.close`, `bars.volume`, `bars.time`, `bars.length`. - `input`: The values of the settings: `input.period`... - `lib`: The calculation library: averages, oscillators, crossings... - `data`: The bars of requests (other timeframes or symbols): `data.daily.close`... - `use`: The libraries listed in uses: `use["My tools"].fn(...)`. ### What it returns - One array per plot id, `bars.length` values each: numbers, or true / false for markers. - `"_color"`: one color number per bar, to color a plot bar by bar. - `"alert_"`: true or false per bar, for each condition declared in alerts. - Nothing for a fill. A plot left out has no value anywhere. - `{}` when the script only draws objects (draw.label...). ### A value carried from bar to bar A variable declared before the loop keeps its value from one bar to the next. ```js calc(bars, input, lib) { const n = bars.length, trend = lib.series(n); let state = 0; // kept from one bar to the next for (let i = 1; i < n; i++) { if (bars.close[i] > bars.high[i - 1]) state = 1; else if (bars.close[i] < bars.low[i - 1]) state = -1; trend[i] = state; } return { trend }; } ``` ### Speed calc runs again on every new price, over all the bars of the chart - about 5000, more on a chart left open. A calculation longer than 2 seconds is stopped. Keep to one pass over the bars: a loop over all the bars inside another one is far too slow; lib.highest, lib.sum and the averages work on a window for you. Call each lib function once, before the loop - it already returns the whole series - never inside it. ## 8. setup and onBar: bar by bar ### How it works Instead of calc, a script can work one bar at a time, oldest first, like reading the chart from left to right. setup returns the state (what is kept from one bar to the next); onBar(b, state, ctx) is called once per bar. b.close is the close of this bar and b.at(1).close that of the bar before (b.at(n): n bars back - never ahead, a script cannot see the future). alert() inside onBar only counts on the newest bar. Faster to write, a little slower to run than calc: prepare heavy series once in setup. ### b: the bar - `b.index` (`number`): Index of the bar in bars (0 = the oldest). - `b.time` (`number`): Opening time, in milliseconds (the broker's server time). - `b.open` (`number`): Open price. - `b.high` (`number`): High price. - `b.low` (`number`): Low price. - `b.close` (`number`): Close price (the current price on the newest bar). - `b.volume` (`number`): Tick volume. - `b.isLast` (`boolean`): true on the newest bar, the one being formed. - `b.at(n)` (`Bar`): The bar n bars back (0 = this one). Never ahead. ### ctx - `ctx.plot(id, value)`: Draws value for the plot id on this bar. A plot never given a value on a bar has none there (NaN). - `ctx.color(id, n)`: Picks color n (0 = the first of colors) for the plot id on this bar. - `ctx.condition(id, value)`: Sets the alert condition id (declared in alerts) to true or false on this bar. - `ctx.input`: The values of the settings, as in calc. - `ctx.lib`: The calculation library. - `ctx.data.`: The bar of a request seen on this bar: data.daily.high, data.daily.at(1).close... - `ctx.use`: The libraries of uses, as in calc. ### Example ```js 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); } }); ``` ### calc or onBar? Use calc when the work is made of whole series (averages, crossings). Use onBar when the logic reads bar after bar (a counter, a state, "since the last signal"). Both give the same result. onBar is a little slower: prepare heavy series once in setup, then read them with `b.index`. ```js setup(input, lib, bars) { return { ema: lib.ema(bars.close, input.period), run: 0 }; }, onBar(b, state, ctx) { const e = state.ema[b.index]; state.run = b.close > e ? state.run + 1 : 0; // bars in a row above the average ctx.plot("run", state.run); } ``` ## 9. bars, time and sessions ### The fields of bars The first argument of calc. Each field is an array with one value per bar, oldest first. - `bars.length` (`number`): Number of bars. Index 0 is the oldest bar, length - 1 the newest (the bar being formed). - `bars.time` (`number[]`): Opening time of each bar, in milliseconds since 1970 - the time of the broker's server, as MetaTrader shows it. - `bars.open` (`number[]`): Open price of each bar. - `bars.high` (`number[]`): High price of each bar. - `bars.low` (`number[]`): Low price of each bar. - `bars.close` (`number[]`): Close price of each bar (the current price on the newest bar). - `bars.volume` (`number[]`): Tick volume of each bar. ### Time is the broker's server time `bars.time` (and `b.time` in onBar) is the opening time of a bar in milliseconds, on the clock of the broker's server, as MetaTrader shows it. Read it with the UTC functions of Date: `getUTCHours()` is the hour of the server, `getUTCDay()` its day of the week (0 = Sunday). ```js const d = new Date(bars.time[i]); const hour = d.getUTCHours(), minute = d.getUTCMinutes(); const newDay = i > 0 && d.getUTCDate() !== new Date(bars.time[i - 1]).getUTCDate(); ``` ### Sessions A session (for example 08:00 to 12:00) is a test on the hour and minute of the server. Give the user int inputs for the hours: brokers' server clocks differ. Each session drawn is its own plot, with its color in the Style tab - bgcolor for a background, draw for a rectangle: see Trading sessions in Complete examples. ```js const m = d.getUTCHours() * 60 + d.getUTCMinutes(); const inSession = m >= input.startHour * 60 && m < input.endHour * 60; ``` ### Volume `bars.volume` is the tick volume: the number of price changes in the bar. ### How many bars a script receives calc receives the bars of the chart: the last 5000 bars of its timeframe when the chart opens, plus each new bar after that. A seconds timeframe has about 1000; Renko, Point & figure and Range charts at least 1000 of their own. Alerts calculate on the last 5000 bars as well, and each request (`data.`) gets the last 5000 bars of its timeframe or symbol. A chart can have fewer: when the broker holds less history for that timeframe, or the first time a symbol or timeframe is opened, while its history is still arriving (choose the timeframe again a few seconds later). Never assume a number: read `bars.length`. ### Warm-up: the bars a value needs before it appears A value appears only after its warm-up: a 200-bar average has nothing before bar 199. Chained calculations add up: an average of 50 bars of an average of 20 bars needs 69 bars. A plot whose warm-up is longer than the bars of the chart draws nothing at all. When a period can be large - set by the user, or growing on small timeframes - compare it with `bars.length` and say why nothing is drawn with `log.warn`. It goes to the Logs tab, with the numbers the user needs. Do not shorten the period quietly: that would draw another indicator. ```js const need = input.slow + input.signal - 1; // an average of an average if (bars.length < need) { log.warn("Needs " + need + " bars, the chart has " + bars.length + ": nothing is drawn. Use shorter periods or a higher timeframe."); } ``` ### The chart's timeframe A script is not told the timeframe of the chart. When a calculation depends on it, read the length of a bar from `bars.time`: the most common gap between two bars (gaps over weekends and closed sessions are rarer). Daily and longer bars give a day or more. ```js // Milliseconds per bar: the most common gap of the last 500 bars. function barMs(bars) { const count = new Map(); let gap = 0, best = 0; for (let i = Math.max(1, bars.length - 500); i < bars.length; i++) { const d = bars.time[i] - bars.time[i - 1]; const c = (count.get(d) || 0) + 1; count.set(d, c); if (d > 0 && c > best) { best = c; gap = d; } } return gap; } const ms = barMs(bars); const intraday = ms > 0 && ms < 86400000, minutes = ms / 60000; // M15: 15 ``` ## 10. The calculation library: lib 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). Parameters: - `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+2xclose)/4. Returns: One price per bar. ```js 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. Parameters: - `n` (`number`): Number of values (usually bars.length). - `value?` (`any`): Initial value of every element. Default: NaN. Returns: An array of n values. ```js 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. Parameters: - `v` (`number`): The value. - `digits?` (`number`): Number of decimals. Default: 0. Returns: The rounded value. ```js lib.round(1.23456, 2) // 1.23 ``` #### lib.sub(a, b) -> number[] Subtracts one series from another, bar by bar. Parameters: - `a` (`Series`): The first series. - `b` (`Series`): The series subtracted from it. Returns: a[i] - b[i] for each bar. ```js 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). Parameters: - `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. ```js 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. Parameters: - `arr` (`number[]`): The series to change (it is modified in place). - `index` (`number`): Bars before this index lose their value. Returns: The same array. ```js 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. Parameters: - `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. ```js 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"]... ```js 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"]. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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 x (period - 1) + value) / period. Also named lib.rma. Parameters: - `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. ```js const avg = lib.smma(bars.close, 14); ``` #### lib.rma(src, period) -> number[] Same as lib.smma (Wilder's average, used by RSI and ATR). Parameters: - `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. ```js 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. Parameters: - `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. ```js const avg = lib.lwma(bars.close, 10); ``` #### lib.wma(src, period) -> number[] Same as lib.lwma (linear weighted moving average). Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js const avg = lib.vwma(bars.close, bars.volume, 20); ``` #### lib.hma(src, period) -> number[] Hull moving average: WMA(2 x WMA(period / 2) - WMA(period), sqrt period). Fast and smooth. Parameters: - `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. ```js const hull = lib.hma(bars.close, 21); ``` #### lib.dema(src, period) -> number[] Double exponential moving average: 2 x EMA - EMA(EMA). Parameters: - `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. ```js const d = lib.dema(bars.close, 14); ``` #### lib.tema(src, period) -> number[] Triple exponential moving average: 3 x EMA - 3 x EMA(EMA) + EMA(EMA(EMA)). Parameters: - `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. ```js 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. Parameters: - `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. ```js const kama = lib.ama(bars.close, 9, 2, 30); ``` #### lib.frama(src, period) -> number[] Fractal adaptive moving average (Ehlers). MetaTrader 5 default period: 14. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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). Parameters: - `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. ```js const top = lib.highest(bars.high, 20); ``` #### lib.lowest(src, period) -> number[] Lowest value of the last period bars (the current bar included). Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js const age = lib.lowestBars(bars.low, 20); ``` #### lib.sum(src, period) -> number[] Sum of the last period values. Parameters: - `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. ```js const vol20 = lib.sum(bars.volume, 20); ``` #### lib.cum(src) -> number[] Running total since the first bar (values that are NaN are skipped). Parameters: - `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. ```js const total = lib.cum(bars.volume); ``` #### lib.change(src, length?) -> number[] Difference between the value and the value length bars before. Parameters: - `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. ```js const diff = lib.change(bars.close); ``` #### lib.roc(src, length) -> number[] Rate of change in percent: 100 x (value - value length bars before) / value length bars before. Parameters: - `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. ```js 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). Parameters: - `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. ```js const sd = lib.stdev(bars.close, 20); ``` #### lib.stdevAround(src, mean, period) -> number[] Standard deviation of the last period values around a given average. Parameters: - `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. ```js 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). Parameters: - `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. ```js 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. Parameters: - `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. ```js const line = lib.linreg(bars.close, 50); ``` #### lib.correlation(a, b, length) -> number[] Correlation coefficient (Pearson) of two series over the last length bars. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js const down = lib.crossunder(fast, slow); ``` #### lib.cross(a, b) -> boolean[] True on each bar where a crosses b in either direction. Parameters: - `a` (`Series`): The first series. - `b` (`Series | number`): The series or the fixed level. Returns: True on the bars where a crosses b. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js const down3 = lib.falling(bars.close, 3); ``` #### lib.barsSince(cond) -> number[] Number of bars since the condition was last true. Parameters: - `cond` (`ArrayLike`): A condition, one true / false per bar. Returns: 0 on a bar where cond is true; NaN before the first time. ```js const since = lib.barsSince(lib.crossover(fast, slow)); ``` #### lib.valueWhen(cond, src, occurrence?) -> number[] The value src had the last time (or an earlier time) the condition was true. Parameters: - `cond` (`ArrayLike`): 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. ```js 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. Parameters: - `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. ```js 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). Parameters: - `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. ```js 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). Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: NaN on the first bar. ```js 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). Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: One value per bar; NaN until the period is filled. ```js 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 x standard deviation. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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 x an EMA of the true range. Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: ADX, +DI and -DI, from 0 to 100. ```js 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"). Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: ADX, +DI and -DI, from 0 to 100. ```js 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. Parameters: - `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. ```js const ich = lib.ichimoku(bars, 9, 26, 52); ``` #### lib.sar(bars, step, maximum) -> number[] Parabolic SAR, as in MetaTrader 5. Parameters: - `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. ```js 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). Parameters: - `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. ```js 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. Parameters: - `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. ```js 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. Parameters: - `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. ```js const st = lib.stoch(bars, 5, 3, 3); ``` #### lib.cci(src, period) -> number[] Commodity channel index. Usually on the typical price. Parameters: - `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. ```js const cci = lib.cci(lib.price(bars, "typical"), 14); ``` #### lib.momentum(src, period) -> number[] Momentum as in MetaTrader 5: 100 x value / value period bars before. Parameters: - `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. ```js const mom = lib.momentum(bars.close, 14); ``` #### lib.wpr(bars, period) -> number[] Williams' percent range. Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: From -100 to 0. ```js const w = lib.wpr(bars, 14); ``` #### lib.demarker(bars, period) -> number[] DeMarker oscillator. Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: From 0 to 1. ```js const dm = lib.demarker(bars, 14); ``` #### lib.rvi(bars, period) -> { rvi: number[]; signal: number[] } Relative vigor index. Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: The RVI line and its signal line. ```js const r = lib.rvi(bars, 10); ``` #### lib.trix(src, period) -> number[] Rate of change of a triple EMA. Parameters: - `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). ```js const t = lib.trix(bars.close, 14); ``` #### lib.force(src, volume, period, method) -> number[] Force index as in MetaTrader 5: volume x change of the moving average of the price. Parameters: - `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. ```js const f = lib.force(bars.close, bars.volume, 13, "sma"); ``` #### lib.bears(bars, period) -> number[] Bears power: low - EMA(close, period). Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: One value per bar; NaN until the period is filled. ```js const b = lib.bears(bars, 13); ``` #### lib.bulls(bars, period) -> number[] Bulls power: high - EMA(close, period). Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: One value per bar; NaN until the period is filled. ```js 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. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: The running total. ```js const obv = lib.obv(bars); ``` #### lib.ad(bars) -> number[] Accumulation / distribution line. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: The running total. ```js const ad = lib.ad(bars); ``` #### lib.chaikin(bars, fast, slow, method) -> number[] Chaikin oscillator: difference of two averages of the accumulation / distribution line. Parameters: - `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. ```js const ch = lib.chaikin(bars, 3, 10, "ema"); ``` #### lib.mfi(bars, period) -> number[] Money flow index (on the typical price). Parameters: - `bars` (`Bars`): The bars received by calc(). - `period` (`number`): Number of bars. Returns: From 0 to 100. ```js 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). Parameters: - `bars` (`Bars`): The bars received by calc(). - `src?` (`Series`): Price to average. Default: the typical price. Returns: One value per bar. ```js const vwap = lib.vwap(bars); ``` #### lib.volumeColors(bars) -> number[] Color index of the volume bars: returned as "_color", it colors a two-color histogram. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: 0 when the volume rises, 1 otherwise. ```js 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. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: One value per bar; NaN until the period is filled. ```js const ao = lib.ao(bars); ``` #### lib.ac(bars) -> number[] Accelerator oscillator: AO - SMA(AO, 5). Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: One value per bar; NaN until the period is filled. ```js 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). Parameters: - `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. ```js 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). Parameters: - `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. ```js 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. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: The high (up) or low (down) on fractal bars; NaN elsewhere. ```js const f = lib.fractals(bars); ``` #### lib.bwmfi(bars) -> { mfi: number[]; color: number[] } Market facilitation index: (high - low) / volume, with its four colors. Parameters: - `bars` (`Bars`): The bars received by calc(). Returns: color: 0 green, 1 fade, 2 fake, 3 squat. ```js const m = lib.bwmfi(bars); ``` #### lib.upDownColors(values) -> number[] Color index for a two-color histogram (rising / falling). Return it as "_color". Parameters: - `values` (`Series`): The series to color. Returns: 0 when the value rises, 1 when it falls; unchanged when it stays. ```js return { hist: m.hist, hist_color: lib.upDownColors(m.hist) }; ``` ## 11. Other timeframes and symbols: requests ### How requests work requests asks for the bars of other timeframes or symbols. Each one reaches calc as data., with time, open, high, low, close, volume and length like bars, one value per CHART bar, already aligned. No look-ahead, ever: a bar of a higher timeframe is seen from the first chart bar that opens after it closed (Monday's D1 bar appears on Tuesday's first M15 bar), so the history never changes afterwards - what a bar showed live is what it shows later. Another symbol on the same (or a lower) timeframe gives the bar that closes with the chart bar, like close. The pairs are sent by MT5: the symbol must be in its Market Watch. Values are NaN before the first bar available. ### The fields of a request - `tf` (`Timeframe | string`): "same" (the chart's, default), M1 ... MN1, a timeframe of your own in minutes, hours or days (M7, H5, D2), or the id of a timeframe input. - `symbol` (`string`): "same" (the chart's, default), a symbol name such as "GBPUSD", or the id of a symbol input. ### Example ```js 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 }; } }); ``` ### Only closed bars of a higher timeframe `data.` gives, on each chart bar, the last CLOSED bar of the higher timeframe. A higher-timeframe bar that is still forming is never visible, so what a chart bar showed live is what it shows later. A script that read the forming bar of a higher timeframe (a value that changes until that bar closes) cannot be reproduced: it is converted to the closed bar, and its newest values may differ from the original. ### A calculation on the higher-timeframe bars themselves `data.` repeats each higher-timeframe value on every chart bar it covers: an average of `data.daily.close` would average those repeats. To average the daily closes themselves, add a value only when a new daily bar appears (`data.daily.time` changes). ```js 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 lib calculation on the higher-timeframe bars Never pass `data..close` straight to a lib function: each value is repeated on every chart bar it covers, so an RSI, an ATR or an average of it is wrong - without any error or warning. Work in three steps: keep one value per higher-timeframe bar, run lib on those, then put each result back on the chart bars it covers. `htfBars` below does the first and the last step. It gives the higher-timeframe bars with the same fields as `bars` (time, open, high, low, close, volume, length), so lib functions that take bars work too: `lib.rma(lib.tr(h), 14)`. ```js 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)) }; } }); ``` ### Limits of requests - 8 requests per script at most. - One request carries open, high, low, close, volume and time: several values of the same timeframe and symbol need ONE request, not one each. - A request must differ from the chart: another timeframe, another symbol, or both. For the chart itself, use `bars`. - Each request gets the last 5000 bars of its timeframe. A lower timeframe therefore covers only the recent chart bars (5000 M1 bars are about 3 and a half days of round-the-clock trading): older chart bars get NaN. ### Another symbol `symbol: "GBPUSD"`, or the id of a symbol input, gives the bars of that symbol aligned on the chart. Your platform must provide that symbol (in MetaTrader: it must be in the Market Watch). On the chart's own timeframe, `data.` goes straight to the lib functions that take bars: `lib.rma(lib.tr(data.other), 14)` is the ATR of the other symbol. ## 12. Drawing objects: labels, lines, boxes, tables ### How drawing works draw places objects on single bars: labels, lines, boxes, and tables over the chart. A point is [bar, price]: bar is an index in bars (0 = the oldest bar; beyond the newest = in the future). Objects follow the zoom and the scroll like the candles. calc recalculates everything each time, so the objects of the previous calculation are replaced: there is nothing to delete. Up to 5000 objects per indicator (the newest are kept, the Logs tab says so) and 20 tables. A wrong argument stops the calculation with a message on the line of the call. The colors written on an object are final - unless the object names a plot of type draw with plot: "": it then takes its color, opacity, width, line style and check box from that plot in the Style tab, like any plot. Give plot to every object the user may want in another color or without. ### draw.label({ ... }) A text in a bubble whose tip points at a bar. - `bar` (`number`, required): The bar index. - `price` (`number`): The price the tip points at. Not needed with yloc "aboveBar" or "belowBar". - `yloc` (`"price" | "aboveBar" | "belowBar"`): "price" (default), or just above the high / below the low of the bar. - `text` (`any`): The text ("\n" starts a new line). Numbers are accepted. - `style` (`LabelStyle`): "labelDown" (default: the bubble is above the point, its tip points down), "labelUp", "labelLeft", "labelRight", "labelCenter", or "text" (the text alone). - `color` (`string`): Color of the bubble. Default: "#2962FF". - `textColor` (`string`): Color of the text. Default: white (the bubble color for style "text"). - `size` (`Size`): "tiny" ... "huge". Default: "normal". - `plot` (`string`): The id of a plot of type draw: the object takes its color, width, line style and check box from that plot in the Style tab (the fill of a box at the plot's opacity). Without it, the colors written here cannot be changed by the user. - `pane` (`"own" | "price"`): "own" (default): the pane of the script. "price": on the price chart, from an indicator in its own pane; its points are then [bar, price]. For a divergence: one line on the indicator, one on the prices. ```js for (let i = 2; i < bars.length - 2; i++) { if (bars.high[i] > bars.high[i - 1] && bars.high[i] > bars.high[i + 1]) draw.label({ bar: i, price: bars.high[i], text: "H", color: "#EF5350" }); } ``` ### draw.line({ ... }) A straight line between two points, extended or not. - `from` (`[number, number]`, required): First point: [bar, price]. - `to` (`[number, number]`, required): Second point: [bar, price]. - `extend` (`Extend`): "none" (default), "right", "left" or "both": continues the line to the edge of the chart. - `color` (`string`): Default: "#2962FF". - `width` (`number`): 0.5, or a whole number from 1 to 5; 0 hides the line. Default: 1. - `style` (`LineStyle`): Default: "solid". - `plot` (`string`): The id of a plot of type draw: the object takes its color, width, line style and check box from that plot in the Style tab (the fill of a box at the plot's opacity). Without it, the colors written here cannot be changed by the user. - `pane` (`"own" | "price"`): "own" (default): the pane of the script. "price": on the price chart, from an indicator in its own pane; its points are then [bar, price]. For a divergence: one line on the indicator, one on the prices. ```js draw.line({ from: [i1, low1], to: [i2, low2], extend: "right", color: "#26A69A", style: "dash" }); ``` ### draw.box({ ... }) A rectangle between two corners, with an optional text in its middle. - `from` (`[number, number]`, required): A corner: [bar, price]. - `to` (`[number, number]`, required): The opposite corner: [bar, price]. - `color` (`string`): Color of the border ("transparent" for none). Default: "#2962FF". - `fill` (`string`): Color inside. Default: the border color at 20%. - `width` (`number`): Border width: 0.5, or a whole number from 1 to 5; 0 = no border, the fill stays. Default: 1. - `style` (`LineStyle`): Border style. Default: "solid". - `extend` (`Extend`): Stretches the box to the left and/or right edge of the chart. - `text` (`any`): Text in the middle of the box. - `textColor` (`string`): Default: the border color. - `size` (`Size`): Size of the text. Default: "normal". - `plot` (`string`): The id of a plot of type draw: the object takes its color, width, line style and check box from that plot in the Style tab (the fill of a box at the plot's opacity). Without it, the colors written here cannot be changed by the user. - `pane` (`"own" | "price"`): "own" (default): the pane of the script. "price": on the price chart, from an indicator in its own pane; its points are then [bar, price]. For a divergence: one line on the indicator, one on the prices. ```js draw.box({ from: [i, bars.high[i]], to: [i + 10, bars.low[i]], fill: "#2962FF22", text: "Range" }); ``` ### draw.table({ ... }) A table in a corner of the pane, written over the chart (sharp text; a cell can have a tooltip). Tables of the same corner are stacked. - `rows` (`TableCell[][]`, required): The rows, each a list of cells: text, a number, or { text, color, bg, tooltip, align }. 100 rows and 20 cells per row at most. - `position` (`TablePosition`): "topRight" (default), "topLeft", "topCenter", "middleLeft", "middleCenter", "middleRight", "bottomLeft", "bottomCenter" or "bottomRight". - `bg` (`string`): Background of the table. Default: a light grey. - `color` (`string`): Text color. Default: the Foreground color of the chart. - `border` (`string`): Color of the cell borders. Default: none. - `size` (`Size`): Size of the text. Default: "normal". A cell given as an object: - `text` (`any`): The text of the cell. - `color` (`string`): Text color of the cell. - `bg` (`string`): Background of the cell. - `tooltip` (`string`): Shown when the pointer rests on the cell. - `align` (`"left" | "center" | "right"`): Alignment of the text. Default: left. ```js const last = bars.length - 1; draw.table({ position: "topRight", rows: [ ["Trend", { text: up ? "Up" : "Down", color: up ? "#26A69A" : "#EF5350" }], ["ATR", atr[last].toFixed(2)] ] }); ``` ### Drawn again at each calculation Objects are not kept from one calculation to the next: calc draws them all again each time. There is nothing to delete or to move, and objects have no id. To show only the last 50 labels, draw only the last 50. ## 13. Alerts ### Alert conditions A script can offer its own alert conditions. Declare them in alerts, and return "alert_" from calc: true on the bars where the condition is met. The user then picks ": " as the condition in Create alert (Alt+A, or the bell of the indicator's legend) and chooses how often it may trigger. The alert runs even when no chart shows the symbol. - `id` (`string`, required): The key calc returns the condition under: alert_<id>. Letters, digits and _. - `title` (`string`): The name shown in Create alert, for example "Bullish cross". Default: the id. - `message` (`string`): The message the alert starts with; the user can change it. Placeholders such as {{symbol}}, {{tf}}, {{close}} and {{plot:<name>}} are filled in when it triggers. ```js 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) }; } }); ``` ### alert(message, bar) alert() sends a message written by the script. It only counts on the newest bar (the one being formed): calc recalculates all the bars each time, and an alert is about what happens now. Pass the bar index as the second argument when you call it inside a loop; calls on older bars are ignored. To receive these messages, the user picks "<indicator>: Any alert() call" in Create alert. The Logs tab of JS EDITOR shows the calls of the last calculation. ```js calc(bars, input, lib) { const rsi = lib.rsi(bars.close, 14), last = bars.length - 1; if (rsi[last] > 70) alert("RSI overbought: " + rsi[last].toFixed(1)); return { rsi }; } ``` ### In onBar Set a declared condition with `ctx.condition(id, true)`. `alert(message)` counts on the newest bar only. ### Limits 50 alert conditions per script. alert() keeps 20 calls per calculation, each message up to 2000 characters. ## 14. Libraries: library and uses ### How libraries work A library is a file of the scripts folder that calls library({ name, exports }) instead of indicator. It draws nothing by itself: scripts that list it in uses get its functions in use["<name>"] (the 5th argument of calc, or ctx.use in onBar). When the library changes, the charts that use it recalculate. An alert freezes the libraries of its script with it. Keep the functions free of saved state: the same library serves every script. - `name` (`string`, required): The name scripts use: uses: ["My tools"]. - `exports` (`{ [name: string]: any }`, required): What the library shares: functions (and constants). They can use lib, draw, log and alert - what they draw or write goes to the script that calls them. - `id` (`string`): A stable identifier, like an indicator's. - `description` (`string`): What it provides. - `author` (`string`): Who wrote it. - `version` (`string`): Its version. - `license` (`string`): Its license. ```js // 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) }; } }); ``` ## 15. Strategies: strategy({ ... }), orders and the Strategy tab ### How a strategy works A strategy is a script that calls strategy({ ... }) instead of indicator({ ... }). It works bar by bar: setup prepares its series once, then onBar runs on every closed bar and places orders with ctx.entry, ctx.exit, ctx.close and ctx.cancel. On a chart, a strategy shows its plots only. Its orders run in the Strategy tab of LinkingChart, on the tick data you downloaded: an order decided at the close of a bar fills at the first tick after that close, a buy at the ask and a sell at the bid of that tick; pending orders, stop losses, take profits and trailing stops fill at the first tick that reaches them, at that tick's price. The year before the tested period warms the indicators up. The report is the one of the backtests (trades with their signal, equity curve, drawdown, profit factor, Sharpe...), and Optimize tests every combination of the inputs you choose, on all the processor cores. In the FUTURES mode, the strategy is tested on a futures contract you downloaded: its candles are made of its trades (volume in contracts), pips are ticks of the contract (slPips: 8 = 8 ticks) and lots are contracts; the account keeps one position per symbol, like a futures account: an entry in the same direction adds its contracts to the position (pyramiding), and the test stops at the last trading day of the contract (END OF CONTRACT: the open position is closed at the last traded price; you choose whether to continue on the next contract). ### The declaration: strategy({ ... }) The fields of indicator({ ... }) except calc - a strategy works bar by bar (setup and onBar) - plus properties, the defaults of its test: - `properties.lots` (`number`): The size of an entry, in lots (contracts in the FUTURES mode), when the entry gives neither lots nor risk. Default: 0.1 (in the FUTURES mode, the smallest quantity of the contract when it does not accept the value). The user can change it in the Strategy tab. - `properties.risk` (`number`): Percent of the balance risked by an entry that gives no lots: the lots come from the distance to its stop loss (the entry needs one). 0 = fixed lots. - `properties.pyramiding` (`number`): Extra entries allowed in the same direction: 0 (default) = one position at a time (in the FUTURES mode, one entry in the position). An entry in the other direction always closes the open position first (a reversal). ### ctx in a strategy: the orders and the account On top of plot, color, condition, input, lib, data and use, ctx places the orders and reads the simulated account at the close of the bar. - `ctx.entry(id, direction, options)`: Opens a position at the market (or places a pending order with limit / stop). id names the entry: it is the Signal of the trade in the report, and what exit, close and cancel refer to. direction is "long" or "short". A position the other way is closed first (a reversal); in the same direction, pyramiding says how many extra entries are allowed. In the FUTURES mode, an entry in the same direction adds its contracts to the one position (its average price, the same ticket), and its stop loss and take profit become those of the whole position. Options: see Entry options. - `ctx.exit(from, options)`: Sets the stop loss, the take profit or a trailing stop of the positions and pending orders of the entry from (null = all of them). In the FUTURES mode, the stop loss and the take profit are those of the whole position. Options: see Exit options. - `ctx.close(from)`: Closes at the market the positions of the entry from (null = all of them). In the FUTURES mode, the contracts of the entries named from; the other entries of the position stay. - `ctx.closeAll()`: Closes every open position at the market. - `ctx.cancel(from)`: Cancels the pending orders of the entry from (null = all of them). - `ctx.cancelAll()`: Cancels every pending order. - `ctx.position`: The net position: size in lots (contracts in the FUTURES mode; negative when short, 0 when flat), avgPrice (the average open price) and openProfit. - `ctx.positions`: The open positions, one object each: id (the entry), ticket, dir, lots, open, sl, tp, profit. In the FUTURES mode, one object per entry still open in the position: its name, contracts, price and profit; the ticket, sl and tp of the position. - `ctx.orders`: The pending orders: id, ticket, type (buy_limit, sell_stop...), lots, price, sl, tp. - `ctx.equity`: The equity of the simulated account: balance plus the open profit. - `ctx.balance`: The balance of the simulated account. - `ctx.freeMargin`: The free margin of the simulated account. - `ctx.bid`: The bid at the close of the bar (the last tick seen). - `ctx.ask`: The ask at the close of the bar. - `ctx.pip`: The size of a pip of the symbol (0.0001 on EURUSD, 0.01 on USDJPY); in the FUTURES mode, the tick of the contract (0.25 on the E-mini S&P 500). - `ctx.digits`: The decimals of the symbol. - `ctx.symbol`: The tested symbol. - `ctx.tf`: The tested timeframe ("M5", "H1"...). ### Entry options The third argument of ctx.entry. Give one of lots / risk, one of sl / slPips, one of tp / tpPips / tpX, one of limit / stop; everything is optional. - `lots` (`number`): The size of this entry, in lots (contracts in the FUTURES mode: a quantity the contract does not accept is rejected), instead of properties.lots. - `risk` (`number`): Percent of the balance risked by this entry; the lots come from the distance to its stop loss (give slPips or sl). - `limit` (`number`): A pending limit order at this price (a buy below the market, a sell above it) instead of a market order. It fills at the first tick that reaches the price. - `stop` (`number`): A pending stop order at this price (a buy above the market, a sell below it). - `sl` (`number`): The stop loss, as a price. - `slPips` (`number`): The stop loss, in pips from the fill price (SL12 = 12 pips; ticks in the FUTURES mode). - `tp` (`number`): The take profit, as a price. - `tpPips` (`number`): The take profit, in pips from the fill price (ticks in the FUTURES mode). - `tpX` (`number`): The take profit at this multiple of the stop loss distance: tpX: 2 is a 1:2 risk to reward. ### Exit options The second argument of ctx.exit. - `sl` (`number`): A new stop loss, as a price. - `slPips` (`number`): A new stop loss, in pips from the open price of the position (in the FUTURES mode: ticks, from its average price). - `tp` (`number`): A new take profit, as a price. - `tpPips` (`number`): A new take profit, in pips from the open price (ticks in the FUTURES mode). - `trail` (`number`): A trailing stop: the stop loss follows the price at this distance, in pips (ticks in the FUTURES mode), tick by tick, and never moves back. ### Testing and optimizing in the Strategy tab In the Strategy tab: choose the strategy, its inputs, the symbol (Tick data), the timeframe of onBar, the period and the simulated account (balance, leverage, commission, swap). Start test replays every tick of the period. Tick Visual mode (Chart) to watch the test candle by candle, at the speed you choose, with pause and one candle at a time: the result is the same. Optimize: tick the numeric inputs to vary, give each a from, a to and a step; every combination is tested (10000 at most) and ranked by net profit; a row shows its full report, and Run as a single test gives the same result with the chart. Lots, Risk % and Pyramiding (the properties) stay as set during an optimization. ### Example ```js 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 }); } }); ``` ### Pips, prices and the two sides of the market Distances (slPips, tpPips, trail) are in pips: 1 pip = 10 points on a 5-digit symbol (0.0001 on EURUSD), 1 point on others. A buy fills at the ask and closes at the bid; a sell the other way: the spread of each tick is paid, as on a real account. Prices (sl, tp, limit, stop) are rounded to the digits of the symbol. ### What a strategy cannot do - Read the future: onBar sees the bars up to the one that just closed, and the ticks of the next bar fill its orders. - Place orders from setup or from a chart: orders exist in the Strategy tab only. On a chart the strategy draws its plots, nothing else. - Trade a real account: the Strategy tab is a simulation on your tick data. ## 16. Logs: log() ### log() Writes to the Logs tab of JS EDITOR, with the line of the call (a click goes to it). Values of any kind are accepted; long arrays are shortened. The Logs tab shows the messages of the last calculation: when the script is saved, and each time the chart recalculates it. console.log, console.info, console.warn and console.error write there too. - `log(...values)`: Writes an information line. - `log.info(...values)`: Writes an information line. - `log.warn(...values)`: Writes a warning line (yellow). - `log.error(...values)`: Writes an error line (red). It does not stop the script. ```js calc(bars, input, lib) { const rsi = lib.rsi(bars.close, 14); log("last RSI", rsi[bars.length - 1]); if (bars.length < 100) log.warn("only", bars.length, "bars"); return { rsi }; } ``` ## 17. Rules and limits ### A sealed sandbox - No internet access of any kind. - No timers: a script calculates; it never waits. - No files, and no access to the application or to the page. - No import and no require: shared code goes in a library (library and uses). ### Time limit A calculation that takes longer than 2 seconds is stopped. The indicator shows the error; the other indicators keep running. ### Plain JavaScript Modern JavaScript: const and let, arrow functions, classes, Map, Set, template strings. No type annotations (`: number`) and no JSX: they are syntax errors. ### Limits per script - draw: 5000 objects per indicator (the newest are kept), 20 tables, 100 rows of 20 cells per table. - alerts: 50 conditions per script; alert(): 20 calls per calculation. - requests: 8 per script (see Limits of requests); uses: 10 libraries. ### The same result live and on the history A script must show on each past bar the result it gave live. Use only closed data: never read ahead, use a pivot only once it is confirmed, read higher timeframes through requests (it gives closed bars only). ## 18. Same name, different formula Platforms do not all calculate an indicator the same way. lib follows MetaTrader 5. When the original script expects another formula, use the variant given here - otherwise the values differ, sometimes on the first bars only, sometimes everywhere. ### Averages and ranges - `lib.ema`: Starts on the first value, with no simple-average seed. A version seeded with a simple average differs on the first bars only, then the two meet. - `lib.atr`: A SIMPLE average of the true range. Wilder's average true range: `lib.rma(lib.tr(bars), period)`. - `lib.tr`: NaN on the first bar (no previous close). Some platforms use high - low there. - `lib.stdev`: Population formula (divides by n). The sample formula (n - 1): multiply by `Math.sqrt(n / (n - 1))`. - `lib.vwap`: Starts again every day of the broker's server. Other anchors (week, session, a chosen bar): write it with running sums of price x volume and of volume. ### Oscillators and trend - `lib.macd`: The signal line is a SIMPLE average of the MACD line. With an exponential signal: `const line = lib.sub(lib.ema(src, 12), lib.ema(src, 26)); const signal = lib.ema(line, 9); const hist = lib.sub(line, signal);` - `lib.adx`: Lines smoothed by EMA. Wilder's smoothing, the most common elsewhere: `lib.adxWilder(bars, period)`. Two different periods (directional lines and ADX smoothing): write it by hand. - `lib.stoch`: %K slowed as sum(close - lowest) / sum(highest - lowest) over slowing bars. Raw %K: `lib.stoch(bars, k, 1, 1).main`. %K as an AVERAGE of the raw %K: `lib.sma(raw, smooth)`; %D: `lib.sma(k, d)`. - `lib.momentum`: A ratio: 100 x value / value period bars before, around 100. Momentum as a DIFFERENCE (value - value n bars before): `lib.change(src, n)`. - `lib.supertrend`: direction 1 = up trend (line under the price), -1 = down trend. Some platforms use the opposite signs. - `lib.sar`: The acceleration starts at step. A start different from the step: write it by hand. - `lib.wpr`: From -100 to 0. ### Positions in time - `lib.highestBars` / `lib.lowestBars`: 0 or more: how many bars ago. Some platforms give a negative offset: use the opposite. - `lib.pivotHigh` / `lib.pivotLow`: The value sits ON the pivot bar, which is only known right bars later. Some platforms put it on the bar where it is confirmed: `confirmed[i] = ph[i - right]`. ### The usual formulas `lib.sma`, `lib.rma`, `lib.wma`, `lib.hma`, `lib.rsi`, `lib.cci`, `lib.roc`, `lib.change`, `lib.bands`, `lib.keltner`, `lib.linreg`, `lib.correlation`, `lib.percentRank`, `lib.valueWhen`, `lib.barsSince`, `lib.crossover` and `lib.crossunder` follow the usual definitions. ## 19. Converting a script from another platform A conversion rewrites the logic of the original script with the tools of this page - never line by line. Work in this order. ### The method 1. Read the whole original script first. List its settings, what it draws, its alert conditions, the other timeframes or symbols it reads, and its drawing objects. 2. Write the declaration: name, placement (price chart or own pane), precision, inputs, plots, alerts, requests. 3. Choose calc (whole series) or setup + onBar (bar by bar). onBar is the closest to a script that runs once per bar. 4. Rewrite each calculation with lib - check its formula in Same name, different formula - or in plain JavaScript. 5. Return every plot, then Save. Fix what the Errors tab shows until it says No errors. 6. Add to chart and compare a few recent bars with the original, on the same symbol and timeframe. 7. Write at the top of the file, in a comment, what could not be converted and why. Never invent a function that does not exist here. ### Equivalences, idea by idea | In the original script | Here | | --- | --- | | The current value of a series | calc: `src[i]` ; onBar: `b.close` | | The value n bars back | calc: `src[i - n]` (index 0 is the OLDEST bar) ; onBar: `b.at(n).close` | | "No value" and its tests | `NaN` ; `Number.isNaN(v)` ; `isFinite(v) ? v : 0` | | A variable kept from bar to bar | calc: a variable declared before the loop ; onBar: a field of state, created in setup | | The bar number | calc: `i` ; onBar: `b.index` | | Is it the last bar? Is the bar closed? | `i === bars.length - 1` ; `b.isLast` - every bar before the last one is closed | | Settings: whole number, decimal, check box, list, source, timeframe, symbol | inputs of type int, float, bool, select, price, timeframe, symbol | | A color setting, a show / hide check box | no input: the element is a plot, its color and its check box are in the Style tab (How a script is organized) | | Line, step line, area, histogram or columns, circles, crosses, dots | plots of type line, step, area, histogram, circles, cross, dots | | A marker or a character above or below the bar, an arrow | plots of type shape (shape, location, text), char, arrow | | A horizontal line at a fixed value | `levels: [value, ...]` | | A fill between two lines or two levels | a plot of type fill, `between: [a, b]` | | Background color, candle color | plots of type bgcolor and barcolor | | A color that changes bar by bar | `colors: [...]` + `"<id>_color"` (calc) or `ctx.color(id, n)` (onBar) | | A color with transparency | 8-digit hex: `#2962FF80` - the last two digits go from 00 (invisible) to FF (solid) | | A plot drawn some bars ahead or back | `shift` on the plot | | Labels, lines, boxes, tables | `draw.label`, `draw.line`, `draw.box`, `draw.table` - drawn again at each calculation: no ids, nothing to delete; `plot: "<id>"` gives an object the colors of a plot of type draw (Style tab) | | Alert conditions | `alerts: [...]` + `"alert_<id>"` from calc, or `ctx.condition` in onBar | | An alert sent from the code | `alert(message, bar)` | | Data of another timeframe or symbol | `requests` + `data.<name>` - closed higher-timeframe bars only | | Strategy orders: enter, exit, close, cancel | `strategy({ ... })` + `ctx.entry`, `ctx.exit`, `ctx.close`, `ctx.cancel` in onBar (see Strategies) | | The position, the equity of a strategy | `ctx.position`, `ctx.positions`, `ctx.equity`, `ctx.balance` (strategies only) | | Text from numbers | `String(v)`, `v.toFixed(2)`, template strings | | Math functions | `Math.max`, `Math.abs`, `Math.round`, `Math.log`... (all of Math) | | Arrays, maps, matrices | JavaScript arrays, `Map`, arrays of arrays | | Debug output | `log(...)`, `log.warn(...)`: the Logs tab | ### What a script cannot read - Symbol details (tick size, contract size, currency): not available. Show prices with `precision: "price"`. - Every smaller bar inside a chart bar (intrabar data): not available. A request on a smaller timeframe gives one value per chart bar - the one that closes with it. - The account, its positions and its orders - except a strategy, which reads its simulated account in onBar (ctx.equity, ctx.position...). - Anything from the internet. - The timeframe of the chart: read the length of a bar from `bars.time` (see The chart's timeframe). ### Very long periods Some scripts use periods of thousands of bars, often a period that grows on small timeframes. A chart here holds about 5000 bars (see How many bars a script receives). Add up the warm-up of each plot for the smallest timeframe the script will be used on. When it can be longer than the bars of the chart, keep the period of the original and say why nothing is drawn with `log.warn` (see Warm-up). ### When the values differ The first bars of a calculation depend on how much history each platform loads: compare recent bars, far from the start of the history. If the values differ everywhere, check the formula (Same name, different formula), the price used (close, typical...) and the clock of the sessions (here: the broker's server time). ## 20. Porting from Pine Script, name by name Pine Script names (versions 5 and 6) and their LinkingChart equivalents. Read Same name, different formula first: a few calculations share a name but not a formula. Scripts of version 4 and older use the same names without the `ta.`, `request.` and `math.` prefixes (`sma`, `security`, `study`...): map them the same way. ### The language | Pine Script | LinkingChart | | --- | --- | | `open`, `high`, `low`, `close`, `volume` | calc: `bars.open[i]`, `bars.close[i]`... ; onBar: `b.open`, `b.close`... | | `close[1]`, `x[n]` | calc: `x[i - n]` - index 0 is the OLDEST bar ; onBar: `b.at(n).close` | | `bar_index`, `last_bar_index` | calc: `i`, `bars.length - 1` ; onBar: `b.index` | | `time` | `bars.time[i]`: milliseconds on the clock of the broker's server (not UTC) | | `hour`, `minute`, `dayofweek` | `new Date(t).getUTCHours()`, `getUTCMinutes()`, `getUTCDay() + 1` (1 = Sunday, as in `dayofweek`) | | `na`, `na(x)`, `nz(x)`, `nz(x, y)` | `NaN`, `Number.isNaN(x)`, `isFinite(x) ? x : 0`, `isFinite(x) ? x : y` | | `fixnan(x)` | a loop that keeps the last finite value | | `var x = 0` | onBar: `state.x`, created in setup ; calc: a variable declared before the loop | | `varip` | no equivalent: each new price recalculates from the closed bars, as `var` does after its rollback | | `x := y`, `and`, `or`, `not`, `==`, `!=` | `x = y`, `&&`, `\|\|`, `!`, `===`, `!==` | | `for i = 0 to n` | `for (let i = 0; i <= n; i++)` - Pine includes the end | | functions `f(x) =>`, `switch`, `?:` | JavaScript functions, `switch`, `?:` | | `type`, `method` (your own types) | JavaScript objects and classes | | `array.*`, `matrix.*`, `map.*` | JavaScript arrays, arrays of arrays, `Map` | | `str.tostring(x, "#.##")`, `str.format(...)` | `x.toFixed(2)`, template strings | | `math.*` | `Math.*` ; `math.round(x, n)`: `lib.round(x, n)` ; `math.sum(x, n)`: `lib.sum(x, n)` | | `barstate.isfirst`, `barstate.islast`, `barstate.isconfirmed` | `i === 0`, `i === bars.length - 1` (`b.isLast`), `i < bars.length - 1` | | `barstate.isrealtime`, `barstate.isnew`, `barstate.ishistory` | no equivalent: every bar is calculated the same way; only the newest one is still forming | | `runtime.error("...")` | `throw new Error("...")` | | `log.info`, `log.warning`, `log.error` | `log()`, `log.warn()`, `log.error()` | | `import`, `library()`, `export` | `uses: ["Name"]` + `library({ name, exports })`, a file of your scripts folder | ### Declaration and inputs | Pine Script | LinkingChart | | --- | --- | | `indicator("Name", overlay = true)` | `indicator({ name: "Name", placement: "overlay" })` - `overlay = false`: `placement: "separate"` | | `precision = 2`, `format = format.price` | `precision: 2`, `precision: "price"` | | `max_bars_back`, `max_labels_count`, `max_lines_count`, `max_boxes_count` | not needed: calc receives all the bars of the chart, about 5000 (see How many bars a script receives); up to 5000 drawing objects (the newest are kept) | | `input.int(14, "Length", minval = 1)` | `{ id: "length", label: "Length", type: "int", default: 14, min: 1 }` | | `input.float`, `input.bool`; `minval`, `maxval`, `step`, `tooltip` | `type: "float"`, `type: "bool"`; `min`, `max`, `step`, `tooltip` | | `input.string("A", options = ["A", "B"])` | `type: "select", options: ["A", "B"], default: "A"` | | `input.source(close)` | `type: "price"` + `lib.price(bars, input.src)` | | `input.timeframe("D")`, `input.symbol("...")` | `type: "timeframe"` (M1 ... MN1), `type: "symbol"` | | `input.color`, `input.session`, `input.time`, `input.price`, `input.text_area` | none: colors are set in the Style tab; use int, float or select inputs | | `hl2`, `hlc3`, `hlcc4`, `ohlc4` | `lib.price(bars, "median")`, `"typical"`, `"weighted"`; ohlc4: `(open + high + low + close) / 4` in a loop | | timeframes `"1"`, `"60"`, `"240"`, `"D"`, `"W"`, `"M"` | `"M1"`, `"H1"`, `"H4"`, `"D1"`, `"W1"`, `"MN1"` | ### Plots | Pine Script | LinkingChart | | --- | --- | | `plot(x, "Title", color, linewidth = 2)` | a plot `{ id: "x", label: "Title", color, width: 2 }`; calc returns `{ x: values }` | | `plot.style_line`, `plot.style_linebr` | `type: "line"` - a NaN leaves a gap, as with `style_linebr` | | `plot.style_stepline`, `plot.style_area` | `type: "step"`, `type: "area"` | | `plot.style_histogram`, `plot.style_columns` | `type: "histogram"` | | `plot.style_circles`, `plot.style_cross` | `type: "circles"`, `type: "cross"` | | `offset = n`, `histbase = 0` | `shift: n`, `base: 0` | | `color = up ? color.green : color.red` | `colors: ["#26A69A", "#EF5350"]` + calc returns `"x_color"`: 0 or 1 per bar | | `color.new(c, t)`, `color.rgb(r, g, b, t)` | 8-digit hex, alpha = round(255 x (100 - t) / 100): `color.new(#2962FF, 50)` is `"#2962FF80"` | | `plotshape(cond, style = shape.triangleup, location = location.belowbar, size = size.small, text = "B")` | a plot `{ type: "shape", shape: "triangleUp", location: "belowBar", size: "small", text: "B" }`; calc returns true or false per bar | | `shape.xcross`, `cross`, `circle`, `triangleup`, `triangledown`, `arrowup`, `arrowdown`, `square`, `diamond`, `flag`, `labelup`, `labeldown` | `"xcross"`, `"cross"`, `"circle"`, `"triangleUp"`, `"triangleDown"`, `"arrowUp"`, `"arrowDown"`, `"square"`, `"diamond"`, `"flag"`, `"labelUp"`, `"labelDown"` | | `location.abovebar`, `belowbar`, `top`, `bottom`, `absolute`; `size.tiny` ... `size.huge` | `"aboveBar"`, `"belowBar"`, `"top"`, `"bottom"`, `"absolute"`; `"tiny"` ... `"huge"` | | `plotchar(cond, char = "*")` | a plot `{ type: "char", char: "*" }` | | `plotarrow(x)` | two `arrow` plots, `direction: "up"` and `direction: "down"`: positive values in one, negative in the other, NaN elsewhere | | `hline(70)` | `levels: [70]` | | `fill(p1, p2, color)`, `fill(h1, h2, color)` | `{ type: "fill", between: ["p1", "p2"] }`, `between: [30, 70]` | | `bgcolor(cond ? c : na)`, `barcolor(...)` | a `bgcolor` plot, a `barcolor` plot (overlay only): true or false per bar | | `plotcandle`, `plotbar` | not available | ### Drawing objects | Pine Script | LinkingChart | | --- | --- | | `label.new(bar_index, high, "H", style = label.style_label_down, yloc = yloc.abovebar)` | `draw.label({ bar: i, price: bars.high[i], text: "H", style: "labelDown", yloc: "aboveBar" })` | | `label.style_label_up`, `_down`, `_left`, `_right`, `_center`, `label.style_none` | `"labelUp"`, `"labelDown"`, `"labelLeft"`, `"labelRight"`, `"labelCenter"`, `"text"` | | `line.new(x1, y1, x2, y2, extend = extend.right, style = line.style_dashed)` | `draw.line({ from: [x1, y1], to: [x2, y2], extend: "right", style: "dash" })` | | `line.style_solid`, `line.style_dotted`, `line.style_dashed` | `"solid"`, `"dot"`, `"dash"` | | `box.new(left, top, right, bottom)` | `draw.box({ from: [left, top], to: [right, bottom] })` | | `table.new(position.top_right, ...)` + `table.cell(t, col, row, text)` | `draw.table({ position: "topRight", rows: [[...]] })` - `rows[row][col]` | | `xloc = xloc.bar_time` | turn each time into a bar index: `bars.time.indexOf(t)` | | `label.delete`, `label.set_*`, `line.set_*`, arrays of drawings | not needed: each calculation draws everything again; draw only what must show | ### Calculations | Pine Script | LinkingChart | | --- | --- | | `ta.sma`, `ta.wma`, `ta.rma`, `ta.hma` | `lib.sma`, `lib.wma`, `lib.rma`, `lib.hma` | | `ta.vwma(x, n)` | `lib.vwma(x, bars.volume, n)` | | `ta.ema(x, n)` | `lib.ema(x, n)` - the first bars can differ slightly (how each one starts) | | `ta.atr(n)` | `lib.rma(lib.tr(bars), n)` - NOT `lib.atr`, which is a simple average | | `ta.tr`, `ta.tr(true)` | `lib.tr(bars)`: NaN on the first bar, where `ta.tr(true)` gives high - low | | `ta.rsi`, `ta.cci`, `ta.roc`, `ta.change` | `lib.rsi`, `lib.cci`, `lib.roc`, `lib.change` | | `ta.mom(x, n)` | `lib.change(x, n)` - NOT `lib.momentum`, a ratio around 100 | | `ta.macd(x, 12, 26, 9)` | `line = lib.sub(lib.ema(x, 12), lib.ema(x, 26))`, `signal = lib.ema(line, 9)`, `hist = lib.sub(line, signal)` - NOT `lib.macd`, whose signal is a simple average | | `ta.stoch(close, high, low, n)` | `lib.stoch(bars, n, 1, 1).main`; smoothed %K: `lib.sma(raw, smooth)`; %D: `lib.sma(k, d)` | | `ta.stdev(x, n)`, `ta.variance(x, n)` | `lib.stdev(x, n)`, `lib.variance(x, n)`: population, as `biased = true` | | `ta.bb(x, n, mult)` | `lib.bands(x, n, mult)`, which returns `{ middle, upper, lower }` | | `ta.kc(x, n, mult)` | `lib.keltner(bars, x, n, mult)`, which returns `{ middle, upper, lower }` | | `ta.dmi(n, n)` | `lib.adxWilder(bars, n)`, which returns `{ adx, plusDi, minusDi }`; two different lengths: write it | | `ta.supertrend(factor, n)` | `lib.supertrend(bars, factor, n)` - the direction signs are OPPOSITE: here 1 = up trend | | `ta.sar(start, inc, max)` | `lib.sar(bars, inc, max)` when start = inc | | `ta.wpr(n)`, `ta.mfi(hlc3, n)` | `lib.wpr(bars, n)`, `lib.mfi(bars, n)` | | `ta.obv`, `ta.accdist` | `lib.obv(bars)` (it starts at the first volume: a constant apart), `lib.ad(bars)` | | `ta.vwap` | `lib.vwap(bars)` - it restarts each day of the broker's server, not each exchange session | | `ta.highest(x, n)`, `ta.lowest(x, n)` | `lib.highest(x, n)`, `lib.lowest(x, n)`; `ta.highest(n)`: `lib.highest(bars.high, n)` | | `ta.highestbars`, `ta.lowestbars` | `-lib.highestBars(x, n)[i]`, `-lib.lowestBars(x, n)[i]` - Pine's offsets are negative | | `ta.pivothigh(x, l, r)`, `ta.pivotlow(x, l, r)` | `lib.pivotHigh(x, l, r)`, `lib.pivotLow(x, l, r)` sit ON the pivot bar; Pine's value comes r bars later: `ph[i - r]` | | `ta.crossover`, `ta.crossunder`, `ta.cross` | `lib.crossover`, `lib.crossunder`, `lib.cross`: arrays of true or false | | `ta.valuewhen`, `ta.barssince`, `ta.rising`, `ta.falling` | `lib.valueWhen`, `lib.barsSince`, `lib.rising`, `lib.falling` | | `ta.cum`, `ta.linreg`, `ta.correlation`, `ta.percentrank` | `lib.cum`, `lib.linreg`, `lib.correlation`, `lib.percentRank` | | `ta.alma`, `ta.swma`, `ta.cmo`, `ta.cog`, `ta.tsi`, `ta.bbw`, `ta.kcw`, `ta.dev`, `ta.median`, `ta.mode`, `ta.range`, `ta.percentile_*`, `ta.wad`, `ta.wvad`, `ta.nvi`, `ta.pvi`, `ta.pvt`, `ta.iii`, `ta.max`, `ta.min` | not in lib: write them in JavaScript (most are a few lines) | | `ta.*` called inside an `if` or a loop | call the `lib` function once, before the loop: it returns the whole series | ### Other timeframes and alerts | Pine Script | LinkingChart | | --- | --- | | `request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)` | `requests: { daily: { tf: "D1" } }` + `data.daily.close` - the same values | | `request.security(syminfo.tickerid, "D", close)` | `data.daily.close` as well: the same on the history, except that a daily close appears one chart bar later; the forming daily bar is never shown live | | `request.security(..., "D", ta.sma(close, 20))`, `ta.rsi`, `ta.atr`... on a higher timeframe | calculate on the daily bars themselves: `const h = htfBars(data.daily)` then `h.toChart(lib.sma(h.close, 20))` (see Any lib calculation on the higher-timeframe bars). Never `lib.sma(data.daily.close, 20)`: it averages the repeats, wrong without any error | | several `request.security` calls on the same symbol and timeframe | ONE request: it carries open, high, low, close, volume and time. 8 requests per script at most | | `request.security("EURUSD", ...)` | `requests: { eu: { symbol: "EURUSD" } }` + `data.eu.close` | | `request.security_lower_tf`, `request.financial`, `request.economic`, `request.seed` | not available | | `syminfo.*`, `ticker.*`, `chart.*` | not available; show prices with `precision: "price"` | | `timeframe.multiplier`, `timeframe.isintraday`, `timeframe.in_seconds()` | not available: read the length of a bar from `bars.time` (see The chart's timeframe). On M1 a period written as `tf / timeframe.multiplier` can exceed the bars of the chart: see Very long periods | | `alertcondition(cond, "Title", "Message")` | `alerts: [{ id: "x", title: "Title", message: "Message" }]` + calc returns `alert_x` | | `{{ticker}}`, `{{interval}}`, `{{close}}`, `{{plot("Name")}}` | `{{symbol}}`, `{{tf}}`, `{{close}}`, `{{plot:<name>}}` | | `alert(message, alert.freq_once_per_bar)` | `alert(message)` - the user chooses how often in Create alert | ## 21. Checklist before you deliver ### Every script - One `indicator({ ... })` - or one `strategy({ ... })`, or one `library({ ... })` - in the file. - No id copied from another script: leave it out, Save adds one. - The file follows How a script is organized: a comment header, constants, helper functions, one declaration with its parts in order. - Every input is used and has a default (and a min / max when it makes sense). - Inputs change the calculation only: every color, opacity, width, line style and show / hide is a plot, in the Style tab - one plot per element the user may color or hide separately; a draw object names its plot of type draw with plot: "<id>". - calc returns every plot id with `bars.length` values; fills get nothing. - No reading ahead (`src[i + 1]`); pivots are used only once confirmed. - The longest warm-up (chained periods add up) fits in the bars of the chart, about 5000; when it may not, the script says why with `log.warn`. - Only lib functions listed in this code base; anything else in plain JavaScript. - No network calls, no timers, no import or require. - Save shows No errors; Add to chart draws what you expect. - Short comments say what each part does, in plain English. - For a conversion: what could not be converted is written at the top of the file. ## 22. Complete examples Complete scripts, ready to paste into a new file and save. ### A trend band: settings, colors, a fill, markers and alerts ```js 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 ```js 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) ```js 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 ```js 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 ```js 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) ```js 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) ```js 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) ```js // 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 ```js // 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) ```js 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 }); } }); ``` --- Pine Script is a trademark of TradingView, Inc. LinkingChart is an independent product, not affiliated with TradingView.