# Tradequix Pine Script docs > How to write Pine Script v6 on Tradequix, a trading terminal on a live OTC feed. Scripts run on PineTS (an open-source Pine runtime) in the browser, or on the server for closed-source scripts. These docs say what works, what this feed cannot supply, and how to publish. Rules for writing Pine for Tradequix: - Start scripts with //@version=6 and indicator(...) or strategy(...). - Request timeframes as Pine strings: 5S 10S 15S 30S 1 2 3 5 10 15 30 60 240 D come from the feed; others are aggregated; under 5 seconds is refused. - At most 40 request.* contexts per script; each request.security call loads at most 3,600 candles. - Volume is a tick count, not traded size. - Fundamentals, earnings, dividends, economic data and order flow are not available; such requests return na with a warning. - Modified tickers (Heikin Ashi, Renko and similar) are refused; compute Heikin Ashi yourself. - import and libraries are not available. - plotshape/plotchar draw where the series is true or a non-zero number; na, false and 0 draw nothing. - The feed trades 24x7 on UTC; symbols look like EURUSD_otc. - A run must finish within 8 seconds; arrays, matrices and tables hold at most 100,000 elements. # Introduction > What Pine Script on Tradequix is, where your code runs, and how to read these docs. Tradequix runs **Pine Script v6**, the language TradingView made popular for indicators and strategies. You write a script in the editor, and it draws on the live chart in front of you: lines, histograms, markers, labels, tables, and strategy backtests. The engine underneath is [PineTS](https://github.com/LuxAlgo/PineTS), an open-source runtime for Pine Script. It runs the same bar-by-bar model as Pine, so most scripts written for TradingView run here unchanged. Where they don't, it is almost always because of the data, and these docs say exactly where that happens. ## Where your code runs | Your script is | It runs | Who can read the code | | --- | --- | --- | | A draft or a private script | In your browser, in a background worker | Only you | | Published open source | In each viewer's browser | Anyone | | Published protected or invite-only | On the Tradequix server | Only you. Subscribers receive computed values, never the source. | Running in a worker means a slow script never freezes the chart. Running closed scripts on the server is what makes selling access possible without giving the code away. ## A 60-second tour 1. Open the terminal at [/chart](/chart) and choose **Pine Script** in the side rail. 2. The editor opens with a starter script. Press **Add to chart** (Ctrl Enter) and it draws. 3. Change a number and add it again. The chart updates in place. 4. **Save** (Ctrl S) keeps the script in your account. 5. **Publish** puts it in the community catalogue, open or closed. Every example in these docs has a **Run** button of its own. Try one: ```pine //@version=6 indicator("Two averages", overlay = true) fast = ta.ema(close, 21) slow = ta.ema(close, 55) plot(fast, "EMA 21", color = color.new(#8b7cff, 0), linewidth = 2) plot(slow, "EMA 55", color = color.new(#ffb547, 0), linewidth = 2) ``` It runs on a fixed, generated EUR/USD-style series, so it works signed out and draws the same picture for everyone. **Open in editor** takes the code to the terminal, where it runs on the real feed. ## How to read these docs - **Start** gets you running and explains the one idea everything else depends on: a script runs once per bar. - **Write** covers each part of the language you will use: plots, inputs, `ta.*`, drawings, other timeframes, strategies, alerts. - **On Tradequix** is what is specific to this platform: the data, publishing and selling, and debugging. - **Reference** has the coverage tables, the built-in catalogue, a cookbook, and how to write Pine with an AI assistant. > [!TIP] > Press **Ctrl K** (or **/**) anywhere in the docs to search pages, headings and functions like `ta.rsi`. --- # Quickstart > Write, run and save your first indicator, then turn it into something you would actually trade with. This page builds one script in four small steps. Run each step to see what changed. ## 1. The smallest script that draws Every script starts with a version line and a declaration. `indicator()` says this is an indicator; `overlay = true` puts it on the price chart instead of in its own pane. ```pine //@version=6 indicator("My first script", overlay = true) plot(ta.sma(close, 20), "SMA 20", color = color.orange) ``` `close` is the closing price of each bar. `ta.sma(close, 20)` averages the last 20 closes. `plot()` draws the result as a line. ## 2. Make the length adjustable Hard-coded numbers become inputs. Each `input.*` call adds a field to the indicator's settings, so you can change it without editing code. ```pine //@version=6 indicator("Adjustable average", overlay = true) length = input.int(20, "Length", minval = 1) src = input.source(close, "Source") plot(ta.sma(src, length), "SMA", color = color.orange, linewidth = 2) ``` ## 3. Mark the crosses Signals are conditions. `ta.crossover(a, b)` is `true` on the bar where `a` moves above `b`. `plotshape` draws a marker on those bars. ```pine //@version=6 indicator("Cross markers", overlay = true) fast = ta.ema(close, 9) slow = ta.ema(close, 21) plot(fast, "Fast", color = color.teal) plot(slow, "Slow", color = color.red) plotshape(ta.crossover(fast, slow), "Bull cross", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small) plotshape(ta.crossunder(fast, slow), "Bear cross", style = shape.triangledown, location = location.abovebar, color = color.red, size = size.small) ``` > [!NOTE] > `plotshape` draws only where its series is `true` or a non-zero number. A condition is the right thing to pass it. See [Plotting](/docs/plotting) for why `plotshape(ta.pivothigh(...))` behaves the way it does. ## 4. A separate pane An oscillator lives in its own pane. Drop `overlay = true` (it defaults to `false`) and add reference lines with `hline`. ```pine //@version=6 indicator("RSI with zones") r = ta.rsi(close, 14) plot(r, "RSI", color = color.purple, linewidth = 2) hline(70, "Overbought", color = color.red) hline(30, "Oversold", color = color.teal) ``` ## Save it, then use it In the terminal's editor: - **Add to chart** (Ctrl Enter) runs the script on the chart you are looking at. - **Save** (Ctrl S) stores it in your account, so it is there next session. - The indicator's **settings** (the gear in its legend) show the inputs from step 2. - **Publish** shares it. See [Publish and sell](/docs/publishing). Next, read [How a script runs](/docs/execution-model). It explains `close[1]`, `var` and `na`, which is where most first scripts go wrong. --- # How a script runs > Pine runs your whole script once per bar, oldest to newest. Series, history references, var and na all follow from that. The single idea behind Pine: **your script runs once for every bar on the chart**, starting at the oldest and ending at the newest. On each run, `close`, `open`, `high`, `low` and `volume` hold that bar's values. Every variable you compute becomes a *series*: one value per bar. Step through it yourself: Interactive: a 12-bar stepper. Pine executes the script once per bar, left to right. On each bar, close is that bar's close and close[1] is the previous bar's close (na on the first bar). A variable declared with var keeps its value from the previous bar; a plain variable is recalculated from scratch on every bar. ta.sma(close, 3) is na until three bars exist. ## History with `[]` `x[1]` is the value `x` had one bar ago, `x[2]` two bars ago, and so on. It works on any series, including ones you compute. ```pine //@version=6 indicator("Bar-to-bar change") change = close - close[1] plot(change, "Change", style = plot.style_histogram, color = change >= 0 ? color.teal : color.red) ``` On the very first bar there is no previous bar, so `close[1]` is `na` and so is `change`. ## `na`: no value yet `na` means "no value". It appears when you look further back than the chart goes, and while an average is still warming up: `ta.sma(close, 50)` is `na` for the first 49 bars. `na` spreads through arithmetic: `na + 1` is `na`. - Test for it with `na(x)`. - Replace it with `nz(x)` (gives `0`) or `nz(x, fallback)`. - A plot simply leaves a gap where the value is `na`. ## `var`: keep a value between bars A plain declaration runs again on every bar, so the variable starts fresh. `var` declares it once, on the first bar, and keeps whatever you assign afterwards. ```pine //@version=6 indicator("Counting up bars") var int ups = 0 if close > open ups += 1 plot(ups, "Up bars so far", color = color.teal) ``` Without `var`, `ups` would be `0` or `1` on every bar, never a running total. ## The current bar On a live chart the newest bar is still forming. The script runs again as its price changes, so values on the last bar can move until it closes. Signals that must not change after they appear should check `barstate.isconfirmed`, which is `true` only once a bar has closed. > [!WARNING] > Logic that looks ahead (for example `close[-1]`, or `request.security` with lookahead) can look perfect on history and never happen live. If a backtest looks too good, check for this first. --- # Types and qualifiers > The types Pine values have, and the qualifiers (const, input, simple, series) that say when a value is known. Why some arguments refuse a series. Every value in Pine has a **type** (what it is) and a **qualifier** (when it is known). Most of the time Pine works both out for you; you only meet them in error messages, or when a function insists on a value that does not change. ## Types | Type | Holds | Example | | --- | --- | --- | | `int` | Whole numbers | `14`, `bar_index` | | `float` | Decimals | `close`, `1.5` | | `bool` | `true` or `false` | `close > open` | | `string` | Text | `"EMA"` | | `color` | A colour | `color.teal`, `#8b7cff` | | `label`, `line`, `box`, `table`… | An id for a drawing | the result of `label.new(...)` | | `array`, `matrix`, `map` | Collections | see [Arrays, matrices and maps](/docs/collections) | | Your own types | Fields you define | see [Objects and enums](/docs/objects) | `na` is a value of any type that means "no value". `int` mixes freely with `float`. ## Qualifiers, from strictest to loosest | Qualifier | Known | Example | | --- | --- | --- | | `const` | When the script is written | `20`, `"title"` | | `input` | When settings are applied | `input.int(20)` | | `simple` | On the first bar, then fixed | `syminfo.mintick` | | `series` | Can change on every bar | `close`, `ta.rsi(close, 14)` | A function argument documented as `simple int` accepts a const, input or simple value, but not a series. This is why some lengths cannot vary per bar. ```pine //@version=6 indicator("Qualifiers") len = input.int(14, "Length") // input int: fine as a length r = ta.rsi(close, len) // series float plot(r, "RSI", color = color.purple) ``` ## Declaring with a type Type keywords are optional; add one when a variable starts as `na`, so Pine knows what it will hold: ```pine float lastHigh = na var label tag = na ``` ## Converting `int(x)` truncates a float, `float(x)` widens an int, `str.tostring(x)` makes text. Use `math.round(x)` rather than `int(x)` when you mean "nearest". --- # Operators, conditionals and loops > Arithmetic and logic operators, the ternary, if and switch as expressions, and for and while loops with their limits. ## Operators | Kind | Operators | | --- | --- | | Arithmetic | `+ - * / %` | | Comparison | `== != > < >= <=` | | Logic | `and`, `or`, `not` | | Ternary | `cond ? a : b` | | History | `x[n]` | | Assignment | `=` declares, `:=` reassigns, `+= -= *= /=` update | Use `:=` to change a variable after declaring it; `=` a second time declares a new one and is an error in the same scope. ## if and switch return values Both can be used as expressions: the last line of the branch is the value. ```pine //@version=6 indicator("Trend state") fast = ta.ema(close, 12) slow = ta.ema(close, 26) state = if fast > slow and close > fast 2 else if fast > slow 1 else -1 plot(state, "State", style = plot.style_stepline, color = state > 0 ? color.teal : color.red) ``` `switch` picks the first matching case; a case with no expression is the default: ```pine kind = input.string("EMA", options = ["SMA", "EMA"]) avg = switch kind "SMA" => ta.sma(close, 20) => ta.ema(close, 20) ``` ## Loops `for i = 0 to n` counts (inclusive), with an optional `by` step. `for x in array` walks an array. `while cond` repeats. `break` and `continue` work as you expect. ```pine //@version=6 indicator("Up closes in the last 20 bars") count = 0 for i = 0 to 19 if close[i] > close[i + 1] count += 1 plot(count, "Up closes", color = color.teal) ``` > [!TIP] > Most loops over history have a built-in that is faster and clearer: this one is `math.sum(close > close[1] ? 1 : 0, 20)`. Reach for a loop when no built-in fits. ## Loop limits The engine stops a loop that runs past its iteration ceiling with "Loop exceeded maximum iterations", and a whole run must finish in 8 seconds. Bound every loop by a length, never by "all history". See [Limits](/docs/limits). --- # Functions and methods > Write your own functions with =>, return several values as a tuple, and call functions as methods. Libraries and import are not available. ## Your own functions A function is a name, its parameters, `=>`, and a body. One line: ```pine pct(a, b) => (a - b) / b * 100 ``` Or several lines, indented; the last line is the result: ```pine //@version=6 indicator("Band position") bandPos(src, len, mult) => [mid, up, lo] = ta.bb(src, len, mult) (src - lo) / (up - lo) plot(bandPos(close, 20, 2), "%B", color = color.purple) hline(1) hline(0) ``` Each call keeps its own history, so calling a function that uses `ta.*` inside it twice with different arguments gives two independent results. ## Returning several values Return a tuple and destructure it at the call: ```pine //@version=6 indicator("Range stats", overlay = true) rangeOf(len) => hi = ta.highest(high, len) lo = ta.lowest(low, len) [hi, lo, (hi + lo) / 2] [h, l, m] = rangeOf(30) plot(h, "High", color = color.teal) plot(l, "Low", color = color.red) plot(m, "Mid", color = color.gray) ``` ## Methods A function declared with `method` can be called with a dot on its first argument. Built-in functions for arrays and drawings can be called the same way: `arr.push(x)` is `array.push(arr, x)`. ```pine method spread(float a, float b) => a - b d = close.spread(open) ``` ## Libraries Pine **libraries** (`library()` and `import user/name/1`) are not available on Tradequix: there is no library resolver. Copy the functions you need into your script. The [checker](/docs/check) flags imports for you. --- # Objects and enums > Define your own types with fields, create and change objects, and use enums for a fixed set of options. ## User-defined types `type` groups related values. Create one with `.new()`, read and change fields with a dot. ```pine //@version=6 indicator("Swing tracker", overlay = true) type Swing float price int bar var Swing last = Swing.new(high, bar_index) if high > last.price last.price := high last.bar := bar_index plot(last.price, "Highest so far", color = color.teal, style = plot.style_stepline) ``` Fields can have defaults (`float price = na`). Objects are references: assigning one to another variable does not copy it. ## Enums An enum is a fixed list of named options, useful for a dropdown that cannot be mistyped. ```pine enum Mode fast = "Fast" slow = "Slow" mode = input.enum(Mode.fast, "Mode") len = mode == Mode.fast ? 10 : 30 ``` ## How far these go here User-defined types and enums are supported. Methods on your own types and some object features are marked as in progress upstream in PineTS, so test a type-heavy script in the editor before relying on it. See [Coverage](/docs/coverage). --- # Arrays, matrices and maps > Collections of values: rolling windows with arrays, grids with matrices, and lookups with maps. Up to 100,000 elements each. ## Arrays An array holds a list of one type. Declare it with `var` so it survives between bars, otherwise you get a new empty array every bar. ```pine //@version=6 indicator("Rolling median of ranges") var array ranges = array.new() ranges.push(high - low) if ranges.size() > 50 ranges.shift() plot(ranges.median(), "Median range", color = color.orange) plot(high - low, "Range", color = color.new(color.gray, 50), style = plot.style_columns) ``` The pattern above is a rolling window: push the newest, shift the oldest once it is long enough. Common functions: `push`, `pop`, `shift`, `unshift`, `get`, `set`, `size`, `sum`, `avg`, `median`, `max`, `min`, `stdev`, `sort`, `includes`, `indexof`, `slice`, `join`. The full list is in the [reference](/docs/reference/collections). ## Matrices A two-dimensional grid: `matrix.new(rows, columns, initial)`, then `get`, `set`, `row`, `col`, `transpose`, `mult` and more. ## Maps Key-value lookups: `map.new()`, then `put`, `get`, `contains`, `remove`, `keys`, `values`. ```pine var map levels = map.new() levels.put("high", ta.highest(high, 20)) levels.put("low", ta.lowest(low, 20)) plot(levels.get("high")) ``` ## Limits Arrays, matrices and tables hold at most **100,000** elements; asking for more stops the script with "The requested size exceeds the 100000 element limit". Index out of range is a runtime error naming the line. --- # Strings and colours > Format numbers for labels and tables, build text, and make colours with transparency and gradients. ## Strings Strings are text in double or single quotes. Join them with `+`. - `str.tostring(x, format.mintick)` formats a price to the symbol's precision; `"#.00"` gives two decimals; `format.percent` adds a percent sign. - `str.format("{0} at {1}", "RSI", r)` fills placeholders. - `str.contains`, `str.replace_all`, `str.split`, `str.upper`, `str.length` do what they say. ```pine //@version=6 indicator("Price tag", overlay = true) if barstate.islast txt = str.format("{0} RSI {1}", str.tostring(close, format.mintick), str.tostring(ta.rsi(close, 14), "#.0")) label.new(bar_index, high, txt, style = label.style_label_down, color = color.new(#100e18, 0), textcolor = color.white) ``` ## Colours - Named colours: `color.teal`, `color.red`, `color.orange`, `color.purple`, `color.gray` and more. - Hex: `#8b7cff`, or with transparency `#8b7cff80`. - `color.new(c, transp)` sets transparency from 0 (solid) to 100 (invisible). - `color.rgb(r, g, b, transp)` builds one from channels. - `color.from_gradient(value, lo, hi, loColor, hiColor)` blends by where a value sits. ```pine //@version=6 indicator("Gradient RSI") r = ta.rsi(close, 14) plot(r, "RSI", color = color.from_gradient(r, 30, 70, color.red, color.teal), linewidth = 3) hline(70) hline(30) ``` A colour can change per bar: pass a series (often a ternary) wherever a `color` is accepted. --- # Time and sessions > The OTC feed trades around the clock on UTC. Reading bar time, filtering by hour, and what session variables mean here. ## The clock this feed runs on OTC pairs on Tradequix trade **24 hours a day, 7 days a week**, and bars sit on a plain **UTC** grid. For a script that means: - `syminfo.timezone` is `"Etc/UTC"` and `syminfo.session` is `"24x7"`. - There are no weekend gaps and no market open or close, so `session.ismarket` is always true and pre- and post-market are empty. - Symbols look like `EURUSD_otc`. For six-letter pairs, `syminfo.basecurrency` and `syminfo.currency` are filled from the name (`EUR`, `USD`). ## Reading time `time` is the bar's open time in milliseconds. The calendar functions take a time and, optionally, a timezone: | Function | Gives | | --- | --- | | `year(time)`, `month(time)`, `dayofmonth(time)` | The date | | `hour(time)`, `minute(time)`, `second(time)` | The time of day | | `dayofweek(time)` | 1 (Sunday) to 7 (Saturday) | | `timestamp(...)` | A time from parts | They default to UTC here. Pass a timezone to shift: `hour(time, "Asia/Dhaka")`. ## Trading hours of your own Even on a round-the-clock feed you may only want to act at certain hours. Filter by hour: ```pine //@version=6 indicator("London hours", overlay = true) h = hour(time, "UTC") inLondon = h >= 7 and h < 16 bgcolor(inLondon ? color.new(#8b7cff, 90) : na) ``` ## Formatting a time `str.format_time(time, "yyyy-MM-dd HH:mm", "UTC")` turns a time into text for a label or a table. --- # Bar states > barstate.* tells the script where it is in the run: the first bar, the last, history or live, and whether the bar has closed. Because a script runs once per bar, it sometimes needs to know *which* bar it is on. | Variable | true when | | --- | --- | | `barstate.isfirst` | The first bar of the run | | `barstate.islast` | The last bar on the chart (the forming one, when live) | | `barstate.ishistory` | A bar that had closed before the chart loaded | | `barstate.isrealtime` | A bar forming while the chart is open | | `barstate.isnew` | The first update of a new bar | | `barstate.isconfirmed` | The bar has closed | | `barstate.islastconfirmedhistory` | The last closed bar before live bars began | ## The two you will use most **Draw once, at the end.** Wrap drawings and tables in `if barstate.islast` so they are made once rather than on every bar of history. **Signal only on closed bars.** On the live bar, prices move until it closes. A condition can be true mid-bar and false at the close. Require `barstate.isconfirmed` for signals that must not disappear: ```pine //@version=6 indicator("Confirmed crosses", overlay = true) f = ta.ema(close, 9) s = ta.ema(close, 21) plotshape(ta.crossover(f, s) and barstate.isconfirmed, "Confirmed", style = shape.triangleup, location = location.belowbar, color = color.teal) ``` On history every bar is confirmed, so this only changes behaviour live. See [Repainting](/docs/repainting). --- # Plotting > Every way a script draws a series: plot styles, markers, reference lines, fills and colouring bars, on the price chart or in its own pane. A script that computes something still needs to draw it. Pine's drawing functions take a series and turn it into lines, markers or colours on the chart. ## Price chart or its own pane `indicator("...", overlay = true)` draws on the price chart. Leave `overlay` out (it defaults to `false`) and the script gets its own pane below the chart, with its own scale. Oscillators such as RSI belong in a pane; averages and bands belong on price. A single script can still put one visual on the price chart from a pane with `force_overlay = true` on that call. ## `plot()` and its styles ```pine //@version=6 indicator("Plot styles") mom = ta.mom(close, 10) plot(mom, "Momentum", style = plot.style_columns, color = mom >= 0 ? color.new(color.teal, 30) : color.new(color.red, 30)) plot(ta.sma(mom, 9), "Signal", color = color.orange, linewidth = 2) hline(0, "Zero", color = color.gray) ``` | Style | Draws | | --- | --- | | `plot.style_line` (default) | A continuous line | | `plot.style_linebr` | A line with gaps where the value is `na` | | `plot.style_stepline` | Steps instead of slopes | | `plot.style_histogram` | Thin bars from the base line | | `plot.style_columns` | Wide bars from the base line | | `plot.style_area` / `style_areabr` | A filled area | | `plot.style_circles` / `style_cross` | A dot or a cross per bar | Useful arguments: `linewidth`, `color` (which can change per bar, as above), `offset` to shift the plot left or right, `show_last` to draw only the last N bars, and `display = display.none` to compute a plot without drawing it (handy as the input to a `fill`). ## Markers: `plotshape`, `plotchar`, `plotarrow` Markers mark events, not values. `plotshape` draws a shape, `plotchar` draws a character, `plotarrow` draws an arrow sized by its value (positive up, negative down). ```pine //@version=6 indicator("RSI extremes", overlay = true) r = ta.rsi(close, 14) plotshape(ta.crossunder(r, 30), "Oversold", style = shape.circle, location = location.belowbar, color = color.teal, size = size.tiny) plotshape(ta.crossover(r, 70), "Overbought", style = shape.circle, location = location.abovebar, color = color.red, size = size.tiny) plotchar(ta.cross(close, ta.sma(close, 50)), "Cross 50", char = "x", location = location.top, color = color.orange) ``` > [!WARNING] > A marker appears only where the series is `true` or a **non-zero number**. `na`, `false` and `0` draw nothing. So `plotshape(ta.pivothigh(high, 5, 5))` does draw, at each pivot, because a pivot returns a price; but a condition like `not na(ph)` says what you mean more clearly. If your markers never appear, print the series with `plot()` first and check it is ever true. Locations: `location.abovebar`, `location.belowbar`, `location.top`, `location.bottom`, and `location.absolute`, which places the marker at the series value itself. ## Reference lines and fills `hline(price)` draws a fixed horizontal line. `fill(a, b, color)` shades between two plots or two hlines; pass the objects those calls return. ```pine //@version=6 indicator("Bollinger fill", overlay = true) [mid, up, lo] = ta.bb(close, 20, 2) p1 = plot(up, "Upper", color = color.new(#8b7cff, 0)) p2 = plot(lo, "Lower", color = color.new(#8b7cff, 0)) plot(mid, "Basis", color = color.new(#ffb547, 0)) fill(p1, p2, color = color.new(#8b7cff, 88), title = "Band") ``` ## Colouring the chart itself - `bgcolor(color)` tints the background of a bar. - `barcolor(color)` recolours the candles. ```pine //@version=6 indicator("Trend tint", overlay = true) trendUp = ta.ema(close, 20) > ta.ema(close, 50) bgcolor(trendUp ? color.new(color.teal, 90) : color.new(color.red, 92)) barcolor(close > open ? color.teal : color.red) ``` ## Drawing candles `plotcandle` and `plotbar` draw your own OHLC series, for example Heikin Ashi computed by hand, in a pane or on price. ## How close it is to TradingView Every style above is drawn natively. A few things are approximations rather than pixel-identical: some marker and label shapes, proportional arrow sizing, curved lines, and table layout. The numbers are exact; the shapes are close. --- # Inputs > Turn hard-coded numbers into settings. Every input.* call becomes a field in the indicator's settings, saved per chart. An input is a value the person using the script can change without touching code. Each `input.*` call adds one field to the indicator's **settings** dialog (the gear in its legend), and the chart re-runs the script with the new value. ```pine //@version=6 indicator("Envelope", overlay = true) length = input.int(20, "Length", minval = 1, maxval = 500) pct = input.float(1.5, "Width %", minval = 0.1, step = 0.1) src = input.source(close, "Source") showMid = input.bool(true, "Show basis") col = input.color(color.new(#8b7cff, 0), "Colour") basis = ta.sma(src, length) plot(showMid ? basis : na, "Basis", color = col) plot(basis * (1 + pct / 100), "Upper", color = col) plot(basis * (1 - pct / 100), "Lower", color = col) ``` ## The input types | Function | Field in settings | | --- | --- | | `input.int` | A whole number, with `minval`, `maxval`, `step` | | `input.float` | A decimal number, same options | | `input.bool` | A checkbox | | `input.color` | A colour picker | | `input.source` | A choice of series: `close`, `open`, `hl2`, `hlc3`, `ohlc4`… | | `input.timeframe` | A timeframe picker, for use with `request.security` | | `input.string` with `options = [...]` | A dropdown | | `input.text_area` | A multi-line text box | The second argument is the **title**, which is the label in settings. ## A dropdown ```pine //@version=6 indicator("Average of your choice", overlay = true) kind = input.string("EMA", "Average", options = ["SMA", "EMA", "WMA", "HMA"]) len = input.int(30, "Length", minval = 2) avg = switch kind "SMA" => ta.sma(close, len) "EMA" => ta.ema(close, len) "WMA" => ta.wma(close, len) => ta.hma(close, len) plot(avg, kind, color = color.orange, linewidth = 2) ``` ## How saved values behave Values you set are saved with the indicator on that chart and come back next session. They are matched to inputs by **position in the script**, not by title. So when you later edit the script: - A number now outside a new `minval`/`maxval` is clamped into range. - A value whose input changed **type** (say a number that became a checkbox) is dropped, with a warning naming the setting. - A saved value whose input no longer exists is dropped, with a warning. - **Inserting** an input above others shifts their positions, so their saved values can land on the wrong field. Add new inputs at the end of the list when a script is already in use. > [!TIP] > Give related inputs the same `group = "Bands"` and the settings dialog shows them under one heading, in the order you declared them. --- # Technical analysis > The ta.* namespace: averages, oscillators, bands, crosses, pivots and multi-value studies, with working recipes. `ta.*` holds the building blocks: more than seventy functions, from `ta.sma` to `ta.supertrend`. They all follow the bar-by-bar model, so each returns a series and handles its own warm-up (the first bars are `na`). ## Averages | Function | Notes | | --- | --- | | `ta.sma(src, len)` | Simple average | | `ta.ema(src, len)` | Exponential, reacts faster | | `ta.wma(src, len)` | Linearly weighted | | `ta.hma(src, len)` | Hull, smooth and fast | | `ta.rma(src, len)` | Wilder's smoothing, used inside RSI and ATR | | `ta.vwma(src, len)` | Volume weighted (see the note on volume below) | | `ta.alma(src, len, offset, sigma)` | Arnaud Legoux | ## Oscillators and volatility `ta.rsi`, `ta.stoch`, `ta.cci`, `ta.mfi`, `ta.mom`, `ta.roc`, `ta.tsi`, `ta.wpr`, `ta.atr`, `ta.tr`, `ta.stdev`, `ta.dev`, and more. ```pine //@version=6 indicator("Stochastic") k = ta.sma(ta.stoch(close, high, low, 14), 3) d = ta.sma(k, 3) plot(k, "%K", color = color.new(#8b7cff, 0), linewidth = 2) plot(d, "%D", color = color.new(#ffb547, 0)) hline(80, "Upper", color = color.gray) hline(20, "Lower", color = color.gray) ``` ## Studies that return several values Some functions return a tuple. Destructure it with square brackets: ```pine //@version=6 indicator("MACD") [macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9) plot(hist, "Histogram", style = plot.style_columns, color = hist >= 0 ? color.new(color.teal, 40) : color.new(color.red, 40)) plot(macdLine, "MACD", color = color.new(#8b7cff, 0)) plot(signalLine, "Signal", color = color.new(#ffb547, 0)) ``` Others in this family: `ta.bb` (basis, upper, lower), `ta.kc` (Keltner), `ta.dmi` (+DI, -DI, ADX), `ta.supertrend` (value, direction). ```pine //@version=6 indicator("Supertrend", overlay = true) [st, dir] = ta.supertrend(3, 10) plot(dir < 0 ? st : na, "Up trend", color = color.teal, style = plot.style_linebr, linewidth = 2) plot(dir > 0 ? st : na, "Down trend", color = color.red, style = plot.style_linebr, linewidth = 2) ``` In `ta.supertrend`, a **negative** direction means an up trend. ## Crosses, highs and lows, pivots - `ta.crossover(a, b)`, `ta.crossunder(a, b)`, `ta.cross(a, b)`: `true` on the bar the cross happens. - `ta.highest(src, len)`, `ta.lowest(src, len)`, and `ta.highestbars` / `ta.lowestbars` for how many bars ago. - `ta.pivothigh(src, left, right)` and `ta.pivotlow(...)`: the pivot price, reported `right` bars after the pivot (because it needs those bars to confirm). `na` elsewhere. - `ta.valuewhen(cond, src, n)`: the value of `src` the n-th last time `cond` was true. - `ta.barssince(cond)`: bars since `cond` was last true. ```pine //@version=6 indicator("Pivot levels", overlay = true) ph = ta.pivothigh(high, 10, 10) pl = ta.pivotlow(low, 10, 10) plot(ta.valuewhen(not na(ph), ph, 0), "Last pivot high", color = color.red, style = plot.style_stepline) plot(ta.valuewhen(not na(pl), pl, 0), "Last pivot low", color = color.teal, style = plot.style_stepline) plotshape(not na(ph), "PH", style = shape.triangledown, location = location.abovebar, color = color.red, offset = -10, size = size.tiny) plotshape(not na(pl), "PL", style = shape.triangleup, location = location.belowbar, color = color.teal, offset = -10, size = size.tiny) ``` `offset = -10` draws each marker back on the bar that actually was the pivot. ## A note on volume Volume on this feed is a **tick count** per bar, not traded size. Indicators that compare volume between bars (`ta.obv`, `ta.mfi`, plotting volume itself) are meaningful on it. Ones that treat it as size, such as `ta.vwap` and accumulation/distribution, still compute, and the editor warns that the result is approximate. See [The data](/docs/data). --- # Drawings and tables > Labels, lines, boxes, polylines and tables: objects a script places at exact coordinates, and how they behave on Tradequix. Plots draw one value per bar. Drawings are objects you place yourself: a label at a price, a line between two points, a box around a range, a table pinned to a corner. Each is created with `*.new(...)` and can be changed later through the id it returns. ## Labels and lines on the last bar A common pattern is to draw only once, on the last bar, so the object does not repeat on every bar of history. ```pine //@version=6 indicator("Last price label", overlay = true) hi = ta.highest(high, 50) lo = ta.lowest(low, 50) if barstate.islast line.new(bar_index - 50, hi, bar_index, hi, color = color.red, width = 2) line.new(bar_index - 50, lo, bar_index, lo, color = color.teal, width = 2) label.new(bar_index, hi, "50-bar high " + str.tostring(hi, format.mintick), style = label.style_label_down, color = color.red, textcolor = color.white) label.new(bar_index, lo, "50-bar low " + str.tostring(lo, format.mintick), style = label.style_label_up, color = color.teal, textcolor = color.white) ``` `bar_index` counts bars from 0, so `bar_index - 50` is fifty bars back. ## Keeping one object up to date To keep a single object moving rather than creating a new one every bar, store its id in a `var` and update it: ```pine //@version=6 indicator("One moving label", overlay = true) var label tag = label.new(na, na, "") label.set_xy(tag, bar_index, close) label.set_text(tag, str.tostring(close, format.mintick)) ``` To remove objects, call `label.delete(id)`, `line.delete(id)` and so on. Only objects that still exist at the end of the run are drawn. ## Boxes ```pine //@version=6 indicator("Range box", overlay = true) len = input.int(30, "Bars", minval = 5) if barstate.islast top = ta.highest(high, len) bottom = ta.lowest(low, len) box.new(bar_index - len + 1, top, bar_index, bottom, border_color = color.new(#8b7cff, 0), bgcolor = color.new(#8b7cff, 85)) ``` ## Tables A table is a grid pinned to a corner of the chart or pane: good for a dashboard of current values. ```pine //@version=6 indicator("Dashboard", overlay = true) r = ta.rsi(close, 14) a = ta.atr(14) var table t = table.new(position.top_right, 2, 3, bgcolor = color.new(#100e18, 0), border_width = 1, border_color = color.new(#3a3352, 0)) if barstate.islast table.cell(t, 0, 0, "Close", text_color = color.gray) table.cell(t, 1, 0, str.tostring(close, format.mintick), text_color = color.white) table.cell(t, 0, 1, "RSI 14", text_color = color.gray) table.cell(t, 1, 1, str.tostring(r, "#.0"), text_color = r > 70 ? color.red : r < 30 ? color.teal : color.white) table.cell(t, 0, 2, "ATR 14", text_color = color.gray) table.cell(t, 1, 2, str.tostring(a, format.mintick), text_color = color.white) ``` Cells are addressed `(column, row)`, both from 0. ## Polylines and linefills `polyline.new(points)` draws a path through an array of `chart.point`s, optionally curved or closed and filled. `linefill.new(line1, line2, color)` shades between two lines. Both are supported. ## Coordinates - By default the x coordinate is a **bar index**. Pass `xloc = xloc.bar_time` to use a time in milliseconds instead, for example `time` or a value from `timestamp(...)`. - In a pane script, drawings sit in that pane. Add `force_overlay = true` to put one on the price chart. - Drawings count toward the chart's autoscale, so a label far above price widens the scale to show it. > [!NOTE] > Script drawings are not chart drawings. They are not added to your object tree or saved layouts; they come back each time the script runs. Some label shapes and table layouts are close to TradingView's but not pixel-identical. --- # Multiple timeframes > Read another timeframe with request.security. Which timeframes the feed serves directly, which are built from others, and what is refused. `request.security` evaluates an expression on another timeframe and brings the result back to your chart. The classic use is a higher-timeframe trend filter on a lower-timeframe chart. ```pine //@version=6 indicator("1h trend on any chart", overlay = true) tf = input.timeframe("60", "Trend timeframe") htfEma = request.security(syminfo.tickerid, tf, ta.ema(close, 50)) plot(htfEma, "HTF EMA 50", color = color.orange, linewidth = 2) bgcolor(close > htfEma ? color.new(color.teal, 92) : color.new(color.red, 92)) ``` This example has no Run button: other timeframes are fetched from the live feed, which the docs' generated series cannot provide. **Open the terminal** to try it. ## Timeframes the feed serves These fourteen come straight from the feed, with the string Pine uses for each: | Timeframe | Pine string | Timeframe | Pine string | | --- | --- | --- | --- | | 5 seconds | `"5S"` | 5 minutes | `"5"` | | 10 seconds | `"10S"` | 10 minutes | `"10"` | | 15 seconds | `"15S"` | 15 minutes | `"15"` | | 30 seconds | `"30S"` | 30 minutes | `"30"` | | 1 minute | `"1"` | 1 hour | `"60"` (or `"1H"`) | | 2 minutes | `"2"` | 4 hours | `"240"` (or `"4H"`) | | 3 minutes | `"3"` | 1 day | `"D"` (or `"1D"`) | ## Other timeframes - **Higher timeframes that are not in the list** (for example `"W"`, `"45"` or `"120"`) are **built by combining** smaller bars, the same way PineTS does for any provider. They work, with one limit: a weekly bar needs many daily bars, and history is finite, so the earliest values can be `na`. The editor says when this happens. - **Anything under 5 seconds** is refused with a clear error. The feed has nothing smaller. ## Lower timeframes `request.security_lower_tf` returns an **array** of the lower-timeframe values inside each chart bar, for example the 1-minute closes inside a 1-hour bar. ## Rules that keep results honest - `request.security` uses the chart's own symbol through `syminfo.tickerid`. Asking for a modified ticker (Heikin Ashi, Renko and similar) fails explicitly instead of quietly serving ordinary candles. - Data a candle feed does not carry (`request.financial`, `request.earnings`, `request.dividends`, `request.economic`, `request.footprint`, and similar) returns `na` with a warning in the console. - Fetches for other timeframes respect the chart's date range and are limited per run, so a script cannot pull unlimited history. > [!WARNING] > On a live higher-timeframe bar, the value changes until that bar closes. If you want only confirmed values, request the previous bar: `request.security(syminfo.tickerid, tf, close[1], lookahead = barmerge.lookahead_on)` is the standard non-repainting form. --- # Strategies > Turn signals into simulated trades with strategy(), read the backtest panel, and understand what each metric does and does not tell you. An indicator draws. A **strategy** also places simulated orders, and Tradequix shows the resulting backtest: trades on the chart and a results panel with profit, drawdown and win rate. Declare `strategy(...)` instead of `indicator(...)`, then use `strategy.entry`, `strategy.close` and `strategy.exit`. ```pine //@version=6 strategy("EMA cross with stops", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10) fast = ta.ema(close, 12) slow = ta.ema(close, 26) atr = ta.atr(14) plot(fast, "Fast", color = color.teal) plot(slow, "Slow", color = color.red) if ta.crossover(fast, slow) strategy.entry("Long", strategy.long) if ta.crossunder(fast, slow) strategy.entry("Short", strategy.short) strategy.exit("Long exit", "Long", stop = close - 2 * atr, limit = close + 3 * atr) strategy.exit("Short exit", "Short", stop = close + 2 * atr, limit = close - 3 * atr) ``` ## Orders | Call | Does | | --- | --- | | `strategy.entry(id, direction)` | Opens or adds to a position; an opposite entry reverses it | | `strategy.close(id)` | Closes the position opened by entry `id` at market | | `strategy.close_all()` | Closes everything | | `strategy.exit(id, from_entry, stop, limit)` | Attaches a stop loss and/or take profit to an entry | | `strategy.order(...)` | A raw order, without entry's reversal logic | Orders fill on the **next** bar's open by default, which is how a real order placed at the close would behave. ## Settings that change results Arguments to `strategy()` that matter most: `initial_capital`, `default_qty_type` and `default_qty_value` (position size), `pyramiding` (how many entries may stack), `commission_type` / `commission_value`, and `slippage`. Leave commission at zero and a scalping strategy will look far better than it is. ## Reading the results panel | Metric | Meaning | | --- | --- | | Net profit | The result of closed trades | | Return | Net profit as a percentage of initial capital | | Max drawdown | The largest fall from a peak in equity, in money and percent | | Trades | How many trades closed | | Win rate | The share of closed trades that made money | | Gross +/− | Total won and total lost, separately | | Sharpe / Sortino | Risk-adjusted return, computed from monthly returns | Each trade's entry and exit is also drawn on the chart, so you can see where the strategy acted. > [!NOTE] > Sharpe and Sortino show **0** until there is enough monthly history to compute them. On a 5-second or 1-minute chart that can mean never. Read 0 as "not enough data", not "no edge". ## Before you trust a backtest - Run it on more than one pair and more than one timeframe. - Add commission and slippage that match how you would actually trade. - Check it does not use future data. A strategy that reads `close` and enters on the same bar's close, or uses `request.security` with lookahead on the current bar, can look perfect and never work live. - History on a short timeframe is short. A great result over 300 bars of 5-second data is a few minutes of market. --- # Alerts in scripts > What alert() and alertcondition() do on Tradequix today, and how they differ from the server price alerts that fire with the tab closed. There are two different things called alerts on Tradequix. Knowing which is which saves confusion. | | Script alerts | Price alerts | | --- | --- | --- | | Created by | `alert()` / `alertcondition()` in Pine | The alert button on the chart | | Evaluated | Where the script runs, while the chart is open | On the server, all the time | | You see them | In the Pine editor's console | As a notification and an email | | Fire with the tab closed | No | Yes | ## Script alerts `alert(message)` emits an event when it is called. `alertcondition(condition, title, message)` declares a condition that can be alerted on. Both run and are captured; the events appear in the **console** of the Pine editor, so you can see exactly when your logic would have fired. ```pine //@version=6 indicator("Breakout alert", overlay = true) hi = ta.highest(high, 20)[1] plot(hi, "20-bar high", color = color.orange, style = plot.style_stepline) breakout = ta.crossover(close, hi) plotshape(breakout, "Breakout", style = shape.arrowup, location = location.belowbar, color = color.teal, size = size.small) alertcondition(breakout, "Breakout", "Close broke the 20-bar high") if breakout alert("Breakout at " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close) ``` Use them to check your signal logic while building a script. > [!WARNING] > Script alerts are not yet a background service. They do not notify you when the chart is closed, and they are not sent by email or push. For that, use a price alert. ## Price alerts Price alerts are set from the chart's alert button on a level: crossing, greater than, less than, entering or leaving a range, and more. They are checked by the server on every bar, so they fire whether or not your chart is open, and reach you as an in-app notification and an email. Conditions based on an indicator's value are not available yet. --- # Repainting > Why a signal can look perfect on history and never happen live, the four usual causes, and the patterns that prevent each. A script **repaints** when what it shows on past bars differs from what it showed while those bars were live. A repainting strategy backtests beautifully and then loses money, because the signals it was tested on never existed in real time. ## The four usual causes | Cause | What happens | Fix | | --- | --- | --- | | Acting on the live bar | A condition is true mid-bar, then false at the close, and the marker disappears | Require `barstate.isconfirmed` | | Higher timeframe with lookahead | `request.security(..., lookahead_on)` on the current value reads the *future* close of the higher-timeframe bar on history | Use the `[1]` pattern below | | Pivots and "future" bars | `ta.pivothigh(5, 5)` confirms five bars late; plotting it back with `offset = -5` hides that delay | Act on it when it is confirmed, not where it is drawn | | `varip` and per-tick logic | Values that change within a live bar cannot be reproduced on history | Use `var` unless you truly need per-tick state | ## The non-repainting higher-timeframe pattern Request the **previous** completed bar of the higher timeframe, with lookahead on, so that history and live behave the same: ```pine //@version=6 indicator("HTF close without repainting", overlay = true) htfClose = request.security(syminfo.tickerid, "60", close[1], lookahead = barmerge.lookahead_on) plot(htfClose, "1h close (confirmed)", color = color.orange, style = plot.style_stepline) ``` ## Confirmed signals ```pine //@version=6 indicator("Signals that stay", overlay = true) f = ta.ema(close, 9) s = ta.ema(close, 21) longSignal = ta.crossover(f, s) and barstate.isconfirmed plotshape(longSignal, "Long", style = shape.triangleup, location = location.belowbar, color = color.teal) ``` ## Checking a script Watch it live for a while next to its history: if markers appear and vanish on the forming bar, it acts on unconfirmed data. The [checker](/docs/check) also warns about `lookahead_on` and `varip`. --- # The Pine editor > Shortcuts, the console, editor settings, and what is still coming. Everything about the panel where you write scripts. Open the editor from **Pine Script** in the terminal's side rail. It sits over the live chart, so every change runs on real candles. ## Shortcuts | Keys | Does | | --- | --- | | Ctrl Enter (Cmd Enter) | **Add to chart**: run the script on the chart | | Ctrl S (Cmd S) | **Save** to your account | | Tab | Insert 4 spaces; with several lines selected, indent them | | Shift Tab | Outdent the selected lines | | Enter | New line, keeping the current indentation | | Esc, then Tab | Leave the text area (Tab alone indents) | | Esc | Close an open menu | ## The console The strip under the code reports the last run: - **Syntax error**, **Script error**, **Timed out** or **Engine error**, with the line and column, a **Go to line** button, and an **Explain** link that opens the [error index](/docs/errors) at that message. - Warnings, each shown once. - Alerts your script fired, as title and message. - "Compiled successfully" or "added to the chart" when all went well. Save and load problems appear on their own yellow line, so a storage failure is never mistaken for a bug in your code. ## Editor settings Two settings work today: **Word wrap** and **Line numbers**. The others in the settings panel are shown but not yet available, each with its reason: suggestions as you type (needs a language server), minimap and line-length guide (planned), import hints (libraries are not supported), and diff decorations (needs a history of editor saves). ## The Script menu Save, Rename, **Version history** (for a saved script, it opens its published versions on your dashboard), **New indicator**, the list of your saved scripts, and **Pine docs**, which opens these docs in a new tab. ## Coming soon Shown in the editor with a preview of what they will do: Make a copy, a New strategy template, a New library template, Pine logs (a pane for `log.info` and friends), and a Profiler. --- # Indicator settings > The gear in an indicator's legend: change inputs, restyle plots, hide drawings, and choose which timeframes it shows on. Every indicator on the chart has a settings dialog, opened from the gear in its legend. It has three tabs. ## Inputs One field per `input.*` call in the script, grouped under the `group` headings the script declares. Changes re-run the script immediately and are saved with the chart. See [Inputs](/docs/inputs) for how saved values survive edits to the script. ## Style - **Plots:** a colour per plot, and each plot as a line or a histogram. - **Graphic objects:** turn the script's boxes, labels, lines and tables on or off without touching the code. - **Output values:** the precision values are shown with, whether labels appear on the price scale, and whether values appear in the legend's status line. - **Input values:** whether the script's input values appear in the status line. ## Visibility Choose the timeframes the indicator appears on, by group: seconds (5, 10, 15, 30), minutes (1 to 30), hours (1h, 4h) and days (1D). Hidden on a timeframe means not drawn there; the indicator stays on the chart for when you switch back. > [!TIP] > Style and visibility live with the chart, not the script. Two charts can show the same script in different colours. --- # Coming from TradingView > Bring an existing TradingView script to Tradequix: what runs unchanged, what to edit, and a checklist. Start with the checker. Most Pine v6 scripts run on Tradequix unchanged. The differences come from three places: the data (an OTC candle feed), the engine (PineTS, which implements most but not all of Pine), and the platform (no libraries). ## The fastest path 1. Paste the script into **[Will it run here?](/docs/check)**. It lists every line that needs attention. 2. Fix the red items, read the yellow ones. 3. Open it in the editor and press **Add to chart**. ## What to change | On TradingView | On Tradequix | | --- | --- | | `import user/lib/1` | Not available. Paste the library's functions into your script. | | `request.financial`, `earnings`, `dividends`, `economic` | Return `na`. Remove them or treat them as optional. | | `ticker.heikinashi(...)` and other modified tickers | Refused. Compute Heikin Ashi in the script ([cookbook](/docs/cookbook)). | | Volume as traded size | Volume is a tick count. VWAP-style values are approximate. | | Tick or sub-5-second timeframes | Not available. 5 seconds is the smallest. | | `"W"`, `"M"` timeframes | Built from daily bars; history may be short. | | `log.info` and the Pine Logs pane | The calls run, but logs are not shown yet. | | Session times and exchange hours | The feed is 24x7 on UTC. See [Time and sessions](/docs/time-and-sessions). | ## From older Pine versions v5 scripts usually run. Older ones need the usual conversions: `study()` becomes `indicator()`, `security()` becomes `request.security()`, `rsi()` becomes `ta.rsi()`, and so on. TradingView's editor can convert a script to v6 for you before you bring it over. ## Things that are better here - Closed-source scripts run on the server, so selling access never ships your code. - Every example in these docs runs in the page. - The [error index](/docs/errors) explains every console message. --- # The data > What the live OTC feed gives a script, what it cannot, and how the editor tells you when a script asks for something missing. Pine on Tradequix runs on a live **OTC candle feed**. Most of Pine's language works exactly as documented; the differences come from what a candle feed can and cannot supply. ## What every bar carries | Series | On this feed | | --- | --- | | `open`, `high`, `low`, `close` | The bar's prices, live | | `hl2`, `hlc3`, `ohlc4` | Derived from the above | | `volume` | A **tick count**: how many price updates the bar received | | `time` | When the bar opened, in milliseconds | | `bar_index` | 0 on the oldest loaded bar | | `syminfo.tickerid`, `syminfo.mintick` | The chart's symbol and its price step | | `timeframe.period` | The chart's timeframe as a Pine string | ## Volume is a tick count The feed reports how many ticks each bar had, not how much was traded. That is a fair measure of activity, so comparing volume between bars is meaningful: `ta.obv`, `ta.mfi`, volume spikes and plotting volume itself all work as you would expect. Indicators that treat volume as traded size, such as VWAP and accumulation/distribution, still compute, but their values mean something narrower than their names. The editor shows a warning whenever a script uses volume. ## Timeframes Fourteen timeframes come from the feed: 5, 10, 15 and 30 seconds; 1, 2, 3, 5, 10, 15 and 30 minutes; 1 and 4 hours; and 1 day. Others are built from these. See [Multiple timeframes](/docs/timeframes). ## What is not available A candle feed has no company data or order book. Scripts that ask for these still run; the request returns `na` and the console says why: - `request.financial`, `request.earnings`, `request.dividends`, `request.splits`, `request.economic` - `request.footprint` (needs order-flow data) - Modified tickers: Heikin Ashi, Renko, Kagi, Line Break, Point and Figure. These fail with an explicit error rather than serving ordinary candles under another name. Compute Heikin Ashi yourself instead; see the [cookbook](/docs/cookbook). ## How much history a script sees A script runs on the bars loaded on the chart. Scroll back and more history loads; the script runs again over it. Long averages need warm-up: a 200-bar average is `na` for the first 199 bars it sees. > [!TIP] > The docs' **Run** buttons use a fixed generated series of 300 five-minute bars, not the live feed. Behaviour that depends on the feed (other timeframes, the live last bar) is best tried in the terminal with **Open in editor**. --- # Publish and sell > Share a script open source, protect its code, or sell access to it. Visibility, the edit window, the published chart and paid spaces. A saved script is private. Publishing puts it in the community catalogue with its own page, where people can add it to their charts, boost it, favourite it and discuss it. ## Choose a visibility | Visibility | Who can use it | Who can read the code | Where it runs | | --- | --- | --- | --- | | **Open source** | Everyone | Everyone | In each viewer's browser | | **Protected** | Everyone | Only you | On the Tradequix server | | **Invite-only** | People you grant access | Only you | On the Tradequix server | Protected and invite-only scripts run on the server, and only the computed values reach a subscriber's browser. The source is never sent to anyone but its author; the endpoints that serve source refuse it outright. ## The edit window For **15 minutes** after publishing you can still correct the title, description and tags, and replace the published chart. After that, the publication is fixed. To change the code, publish an update; each publication is a version. Public publications are rate limited: five per rolling day and fifteen per month. Updates do not count toward either. All limits are listed on [Limits](/docs/limits). ## The published chart A script page shows a chart of the script running, like a published idea: you choose the symbol, timeframe and inputs, and the server runs the script and captures the result. Viewers can pan, zoom and read the values. The capture is computed by the server, so a published chart cannot be faked. ## Invite-only access An invite-only script appears in the catalogue but is locked. You grant access by hand from your dashboard, or sell it through a paid space. Every grant, manual or paid, is the same kind of record, and revoking it removes access. ## Selling access with a space A **space** is your storefront: one subscription covers every script you put in it. Subscribers pay through Stripe and get access to the whole space for as long as they subscribe. Set up payouts in the [author studio](/studio). > [!NOTE] > Closed source is about who can *read* the code, not who can *run* it. A subscriber's chart shows the script working, values and all; they just never receive the source. --- # Catalogue and community > Finding scripts in the Indicators dialog, script pages, boosts and comments, asking for invite-only access, and talking to authors. ## The Indicators dialog Open **Indicators** in the terminal to add a script to the chart. Its sections: - **Favorites**, **My scripts**, **Invite-only** (scripts you have access to) and **Purchased**. - **Technicals**: the [built-in catalogue](/docs/built-ins), grouped as indicators, strategies, profiles and patterns. - **Editors' picks**, **Top**, **Trending** and **Marketplace** for community scripts. ## A script's page Every published script has a page at `/scripts/` with its description, the published chart, release notes and comments. From there: - **Open on chart** adds it to your terminal. - **Boost** recommends it (signed in), and the count feeds Top and Trending. - **Comments** for questions and feedback. - The menu has **Copy link**, **Discussion room** (a chat for the script, on public scripts), **Message the author**, and **Manage** if it is yours. ## Asking for invite-only access An invite-only script appears in the catalogue but is locked. Its page shows the author's instructions for getting access. If it is sold through a paid space, it says so and links there; otherwise **Request access** sends the author a request, and the button changes to "Request sent". The author approves or declines from their dashboard. --- # Your dashboard and earnings > Track reach, roll back versions, answer access requests and set up payouts for the scripts you publish. Your [dashboard](/dashboard) is where published scripts are managed. ## Overview and scripts The overview shows recent versions, comments and activity. **Scripts** lists everything you have published with its lifetime reach. ## One script Open a script to see boosts, comments, views and uses, then three tabs: - **Versions:** a timeline of every publication with a diff between versions, and **rollback** to an earlier one. - **Access:** for invite-only scripts, the request inbox and the people who have access, with how many grants are used. - **Settings:** title, the instructions people see when asking for access, publishing options, and **Unpublish**. ## Access The Access page gathers requests across all your scripts: **Approve** or **Decline** each, and **Remove access** from anyone at any time. A privately published invite-only script can have up to 5 people; publish it publicly to remove that cap. ## Activity The 30 most recent things that happened on your scripts. ## Earnings Sell access through a **space** in the [author studio](/studio): one subscription covers up to 50 of your scripts. Payments go through Stripe; connect your payout account under [Payouts](/studio/payouts). --- # Errors and debugging > Read the editor console, recognise the common errors and their real causes, and find out why a script runs but draws nothing. When a script fails, the editor's **console** says what went wrong and, when it can, which line. Warnings (a script that runs but with a caveat) appear there too, along with any `alert()` events. ## Kinds of error | Kind | Means | Usually | | --- | --- | --- | | Transpile | The code could not be understood | A typo, a missing bracket, wrong indentation | | Runtime | It ran and then failed on some bar | Dividing by `na`, an array index out of range, a bad argument | | Timeout | It did not finish in time | An unbounded loop | Every runnable example in these docs reports errors the same way. Try breaking one: ```pine //@version=6 indicator("Spot the mistake") len = 14 r = ta.rsi(close, len) plot(r, "RSI", color = color.purple) hline(50) ``` Change `ta.rsi` to `ta.rsii` and press **Run** to see a real error message. ## Common errors and their real causes **"Loop exceeded maximum iterations"** comes from a `while` or `for` loop that never ends. The engine stops it rather than hang the chart. **"This feed cannot serve the '…' timeframe."** A `request.security` asked for less than five seconds. See [Multiple timeframes](/docs/timeframes). **Indentation.** Blocks under `if`, `for` and functions are indented by four spaces (or one tab). A line indented by a different amount is a transpile error. **Saved setting no longer exists.** A warning, not an error: an input you had customised was removed from the script. See [Inputs](/docs/inputs). ## It runs, but draws nothing Work through these in order: 1. **Is the value ever not `na`?** Long lookbacks need history. Plot the raw series and look for a line. 2. **Is a `plotshape` series ever true?** Markers need `true` or a non-zero number. Plot the condition as a number (`plot(cond ? 1 : 0)`) to see. 3. **Is it on the right scale?** An oscillator with `overlay = true` draws its 0 to 100 values on a price chart where it is off screen. Remove `overlay`. 4. **Is the drawing only on the last bar?** `barstate.islast` objects appear at the right edge. Scroll there. 5. **Is the colour transparent?** `color.new(c, 100)` is invisible. ## Seeing values - Plot it. A temporary `plot(x, "debug")` shows every bar's value in the indicator's legend as you move the crosshair. Put it in a pane script so it gets its own scale. - A table on the last bar is a quick dashboard of current values; see [Drawings and tables](/docs/drawings). - A label with `str.tostring(x)` shows a value at a specific bar. - `alert("x = " + str.tostring(x))` writes to the console each time it runs. --- # Limits > Every limit a script, a chart and a publication runs into on Tradequix, with the exact numbers and what happens when you hit one. Limits exist so one script cannot freeze a chart or drain the feed for everyone. These are the real numbers. ## A script run | Limit | Value | When you hit it | | --- | --- | --- | | Run time | 8 seconds | The run stops: "Script did not finish within 8000ms" | | Loops | An iteration ceiling inside the engine | "Loop exceeded maximum iterations" | | `request.*` contexts | 40 per script | "The script executes too many request.*() function calls." | | History per `request.security` | 3,600 candles (20 pages of 180) | A warning; older values are na | | Fetches per run | 60 | "This script asked for too much history in one run." | | Each fetch | 15 seconds to answer | The request fails | | Array, matrix, table size | 100,000 elements | "The requested size exceeds the 100000 element limit." | | `calc_bars_count` | Capped at 100,000 | Silently capped | | Script source | 200,000 bytes | Cannot be saved | ## A chart | Limit | Value | | --- | --- | | Indicators on one chart | 50 | | Plot style overrides per indicator | 64 | | Indicator templates per account | 50, each holding up to 50 indicators | | Saved layouts | 30 | | Price alerts | 200, firing at most 60 times an hour | ## Publishing | Limit | Value | | --- | --- | | Public publications | 5 per day and 15 per month (updates do not count) | | Edit window after publishing | 15 minutes | | Description | 10,000 characters | | Release notes | 5,000 characters | | Access-request instructions | 1,000 characters | | Tags | 10 | | Comment | 4,000 characters | | Scripts in one paid space | 50 | | Access grants on a privately published invite-only script | 5 | | Published-chart captures | 10 per hour | --- # Coverage > Which parts of Pine Script v6 work on Tradequix, which are verified by our own tests, and which are not available. Tradequix runs Pine through **PineTS 0.11.1**. This page combines PineTS's own coverage notes with what Tradequix has tested itself. It is honest rather than complete: "works" here means tested on this platform, not that every argument of every function has been compared with TradingView. ## Status key | Mark | Means | | --- | --- | | **Verified** | Covered by Tradequix's own tests and rendered on a real chart | | **Supported** | Implemented by PineTS; used by scripts here, not exhaustively tested | | **Partial** | Works with known limits, listed alongside | | **Not available** | Fails or returns `na`, with an explicit message | ## Language | Feature | Status | Notes | | --- | --- | --- | | Bar-by-bar execution, series, `[]` history | Verified | | | `var`, `varip`, `na`, `nz` | Verified | | | `if`, `switch`, `for`, `for … in`, `while` | Supported | Infinite loops are stopped with an error | | User functions `f(x) => …` | Verified | Including multi-line bodies | | Tuples `[a, b] = f()` | Verified | | | Arrays, matrices, maps | Verified | Representative operations tested | | User-defined types, enums | Supported | | | Methods, objects | Partial | Upstream marks these as in progress | | `import` of libraries | Not available | Needs a library resolver this platform does not have | ## Namespaces | Namespace | Status | Notes | | --- | --- | --- | | `ta.*` | Verified | Seventy-plus functions; all 62 built-ins use them | | `math.*`, `str.*`, `color.*` | Verified | | | `input.*` | Verified | Every type becomes a settings field | | `plot*`, `hline`, `fill`, `bgcolor`, `barcolor` | Verified | All styles drawn natively | | `plotshape`, `plotchar`, `plotarrow` | Verified | Draw where the series is true or non-zero | | `plotcandle`, `plotbar` | Verified | | | `label`, `line`, `box`, `table`, `polyline`, `linefill` | Verified | Some shapes and table layouts are approximate | | `strategy.*` | Verified | Not every order variant tested | | `request.security`, `request.security_lower_tf` | Verified | See [Multiple timeframes](/docs/timeframes) | | `request.financial`, `earnings`, `dividends`, `economic`, `footprint` | Not available | Return `na` with a warning | | `alert`, `alertcondition` | Partial | Shown in the editor console; no background delivery | | `chart.left_visible_bar_time` and other viewport values | Partial | Not verified | | `syminfo.*`, `timeframe.*`, `barstate.*` | Supported | Symbol, timeframe and precision come from the chart | ## Known differences from TradingView - **Data.** Volume is a tick count, and the feed has no fundamentals or order flow. See [The data](/docs/data). - **Rendering.** Values are exact; some marker and label shapes, proportional arrow sizes, curved lines and table layouts are close but not pixel-identical. - **Realtime.** The last bar recalculates as it forms; exact rollback behaviour of `varip` on every tick is not verified. - **Modified tickers.** Heikin Ashi, Renko and similar fail explicitly instead of serving plain candles. For the status of each individual function, see the [function reference](/docs/reference), which lists every name the engine implements. For PineTS's own coverage tables, see the [PineTS language coverage](https://docs.luxalgo.com/developers/pinets/lang-coverage) and [API coverage](https://docs.luxalgo.com/developers/pinets/api-coverage) pages. --- # Built-in catalogue > All 62 scripts that ship with Tradequix, by group. Each opens its own page, with the full open source to read or copy. Tradequix ships 62 ready-made scripts. Add any of them from the **Indicators** dialog in the terminal, or open its page below to read the source. Every one is written in ordinary Pine v6 and is tested to run and draw, so they double as examples: when you want to know how something is done, find the built-in that does it and read it. > [!TIP] > In the terminal, the **{}** button on an indicator opens its code. Copy it into a new script and change it; that is often the fastest way to start. ## Indicators | Script | What it shows | | --- | --- | | [Simple Moving Average](/scripts/sma) | The unweighted mean of the last N closes. The baseline every other average is a reaction to. | | [Exponential Moving Average](/scripts/ema) | Weights recent bars more heavily, so it turns sooner than an SMA of the same length and whipsaws more. | | [Weighted Moving Average](/scripts/wma) | Linear weighting: the oldest bar in the window counts once, the newest counts N times. | | [Smoothed Moving Average](/scripts/smma) | An EMA with a 1/N smoothing factor , slower than either, and the average underneath Wilder's RSI and ATR. | | [Double Exponential Moving Average](/scripts/dema) | 2*EMA minus the EMA of that EMA, which cancels most of the lag an EMA carries at the cost of overshoot. | | [Triple Exponential Moving Average](/scripts/tema) | The same lag cancellation applied a third time. Faster than DEMA and correspondingly noisier. | | [Hull Moving Average](/scripts/hma) | Weighted averages combined so the result is both fast and smooth , the usual answer to 'lag or noise, pick one'. | | [Volume Weighted Moving Average](/scripts/vwma) | An SMA weighted by volume, so bars nobody traded move it less than bars everybody did. | | [Arnaud Legoux Moving Average](/scripts/alma) | A Gaussian window whose peak can be shifted toward the recent end, trading smoothness against responsiveness explicitly. | | [Moving Average Ribbon](/scripts/ma-ribbon) | Six averages at increasing lengths. Spacing shows trend strength; crossing order shows it turning. | | [Moving Average Cross](/scripts/ma-cross) | A fast and a slow average with their crossings marked , the oldest trend-following signal there is. | | [Relative Strength Index](/scripts/rsi) | Average gain against average loss over N bars, scaled 0-100. Above 70 and below 30 are the conventional extremes. | | [MACD](/scripts/macd) | The gap between a fast and a slow EMA, its own average, and the difference between them as a histogram. | | [Stochastic](/scripts/stochastic) | Where the close sits inside the recent high-low range, smoothed. %K crossing %D is the usual trigger. | | [Stochastic RSI](/scripts/stochastic-rsi) | A stochastic computed over RSI rather than price. Far more sensitive than either, and reaches its extremes often. | | [Commodity Channel Index](/scripts/cci) | Distance of the typical price from its average, in units of mean deviation. Unbounded, unlike RSI. | | [Williams %R](/scripts/williams-r) | The stochastic inverted and scaled -100 to 0: where the close sits in the range, measured from the top. | | [Awesome Oscillator](/scripts/awesome-oscillator) | A 5-period against a 34-period average of the bar midpoint. Colour is the direction of the change, not the sign. | | [Momentum](/scripts/momentum) | Today's close minus the close N bars ago. The simplest possible rate-of-change, and still a useful one. | | [Rate of Change](/scripts/roc) | Momentum as a percentage, which makes it comparable across instruments at different price levels. | | [Money Flow Index](/scripts/mfi) | An RSI weighted by volume, so a move nobody traded moves it less than a move everybody did. | | [Chande Momentum Oscillator](/scripts/cmo) | Gains minus losses over their sum, scaled -100 to 100. Unsmoothed, so it is faster and noisier than RSI. | | [True Strength Index](/scripts/tsi) | Double-smoothed momentum over double-smoothed absolute momentum. Much slower than RSI and much cleaner. | | [TRIX](/scripts/trix) | The rate of change of a triple-smoothed EMA. The smoothing strips most noise, so a zero cross means something. | | [Ultimate Oscillator](/scripts/ultimate-oscillator) | Buying pressure measured over three timeframes at once and weighted, which blunts the false divergences a single-period oscillator shows. | | [Bollinger Bands](/scripts/bollinger-bands) | A moving average with bands at N standard deviations. The bands widen as the market gets noisier, so distance from them is relative rather than absolute. | | [Bollinger BandWidth](/scripts/bollinger-bandwidth) | The spread between the bands as a fraction of the basis. Lows mark the squeezes that often precede a move. | | [Bollinger %B](/scripts/bollinger-percent-b) | Where price sits between the bands: 0 is the lower band, 1 the upper. Outside that range price has left them. | | [Keltner Channels](/scripts/keltner-channels) | Bands set by ATR rather than standard deviation, so they track the range a market actually travels instead of the dispersion of its closes. | | [Donchian Channels](/scripts/donchian-channels) | The highest high and lowest low of the last N bars. No smoothing at all, which is why breakout systems are built on it. | | [Average True Range](/scripts/atr) | The average bar range, counting gaps. A volatility unit rather than a signal: most stop and sizing rules are denominated in it. | | [Envelope](/scripts/envelope) | Bands at a fixed percentage above and below a moving average. Unlike Bollinger or Keltner, the width never adapts. | | [Historical Volatility](/scripts/historical-volatility) | The annualised standard deviation of log returns , volatility as an options desk means it, not as a band width. | | [Chandelier Exit](/scripts/chandelier-exit) | A trailing stop hung N ATRs below the running high, and above the running low. Ratchets one way and never loosens. | | [Average Directional Index](/scripts/adx) | Trend strength regardless of direction, with the two directional lines that produce it. Above 25 is the conventional threshold for 'trending'. | | [Supertrend](/scripts/supertrend) | An ATR band that flips sides when price closes through it. Binary by construction: there is always a direction, and it is always a stop level. | | [Parabolic SAR](/scripts/parabolic-sar) | A stop that accelerates toward price the longer a trend runs, and flips when touched. Excellent in a trend, punishing in a range. | | [Ichimoku Cloud](/scripts/ichimoku-cloud) | Five lines giving support, resistance, momentum and a projected band in one view. The cloud is drawn forward, so it is a forecast rather than a reading. | | [Aroon](/scripts/aroon) | How recently the highest high and lowest low occurred, as a percentage of the lookback. Measures how fresh a trend is rather than how large. | | [Vortex Indicator](/scripts/vortex) | Upward and downward movement measured against true range. The crossing of the two lines is the signal, not their level. | | [Linear Regression Channel](/scripts/linear-regression) | The least-squares line through the last N closes, with bands at a multiple of the residual deviation. | | [Choppiness Index](/scripts/choppiness-index) | How much ground price covered against how far it actually went. High means ranging, low means trending , it says nothing about direction. | | [Detrended Price Oscillator](/scripts/dpo) | Price minus a displaced moving average, which removes the trend to leave the cycle. Shifted back, so it is not a real-time signal. | | [Volume](/scripts/volume) | Activity per bar, coloured by whether the bar closed up or down, with its own moving average. | | [On Balance Volume](/scripts/obv) | A running total that adds the bar's volume on an up close and subtracts it on a down one. The level is arbitrary; the slope is the reading. | | [Accumulation/Distribution](/scripts/accumulation-distribution) | Like OBV, but weights each bar by where it closed within its range rather than counting the whole bar one way. | | [Chaikin Money Flow](/scripts/chaikin-money-flow) | Accumulation/Distribution normalised by volume over N bars, so it oscillates around zero instead of drifting. | | [Price Volume Trend](/scripts/price-volume-trend) | A cumulative total weighted by the size of each percentage move, not just its sign , so a large move counts for more than a small one. | | [Volume Weighted Average Price](/scripts/vwap) | The average price every unit of volume actually paid. The reference most execution is measured against. | | [Ease of Movement](/scripts/ease-of-movement) | How far price moved per unit of volume. High readings mean price travelled on little participation, which rarely holds. | | [Elder's Force Index](/scripts/force-index) | The size of a move multiplied by the volume behind it, smoothed. Combines direction, extent and participation in one number. | | [Net Volume](/scripts/net-volume) | Volume signed by the bar's direction, bar by bar rather than cumulatively. The per-bar form of what OBV totals. | ## Strategies | Script | What it shows | | --- | --- | | [Moving Average Cross Strategy](/scripts/ma-cross-strategy) | Long when the fast average crosses above the slow one, flat or short when it crosses back. A demonstration of the mechanism, not a system to trade. | | [RSI Mean Reversion Strategy](/scripts/rsi-reversion-strategy) | Buys oversold readings and exits on the return to the midline. Mean reversion works until it does not; this has no stop, which is the lesson. | | [Supertrend Strategy](/scripts/supertrend-strategy) | Follows the Supertrend flip in both directions. Trend following: a low hit rate carried by the size of the winners, which a short backtest will not show. | | [Donchian Breakout Strategy](/scripts/donchian-breakout-strategy) | Enters on a new N-bar extreme and exits on the opposite shorter one , the classic turtle structure, stripped to its two rules. | ## Profiles | Script | What it shows | | --- | --- | | [Pivot Points Standard](/scripts/pivot-points-standard) | The classic floor-trader levels computed from the previous session's range: a central pivot with three supports and three resistances. | | [Price Range Profile](/scripts/price-range-profile) | Where the current price sits inside the session range, as a percentage, with the range boundaries drawn. | | [Relative Volume](/scripts/relative-volume) | This bar's volume against the recent average. Above 1 means more participation than usual, which is what makes a move worth trusting. | ## Patterns | Script | What it shows | | --- | --- | | [Pivot Points High Low](/scripts/pivot-points-high-low) | Marks bars whose high (or low) exceeds N bars either side. Confirmed only: a pivot appears N bars after it happened. | | [Williams Fractal](/scripts/williams-fractal) | The five-bar reversal shape: a high with two lower highs on each side. The same confirmation lag as any pivot. | | [ZigZag](/scripts/zigzag) | Connects confirmed swing highs and lows, hiding moves below a threshold. A description of structure, never a signal , the last leg repaints until it is confirmed. | --- # Cookbook > Complete, runnable recipes to copy and adapt: Heikin Ashi, a squeeze, a trailing stop, divergence, a ribbon, volume spikes and a breakout strategy. Each recipe is a complete script. Run it here, then **Open in editor** to try it on the live feed and change it. ## Heikin Ashi, computed yourself The feed does not serve Heikin Ashi candles, but they are four lines of Pine. This draws them in a pane. ```pine //@version=6 indicator("Heikin Ashi") haClose = (open + high + low + close) / 4 var float haOpen = na haOpen := na(haOpen[1]) ? (open + close) / 2 : (haOpen[1] + haClose[1]) / 2 haHigh = math.max(high, math.max(haOpen, haClose)) haLow = math.min(low, math.min(haOpen, haClose)) plotcandle(haOpen, haHigh, haLow, haClose, "HA", color = haClose >= haOpen ? color.teal : color.red) ``` ## Squeeze: Bollinger inside Keltner When the Bollinger Bands contract inside the Keltner Channel, volatility is low and a move often follows. ```pine //@version=6 indicator("Squeeze") [bbMid, bbUp, bbLo] = ta.bb(close, 20, 2) [kcMid, kcUp, kcLo] = ta.kc(close, 20, 1.5) squeezed = bbUp < kcUp and bbLo > kcLo mom = ta.linreg(close - ta.sma(close, 20), 20, 0) plot(mom, "Momentum", style = plot.style_columns, color = mom >= 0 ? color.new(color.teal, 30) : color.new(color.red, 30)) plotshape(squeezed, "Squeeze on", style = shape.circle, location = location.bottom, color = color.orange, size = size.tiny) ``` ## ATR trailing stop A stop that follows price up and never moves down (for longs), flipping when price crosses it. ```pine //@version=6 indicator("ATR trailing stop", overlay = true) mult = input.float(3.0, "ATR multiple", minval = 0.5, step = 0.5) a = ta.atr(14) * mult var float stop = na var int dir = 1 if dir == 1 stop := math.max(nz(stop, close - a), close - a) if close < stop dir := -1 stop := close + a else stop := math.min(nz(stop, close + a), close + a) if close > stop dir := 1 stop := close - a plot(stop, "Stop", color = dir == 1 ? color.teal : color.red, style = plot.style_linebr, linewidth = 2) ``` ## RSI divergence Bearish divergence: price makes a higher pivot high while RSI makes a lower one. Pivots are confirmed `5` bars later, so markers are shifted back with `offset`. ```pine //@version=6 indicator("RSI divergence") r = ta.rsi(close, 14) lb = 5 ph = ta.pivothigh(r, lb, lb) isPh = not na(ph) prevR = ta.valuewhen(isPh, r[lb], 1) prevH = ta.valuewhen(isPh, high[lb], 1) bear = isPh and r[lb] < prevR and high[lb] > prevH plot(r, "RSI", color = color.purple) hline(70, color = color.gray) hline(30, color = color.gray) plotshape(bear, "Bearish divergence", style = shape.triangledown, location = location.top, color = color.red, offset = -lb, size = size.small) ``` ## Moving average ribbon ```pine //@version=6 indicator("EMA ribbon", overlay = true) plot(ta.ema(close, 10), "10", color = color.new(#8b7cff, 0)) plot(ta.ema(close, 20), "20", color = color.new(#a48cf0, 0)) plot(ta.ema(close, 30), "30", color = color.new(#c59bff, 0)) plot(ta.ema(close, 40), "40", color = color.new(#e3a58f, 0)) plot(ta.ema(close, 50), "50", color = color.new(#ffb547, 0)) ``` ## Volume spikes Volume is a tick count here, which makes spikes a good activity signal. ```pine //@version=6 indicator("Volume spikes") avg = ta.sma(volume, 20) spike = volume > avg * 1.8 plot(volume, "Ticks", style = plot.style_columns, color = spike ? color.orange : color.new(color.gray, 60)) plot(avg, "Average", color = color.new(#8b7cff, 0)) ``` ## Donchian breakout strategy ```pine //@version=6 strategy("Donchian breakout", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10) len = input.int(20, "Channel", minval = 5) upper = ta.highest(high, len)[1] lower = ta.lowest(low, len)[1] plot(upper, "Upper", color = color.teal) plot(lower, "Lower", color = color.red) if close > upper strategy.entry("Long", strategy.long) if close < lower strategy.entry("Short", strategy.short) ``` Using `[1]` compares with the channel as it stood *before* this bar, so a bar cannot break out of a channel that already includes it. --- # Write Pine with AI > Give an AI assistant these docs and Tradequix's rules, so the scripts it writes actually run here. Includes a ready prompt and a review checklist. AI assistants write Pine well, but they write it for TradingView. They assume fundamentals exist, that volume is traded size, and that any timeframe works. Give them these docs first and those mistakes mostly disappear. ## Three ways to give an assistant the docs 1. **One page.** Every page has **Copy page**, **View as Markdown**, **Open in Claude** and **Open in ChatGPT**. The last two start a chat that is told to read that page. 2. **Everything.** [llms-full.txt](/docs/llms-full.txt) is the whole documentation as one plain-text file. The **Copy all docs for AI** button on the [docs home](/docs) puts it on your clipboard; paste it at the start of a chat. 3. **An index.** [llms.txt](/docs/llms.txt) lists every page with a one-line summary and a link to its markdown. Tools that understand the llms.txt convention (editors, coding agents) can read it and fetch only what they need. Any page's markdown is also at its address plus `.md`, for example [/docs/plotting.md](/docs/plotting.md). The whole [function reference](/docs/reference.md) is one markdown file too. ## Install it in your coding assistant If you write Pine in an editor with an AI assistant, install the rules once and it follows them every time: - **Claude Code.** Save [SKILL.md](/docs/skills/tradequix-pine/SKILL.md) as `.claude/skills/tradequix-pine/SKILL.md` in your project (or in `~/.claude/skills/` for every project). Claude uses it whenever you ask for a Tradequix indicator or paste a console error. - **Cursor.** Save [tradequix-pine.mdc](/docs/tradequix-pine.mdc) as `.cursor/rules/tradequix-pine.mdc`. It applies to `.pine` files. Both carry the same rules as the prompt below, plus links to the reference and the error index so the assistant can check before it writes. ## A prompt that works Paste this, then describe your indicator: ```text You are writing Pine Script v6 for Tradequix, which runs Pine on PineTS over a live OTC candle feed. Follow these rules: - Start with //@version=6 and indicator(...) or strategy(...). - Use only price data: open, high, low, close, volume, time. Volume is a tick count, not traded size. - Do not use request.financial, request.earnings, request.dividends, request.economic or request.footprint; they return na here. - request.security works on these timeframes: 5S 10S 15S 30S 1 2 3 5 10 15 30 60 240 D. Others are aggregated; nothing below 5 seconds. - plotshape and plotchar only draw where the series is true or a non-zero number. - Do not use import; libraries are not available. - Prefer barstate.isconfirmed for signals that must not repaint. Write the complete script, then list any assumption you made. ``` ## Review what comes back Before you trust an AI-written script, check: - It runs. Paste it into the editor and press **Add to chart**; read the console. - It draws where you expect. Markers that never appear usually mean a `plotshape` series that is never true. - It does not look ahead. No `close[-1]`, no `lookahead_on` on the current bar's value. - Strategy settings are realistic: commission, slippage, position size. - Inputs have sensible `minval` and defaults. > [!TIP] > When the script fails, paste the console message back to the assistant along with the page it relates to (for example [Errors and debugging](/docs/debugging)). It fixes most errors in one round. --- # FAQ > Short answers to the questions people ask most about writing and running Pine on Tradequix. ## Running scripts ### Will my TradingView script run here? Most v6 scripts do. Paste it into [Will it run here?](/docs/check) for a line-by-line answer, then see [Coming from TradingView](/docs/coming-from-tradingview). ### Why does my script draw nothing? Usually one of: values still `na` during warm-up, a `plotshape` series that is never true, an oscillator drawn with `overlay = true` off screen, or drawings only on the last bar at the far right. The checklist is in [Errors and debugging](/docs/debugging). ### Why did the run stop after a few seconds? A run has 8 seconds. An unbounded loop or very heavy work exceeds it. See [Limits](/docs/limits). ### Can a script use more than one symbol? `request.security` reads other **timeframes** of the chart's symbol. Use `syminfo.tickerid` as its first argument. ## Data ### Is the volume real? It is a real count of price updates (ticks) per bar, not traded size. Comparing it between bars is meaningful; VWAP-style values are approximate. See [The data](/docs/data). ### Why do fundamentals return na? An OTC candle feed has no company or economic data. Those requests run and return `na` with a warning. ### What timezone are bars in? UTC. The feed runs 24x7, with no sessions or weekend gaps. See [Time and sessions](/docs/time-and-sessions). ## Publishing and selling ### Can people see my code if I sell access? No. Protected and invite-only scripts run on the server; subscribers get values, never the source. See [Publish and sell](/docs/publishing). ### Can I edit a script after publishing? The title, description and tags for 15 minutes. After that, publish an update; every publication is a version you can roll back to from your [dashboard](/docs/dashboard). ### Are alerts from my script sent to me? `alert()` and `alertcondition()` appear in the editor console for now. Price alerts set on the chart fire on the server and reach you by notification and email. See [Alerts in scripts](/docs/script-alerts). ## The docs ### Can I give these docs to an AI assistant? Yes: every page has Copy page and Open in Claude / ChatGPT, the whole set is at [llms-full.txt](/docs/llms-full.txt), and there is an installable skill. See [Write Pine with AI](/docs/pine-with-ai). --- # Glossary > The terms these docs use, in one place: from bar index and series to repainting, tick count and space. | Term | Meaning | | --- | --- | | **Bar** | One candle: the open, high, low, close and volume of a period. | | **Bar index** | `bar_index`: the bar's position, 0 on the oldest loaded bar. | | **Series** | A value with one entry per bar, such as `close` or `ta.rsi(close, 14)`. | | **History reference** | `x[n]`: the value of `x` n bars ago. | | **na** | "No value": before warm-up ends, or further back than the chart goes. | | **Warm-up** | The first bars of a study, where it has too little history and returns `na`. | | **var** | A declaration that keeps its value from bar to bar instead of resetting. | | **Qualifier** | When a value is known: const, input, simple or series. | | **Overlay** | Drawing on the price chart rather than in a separate pane. | | **Pane** | A separate panel under the price chart, with its own scale. | | **Confirmed bar** | A bar that has closed; `barstate.isconfirmed`. | | **Repainting** | A script showing on history something it did not show live. | | **Lookahead** | Letting a higher-timeframe value see the end of its bar early. | | **Higher timeframe (HTF)** | A longer timeframe than the chart's, read with `request.security`. | | **Aggregated timeframe** | A timeframe the feed does not serve, built by combining smaller bars. | | **Tick count** | What `volume` holds on this feed: price updates per bar. | | **OTC** | Over-the-counter: the pairs this feed quotes, trading 24x7. | | **PineTS** | The open-source runtime that executes Pine Script here. | | **Transpile** | Turning Pine into code the engine runs; a failure is a syntax error. | | **Strategy** | A script that places simulated orders and produces a backtest. | | **Drawdown** | The largest fall in equity from a peak. | | **Open source / Protected / Invite-only** | Who can read and who can use a published script. | | **Space** | An author's paid storefront: one subscription for a set of scripts. | | **Grant** | Access to an invite-only script for one person, by hand or by subscription. | | **Boost** | A signed-in recommendation of a published script. | --- # Cheat sheet > One printable page of the Pine you write most often on Tradequix, from the script skeleton to strategies. ## Skeleton ```pine //@version=6 indicator("Name", overlay = true) len = input.int(20, "Length", minval = 1) x = ta.ema(close, len) plot(x, "EMA", color = color.orange) ``` ## Series and history | Write | Means | | --- | --- | | `close`, `open`, `high`, `low`, `volume` | This bar's values (volume = tick count) | | `hl2`, `hlc3`, `ohlc4` | Averages of the above | | `close[1]` | Previous bar's close | | `na(x)`, `nz(x)` | Test for, or replace, no value | | `var float x = na` | Keep x between bars | | `x := 1` | Reassign | ## Studies | Write | Gives | | --- | --- | | `ta.sma/ema/wma/hma(src, len)` | Averages | | `ta.rsi(src, len)`, `ta.atr(len)` | RSI, ATR | | `[m, u, l] = ta.bb(src, len, 2)` | Bollinger Bands | | `[macd, sig, hist] = ta.macd(src, 12, 26, 9)` | MACD | | `[st, dir] = ta.supertrend(3, 10)` | Supertrend (dir < 0 is up) | | `ta.crossover(a, b)` | true on the cross bar | | `ta.highest(high, n)`, `ta.lowest(low, n)` | Range extremes | | `ta.valuewhen(cond, src, 0)` | Value when cond last held | ## Drawing | Write | Draws | | --- | --- | | `plot(x, style = plot.style_columns)` | Line, histogram, columns, area… | | `plotshape(cond, style = shape.triangleup, location = location.belowbar)` | Markers where true or non-zero | | `hline(70)` | A fixed level | | `fill(p1, p2, color.new(color.purple, 85))` | Shade between plots | | `bgcolor(c)`, `barcolor(c)` | Tint the background, recolour candles | | `if barstate.islast` + `label.new(...)` | Draw once at the end | ## Other timeframes ```pine htf = request.security(syminfo.tickerid, "60", close[1], lookahead = barmerge.lookahead_on) ``` Feed timeframes: `5S 10S 15S 30S 1 2 3 5 10 15 30 60 240 D`. ## Strategy ```pine //@version=6 strategy("Name", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10) if ta.crossover(ta.ema(close, 9), ta.ema(close, 21)) strategy.entry("Long", strategy.long) strategy.exit("Exit", "Long", stop = close * 0.99, limit = close * 1.02) ``` ## Limits to remember 8 s per run · 40 `request.*` · 3,600 candles per request · 100,000 elements · 50 indicators per chart. --- # Pine function reference (PineTS 0.11.1) > Every function, variable and constant the Tradequix engine implements. Verified = used in scripts the test suite runs. Not available = this feed cannot supply the data (returns na). ## Built-ins and plotting Declarations, plotting, colouring the chart, and the small helpers every script uses: na, nz, fixnan. ### indicator (Verified) ```pine indicator(title, shorttitle, overlay, format, precision, max_bars_back, max_lines_count, max_labels_count, max_boxes_count) ``` Declares the script an indicator. Must be the first statement after the version line. - `title` (const string): The name shown in the legend and the catalogue. - `shorttitle` (const string, optional): A shorter name for the legend. - `overlay` (const bool, optional): true draws on the price chart; false (default) gives the script its own pane. - `precision` (const int, optional): Decimal places for values in the legend. ### strategy (Verified) ```pine strategy(title, shorttitle, overlay, initial_capital, default_qty_type, default_qty_value, pyramiding, commission_type, commission_value, slippage) ``` Declares the script a strategy, which can place simulated orders and produce a backtest. - `title` (const string): The strategy's name. - `overlay` (const bool, optional): Draw on the price chart. - `initial_capital` (const float, optional): Starting equity. Default 1,000,000. - `default_qty_type` (const string, optional): strategy.fixed, strategy.cash or strategy.percent_of_equity. - `default_qty_value` (const float, optional): The order size in that unit. - `pyramiding` (const int, optional): How many entries may stack in one direction. Default 0. - `commission_type` (const string, optional): strategy.commission.percent, cash_per_contract or cash_per_order. - `commission_value` (const float, optional): Commission in that unit. - `slippage` (const int, optional): Slippage in ticks added to market fills. ### plot (Verified) ```pine plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display, force_overlay) ``` Draws a series on the chart, one value per bar. - `series` (series int/float): The values to draw. na leaves a gap. - `title` (const string, optional): Name in the legend and settings. - `color` (series color, optional): Line colour; may change per bar. - `linewidth` (input int, optional): Width in pixels, 1 to 4. - `style` (input plot_style, optional): plot.style_line, _linebr, _stepline, _histogram, _columns, _area, _areabr, _circles, _cross. - `offset` (simple int, optional): Shift the plot left (negative) or right by bars. - `show_last` (input int, optional): Draw only the last N bars. - `display` (input plot_display, optional): display.none computes without drawing. - `force_overlay` (const bool, optional): Draw on the price chart from a pane script. Returns: `A plot id, for fill().` ```pine //@version=6 indicator("plot", overlay = true) plot(ta.sma(close, 20), "SMA 20", color = color.orange, linewidth = 2) ``` ### plotshape (Verified) ```pine plotshape(series, title, style, location, color, offset, text, textcolor, size, show_last, display, force_overlay) ``` Draws a shape on bars where the series is true or a non-zero number. - `series` (series bool/float): Where to draw. na, false and 0 draw nothing. - `style` (input string, optional): shape.triangleup, triangledown, circle, cross, xcross, diamond, square, flag, arrowup, arrowdown, labelup, labeldown. - `location` (input string, optional): location.abovebar, belowbar, top, bottom, absolute. - `size` (const string, optional): size.tiny, small, normal, large, huge, auto. - `text` (const string, optional): Text drawn with the shape. ```pine //@version=6 indicator("plotshape", overlay = true) plotshape(ta.crossover(ta.ema(close, 9), ta.ema(close, 21)), "Cross", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small) ``` ### plotchar (Verified) ```pine plotchar(series, title, char, location, color, offset, text, textcolor, size, show_last, display) ``` Draws a single character on bars where the series is true or non-zero. - `char` (input string): One character, for example "x" or "▲". ### plotarrow (Supported) ```pine plotarrow(series, title, colorup, colordown, offset, minheight, maxheight, show_last, display) ``` Draws an up arrow for positive values and a down arrow for negative ones; zero and na draw nothing. ### plotcandle (Verified) ```pine plotcandle(open, high, low, close, title, color, wickcolor, bordercolor, display) ``` Draws candles from your own OHLC series, for example Heikin Ashi computed in the script. ### plotbar (Supported) ```pine plotbar(open, high, low, close, title, color, display) ``` Like plotcandle, but draws OHLC bars. ### hline (Verified) ```pine hline(price, title, color, linestyle, linewidth, editable, display) ``` A fixed horizontal line at a price or level. - `price` (input int/float): Where the line sits. - `linestyle` (input hline_style, optional): hline.style_solid, style_dotted, style_dashed. Returns: `An hline id, for fill().` ### fill (Verified) ```pine fill(plot1, plot2, color, title, editable, fillgaps, display) · fill(hline1, hline2, color, …) ``` Shades the area between two plots or two hlines. - `plot1, plot2` (plot or hline): The ids returned by plot() or hline(). - `color` (series color, optional): Usually a transparent colour from color.new(). ```pine //@version=6 indicator("fill", overlay = true) [m, u, l] = ta.bb(close, 20, 2) p1 = plot(u, "Upper") p2 = plot(l, "Lower") fill(p1, p2, color = color.new(color.purple, 85)) ``` ### bgcolor (Verified) ```pine bgcolor(color, offset, editable, show_last, title, display, force_overlay) ``` Tints the background behind each bar. na leaves it untouched. ### barcolor (Verified) ```pine barcolor(color, offset, editable, show_last, title, display) ``` Recolours the chart's candles. ### na (Verified) ```pine na(x) · na ``` As a value, na means "no value". As a function, na(x) is true when x has no value. ### nz (Verified) ```pine nz(source, replacement) ``` Replaces na with a value: 0 by default, or replacement. ```pine //@version=6 indicator("nz") change = close - close[1] plot(nz(change), "Change, na as 0") ``` ### fixnan (Supported) ```pine fixnan(source) ``` Replaces na with the last value that was not na. ### alert (Verified) ```pine alert(message, freq) ``` Emits an alert event when called. On Tradequix it appears in the editor console. - `freq` (input string, optional): alert.freq_all, freq_once_per_bar, freq_once_per_bar_close. ### alertcondition (Verified) ```pine alertcondition(condition, title, message) ``` Declares a condition that can be alerted on. Captured and shown in the editor console. ### timestamp (Supported) ```pine timestamp(year, month, day, hour, minute, second) · timestamp(timezone, year, …) ``` A time in milliseconds, for drawings with xloc.bar_time or comparing with time. The feed runs on UTC. ### max_bars_back (Supported) ```pine max_bars_back(var, num) ``` Reserves history for a series that is referenced further back than the engine can infer. - `bar_index` (Verified) - `bool` (Supported) - `day` (Supported) - `dayofmonth` (Supported) - `dayofweek` (Supported) - `error` (Supported) - `float` (Verified) - `freq_all` (Supported) - `freq_once_per_bar` (Supported) - `freq_once_per_bar_close` (Supported) - `hour` (Verified) - `int` (Verified) - `linestyle_dashed` (Supported) - `linestyle_dotted` (Supported) - `linestyle_solid` (Supported) - `minute` (Supported) - `month` (Supported) - `second` (Supported) - `string` (Supported) - `style_area` (Supported) - `style_areabr` (Supported) - `style_circles` (Supported) - `style_columns` (Supported) - `style_cross` (Supported) - `style_dashed` (Supported) - `style_dotted` (Supported) - `style_histogram` (Supported) - `style_line` (Supported) - `style_linebr` (Supported) - `style_solid` (Supported) - `style_stepline` (Supported) - `style_stepline_diamond` (Supported) - `style_steplinebr` (Supported) - `weekofyear` (Supported) - `year` (Verified) ## ta: technical analysis Averages, oscillators, bands, trend studies, crosses, pivots and lookbacks. Each returns a series and handles its own warm-up. ### ta.sma (Verified) ```pine ta.sma(source, length) ``` Simple moving average: the mean of the last length values. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ```pine //@version=6 indicator("ta.sma", overlay = true) plot(ta.sma(close, 50), "SMA 50", color = color.orange, linewidth = 2) ``` ### ta.ema (Verified) ```pine ta.ema(source, length) ``` Exponential moving average; recent bars weigh more. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ```pine //@version=6 indicator("ta.ema", overlay = true) plot(ta.ema(close, 21), "EMA 21", color = color.teal, linewidth = 2) ``` ### ta.wma (Verified) ```pine ta.wma(source, length) ``` Weighted moving average with linearly decreasing weights. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.hma (Verified) ```pine ta.hma(source, length) ``` Hull moving average: smooth with little lag. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.rma (Verified) ```pine ta.rma(source, length) ``` Wilder's moving average, the smoothing used inside RSI and ATR. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.vwma (Verified) ```pine ta.vwma(source, length) ``` Volume-weighted moving average. Volume on this feed is a tick count. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.alma (Verified) ```pine ta.alma(series, length, offset, sigma, floor) ``` Arnaud Legoux moving average: a Gaussian-weighted average. - `series` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. - `offset` (simple float): 0 to 1; higher reacts faster. 0.85 is usual. - `sigma` (simple float): Smoothness; 6 is usual. Returns: `series float` ### ta.swma (Supported) ```pine ta.swma(source) ``` Symmetrically weighted average over a fixed 4 bars. Returns: `series float` ### ta.linreg (Verified) ```pine ta.linreg(source, length, offset) ``` Linear regression line's value, offset bars from the end. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. - `offset` (simple int): 0 for the current bar. Returns: `series float` ### ta.rsi (Verified) ```pine ta.rsi(source, length) ``` Relative Strength Index, 0 to 100. - `source` (series float): The series to read, usually close. - `length` (series int): Usually 14. Returns: `series float` ```pine //@version=6 indicator("ta.rsi") r = ta.rsi(close, 14) plot(r, "RSI", color = color.purple) hline(70) hline(30) ``` ### ta.stoch (Verified) ```pine ta.stoch(source, high, low, length) ``` Stochastic %K, unsmoothed. Smooth it with ta.sma for the classic %K and %D. - `source` (series float): The series to read, usually close. - `high` (series float): Usually high. - `low` (series float): Usually low. - `length` (series int): How many bars to look back. Returns: `series float` ```pine //@version=6 indicator("ta.stoch") k = ta.sma(ta.stoch(close, high, low, 14), 3) plot(k, "%K") plot(ta.sma(k, 3), "%D", color = color.orange) ``` ### ta.cci (Verified) ```pine ta.cci(source, length) ``` Commodity Channel Index. - `source` (series float): Usually hlc3. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.mfi (Verified) ```pine ta.mfi(series, length) ``` Money Flow Index, RSI weighted by volume (tick count here). - `series` (series float): Usually hlc3. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.mom (Verified) ```pine ta.mom(source, length) ``` Momentum: source minus source length bars ago. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.roc (Verified) ```pine ta.roc(source, length) ``` Rate of change, in percent. - `source` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.tsi (Verified) ```pine ta.tsi(source, short_length, long_length) ``` True Strength Index, -1 to 1. Returns: `series float` ### ta.wpr (Verified) ```pine ta.wpr(length) ``` Williams %R, -100 to 0. - `length` (series int): How many bars to look back. Returns: `series float` ### ta.cmo (Verified) ```pine ta.cmo(series, length) ``` Chande Momentum Oscillator. Returns: `series float` ### ta.atr (Verified) ```pine ta.atr(length) ``` Average True Range: the typical bar range, smoothed with RMA. - `length` (series int): Usually 14. Returns: `series float` ```pine //@version=6 indicator("ta.atr") plot(ta.atr(14), "ATR 14", color = color.orange) ``` ### ta.tr (Verified) ```pine ta.tr · ta.tr(handle_na) ``` True range of the current bar. Returns: `series float` ### ta.stdev (Verified) ```pine ta.stdev(source, length, biased) ``` Standard deviation over length bars. Returns: `series float` ### ta.dev (Supported) ```pine ta.dev(source, length) ``` Mean absolute deviation from the SMA. Returns: `series float` ### ta.variance (Supported) ```pine ta.variance(source, length, biased) ``` Variance over length bars. Returns: `series float` ### ta.bb (Verified) ```pine ta.bb(series, length, mult) ``` Bollinger Bands. - `series` (series float): The series to read, usually close. - `length` (series int): How many bars to look back. - `mult` (simple float): Standard deviations; 2 is usual. Returns: `[middle, upper, lower]` ```pine //@version=6 indicator("ta.bb", overlay = true) [m, u, l] = ta.bb(close, 20, 2) plot(m, "Basis", color = color.orange) plot(u, "Upper") plot(l, "Lower") ``` ### ta.bbw (Supported) ```pine ta.bbw(series, length, mult) ``` Bollinger Band width as a fraction of the basis. Returns: `series float` ### ta.kc (Verified) ```pine ta.kc(series, length, mult, useTrueRange) ``` Keltner Channels around an EMA. Returns: `[middle, upper, lower]` ### ta.kcw (Supported) ```pine ta.kcw(series, length, mult, useTrueRange) ``` Keltner Channel width. Returns: `series float` ### ta.macd (Verified) ```pine ta.macd(source, fastlen, slowlen, siglen) ``` MACD line, signal line and histogram. Returns: `[macdLine, signalLine, histLine]` ```pine //@version=6 indicator("ta.macd") [m, s, h] = ta.macd(close, 12, 26, 9) plot(h, "Hist", style = plot.style_columns, color = h >= 0 ? color.teal : color.red) plot(m, "MACD") plot(s, "Signal", color = color.orange) ``` ### ta.dmi (Verified) ```pine ta.dmi(diLength, adxSmoothing) ``` Directional Movement: +DI, -DI and ADX. Returns: `[plus, minus, adx]` ```pine //@version=6 indicator("ta.dmi") [p, m, adx] = ta.dmi(14, 14) plot(p, "+DI", color = color.teal) plot(m, "-DI", color = color.red) plot(adx, "ADX", color = color.orange) ``` ### ta.supertrend (Verified) ```pine ta.supertrend(factor, atrPeriod) ``` Supertrend line and direction. A negative direction is an up trend. Returns: `[supertrend, direction]` ```pine //@version=6 indicator("ta.supertrend", overlay = true) [st, dir] = ta.supertrend(3, 10) plot(st, "Supertrend", color = dir < 0 ? color.teal : color.red) ``` ### ta.sar (Verified) ```pine ta.sar(start, inc, max) ``` Parabolic SAR. - `start` (simple float): 0.02 is usual. - `inc` (simple float): 0.02 is usual. - `max` (simple float): 0.2 is usual. Returns: `series float` ```pine //@version=6 indicator("ta.sar", overlay = true) plot(ta.sar(0.02, 0.02, 0.2), "SAR", style = plot.style_cross, color = color.orange) ``` ### ta.crossover (Verified) ```pine ta.crossover(source1, source2) ``` true on the bar source1 moves from below source2 to above it. Returns: `series bool` ```pine //@version=6 indicator("ta.crossover", overlay = true) f = ta.ema(close, 9) s = ta.ema(close, 21) plotshape(ta.crossover(f, s), style = shape.triangleup, location = location.belowbar, color = color.teal) ``` ### ta.crossunder (Verified) ```pine ta.crossunder(source1, source2) ``` true on the bar source1 moves from above source2 to below it. Returns: `series bool` ### ta.cross (Verified) ```pine ta.cross(source1, source2) ``` true on any cross, either direction. Returns: `series bool` ### ta.highest (Verified) ```pine ta.highest(source, length) ``` Highest value over the last length bars, including this one. Returns: `series float` ```pine //@version=6 indicator("ta.highest", overlay = true) plot(ta.highest(high, 20), "20-bar high", color = color.teal) plot(ta.lowest(low, 20), "20-bar low", color = color.red) ``` ### ta.lowest (Verified) ```pine ta.lowest(source, length) ``` Lowest value over the last length bars. Returns: `series float` ### ta.highestbars (Verified) ```pine ta.highestbars(source, length) ``` Offset (0 or negative) to the highest bar in the window. Returns: `series int` ### ta.lowestbars (Verified) ```pine ta.lowestbars(source, length) ``` Offset (0 or negative) to the lowest bar in the window. Returns: `series int` ### ta.pivothigh (Verified) ```pine ta.pivothigh(source, leftbars, rightbars) · ta.pivothigh(leftbars, rightbars) ``` The pivot's price, reported rightbars after it; na elsewhere. Returns: `series float` Shift markers back with offset = -rightbars to draw them on the pivot bar. ```pine //@version=6 indicator("ta.pivothigh", overlay = true) ph = ta.pivothigh(high, 5, 5) plotshape(not na(ph), style = shape.triangledown, location = location.abovebar, color = color.red, offset = -5) ``` ### ta.pivotlow (Verified) ```pine ta.pivotlow(source, leftbars, rightbars) · ta.pivotlow(leftbars, rightbars) ``` The pivot low's price, reported rightbars after it; na elsewhere. Returns: `series float` ### ta.valuewhen (Verified) ```pine ta.valuewhen(condition, source, occurrence) ``` source's value on the occurrence-th most recent bar where condition was true (0 is the latest). Returns: `series` ```pine //@version=6 indicator("ta.valuewhen", overlay = true) up = ta.crossover(close, ta.sma(close, 20)) plot(ta.valuewhen(up, close, 0), "Close at last cross", style = plot.style_stepline) ``` ### ta.barssince (Supported) ```pine ta.barssince(condition) ``` Bars since condition was last true; na before it ever was. Returns: `series int` ### ta.change (Verified) ```pine ta.change(source, length) ``` source minus source length bars ago (length defaults to 1). For bools, true when the value changed. Returns: `series` ### ta.rising (Supported) ```pine ta.rising(source, length) ``` true when source has risen on each of the last length bars. Returns: `series bool` ### ta.falling (Supported) ```pine ta.falling(source, length) ``` true when source has fallen on each of the last length bars. Returns: `series bool` ### ta.cum (Supported) ```pine ta.cum(source) ``` Running total of source since the first bar. Returns: `series float` ### ta.correlation (Supported) ```pine ta.correlation(source1, source2, length) ``` Pearson correlation of two series, -1 to 1. Returns: `series float` ### ta.percentrank (Supported) ```pine ta.percentrank(source, length) ``` Percent of the last length values below the current one. Returns: `series float` ### ta.median (Supported) ```pine ta.median(source, length) ``` Median over length bars. Returns: `series float` ### ta.range (Supported) ```pine ta.range(source, length) ``` Highest minus lowest over length bars. Returns: `series float` ### ta.obv (Verified) ```pine ta.obv ``` On Balance Volume. Meaningful on tick-count volume. Returns: `series float` ### ta.accdist (Verified) ```pine ta.accdist ``` Accumulation/Distribution. Treats volume as size, so it is approximate here. Returns: `series float` ### ta.vwap (Verified) ```pine ta.vwap(source) · ta.vwap(source, anchor, stdev_mult) ``` Volume-weighted average price. Volume is a tick count on this feed, so treat it as approximate. Returns: `series float · [vwap, upper, lower]` - `ta.cog` (Supported): Center of Gravity (COG) The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio. - `ta.iii` (Supported): Intraday Intensity Index (III) Formula (as TradingView computes it; its reference manual shows a division by volume): (2 * close - high - low) / (high - low) * volume - `ta.max` (Supported): Trailing Maximum (ta.max) Returns the all-time high value of `source` from the first bar of the chart up to the current bar. - `ta.min` (Supported): Trailing Minimum (ta.min) Returns the all-time low value of `source` from the first bar of the chart up to the current bar. - `ta.mode` (Supported): Mode Returns the mode of the series. - `ta.nvi` (Supported): Negative Volume Index (NVI) Formula: If close or close[1] is 0, nvi = nvi[1] Else if volume < volume[1], nvi = nvi[1] + ((close - close[1]) / close[1]) * nvi[1] Else nvi = nvi[1] Initial value is 1.0 - `ta.percentile_linear_interpolation` (Supported): Percentile Linear Interpolation Calculates percentile using method of linear interpolation between the two nearest ranks. - `ta.percentile_nearest_rank` (Supported): Percentile Nearest Rank Calculates percentile using method of Nearest Rank. - `ta.pivot_point_levels` (Supported): ta.pivot_point_levels(type, anchor, developing) → array of 11 levels [P, R1, S1, …, R5, S5]. - `ta.pvi` (Supported): Positive Volume Index (PVI) Formula: If close or close[1] is 0, pvi = pvi[1] Else if volume > volume[1], pvi = pvi[1] + ((close - close[1]) / close[1]) * pvi[1] Else pvi = pvi[1] Initial value is 1.0 - `ta.pvt` (Verified): Price-Volume Trend (PVT) The PVT function calculates the Price-Volume Trend, which is a cumulative total of volume adjusted by the percentage change in price. - `ta.rci` (Supported): Rank Correlation Index: Spearman's rank correlation between the last `length` values of `source` and their bar order, scaled to -100..100 (100 = rose on every bar). - `ta.wad` (Supported): Williams Accumulation/Distribution (WAD) Formula: trueHigh = math.max(high, close[1]) trueLow = math.min(low, close[1]) mom = ta.change(close) gain = (mom > 0) ? - `ta.wvad` (Supported): Williams Variable Accumulation/Distribution (WVAD) Formula: (close - open) / (high - low) * volume ## math Arithmetic, rounding, logs, trigonometry and aggregates. ### math.abs (Verified) ```pine math.abs(number) ``` Absolute value. ### math.max (Verified) ```pine math.max(number0, number1, …) ``` The largest of its arguments. ### math.min (Verified) ```pine math.min(number0, number1, …) ``` The smallest of its arguments. ### math.avg (Verified) ```pine math.avg(number0, number1, …) ``` The mean of its arguments. ### math.sum (Verified) ```pine math.sum(source, length) ``` Sum of the last length values of a series. ### math.round (Supported) ```pine math.round(number, precision) ``` Rounds to the nearest whole number, or to precision decimals. ### math.round_to_mintick (Supported) ```pine math.round_to_mintick(number) ``` Rounds to the symbol's price step (syminfo.mintick). ### math.floor (Verified) ```pine math.floor(number) ``` Largest whole number not greater than number. ### math.ceil (Supported) ```pine math.ceil(number) ``` Smallest whole number not less than number. ### math.sign (Supported) ```pine math.sign(number) ``` 1, 0 or -1. ### math.pow (Supported) ```pine math.pow(base, exponent) ``` base raised to exponent. ### math.sqrt (Verified) ```pine math.sqrt(number) ``` Square root. ### math.log (Verified) ```pine math.log(number) ``` Natural logarithm. ### math.log10 (Supported) ```pine math.log10(number) ``` Base-10 logarithm. ### math.exp (Supported) ```pine math.exp(number) ``` e raised to number. ### math.random (Supported) ```pine math.random(min, max, seed) ``` A pseudo-random number between min and max. ### math.pi (Supported) ```pine math.pi ``` π. - `math.acos` (Supported) - `math.asin` (Supported) - `math.atan` (Supported) - `math.cos` (Supported) - `math.e` (Supported): Euler's number (e) The base of natural logarithms, approximately 2.718281828459045 - `math.ln` (Supported) - `math.phi` (Supported): Golden ratio (φ, phi) Calculated as (1 + sqrt(5)) / 2, approximately 1.618033988749895 - `math.rphi` (Supported): Reciprocal of golden ratio (1/φ) Equal to phi - 1, approximately 0.6180339887498948 - `math.sin` (Supported) - `math.tan` (Supported) - `math.todegrees` (Supported): Converts an angle in radians to degrees. - `math.toradians` (Supported): Converts an angle in degrees to radians. ## str: strings Format numbers, build and search text for labels and tables. ### str.tostring (Verified) ```pine str.tostring(value, format) ``` Text from a number or bool. format can be format.mintick, format.percent, or a pattern like "#.00". ### str.format (Verified) ```pine str.format(formatString, arg0, arg1, …) ``` Fills {0}, {1}… in formatString, for example str.format("{0} at {1}", "RSI", r). ### str.tonumber (Supported) ```pine str.tonumber(string) ``` Parses a number; na when it cannot. ### str.contains (Supported) ```pine str.contains(source, str) ``` true when source contains str. ### str.length (Supported) ```pine str.length(string) ``` Number of characters. ### str.split (Supported) ```pine str.split(string, separator) ``` An array of strings. ### str.replace_all (Supported) ```pine str.replace_all(source, target, replacement) ``` Replaces every occurrence. ### str.upper (Supported) ```pine str.upper(source) · str.lower(source) ``` Changes case. ### str.format_time (Supported) ```pine str.format_time(time, format, timezone) ``` Formats a millisecond time, for example "yyyy-MM-dd HH:mm". The feed runs on UTC. - `str.endswith` (Supported) - `str.lower` (Supported) - `str.match` (Supported) - `str.pos` (Supported) - `str.repeat` (Supported) - `str.replace` (Supported) - `str.startswith` (Supported) - `str.substring` (Supported) - `str.trim` (Supported) ## input Every input becomes a field in the indicator's settings. See the Inputs guide for how saved values behave. ### input.int (Verified) ```pine input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm, options) ``` A whole-number field. ### input.float (Verified) ```pine input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm, options) ``` A decimal field. ### input.bool (Verified) ```pine input.bool(defval, title, tooltip, inline, group, confirm) ``` A checkbox. ### input.string (Verified) ```pine input.string(defval, title, options, tooltip, inline, group, confirm) ``` Text, or a dropdown when options is given. ### input.color (Verified) ```pine input.color(defval, title, tooltip, inline, group, confirm) ``` A colour picker. ### input.source (Verified) ```pine input.source(defval, title, tooltip, inline, group) ``` A choice of price series: close, open, hl2, hlc3, ohlc4… ### input.timeframe (Supported) ```pine input.timeframe(defval, title, options, tooltip, inline, group, confirm) ``` A timeframe picker for request.security. ### input.text_area (Supported) ```pine input.text_area(defval, title, tooltip, group, confirm) ``` Multi-line text. ### input.enum (Supported) ```pine input.enum(defval, title, options, tooltip, inline, group, confirm) ``` A dropdown of an enum's members. - `input.price` (Supported) - `input.session` (Supported) - `input.symbol` (Supported) - `input.time` (Supported) ## request: other data Other timeframes work. Company, economic and order-flow data are not in this feed and return na with a warning. ### request.security (Supported) ```pine request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency, calc_bars_count) ``` Evaluates expression on another timeframe of the chart's symbol. Use syminfo.tickerid. Fourteen timeframes come from the feed; others are aggregated; under 5 seconds is refused. At most 40 request contexts per script. ### request.security_lower_tf (Supported) ```pine request.security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol, currency, ignore_invalid_timeframe, calc_bars_count) ``` An array of the lower-timeframe values inside each chart bar. ### request.financial (Not available) ```pine request.financial(symbol, financial_id, period, …) ``` Not available on this feed: returns na with a warning. ### request.earnings (Not available) ```pine request.earnings(ticker, field, …) ``` Not available on this feed: returns na with a warning. ### request.dividends (Not available) ```pine request.dividends(ticker, field, …) ``` Not available on this feed: returns na with a warning. ### request.economic (Not available) ```pine request.economic(country_code, field, …) ``` Not available on this feed: returns na with a warning. ### request.footprint (Not available) ```pine request.footprint(…) ``` Needs order-flow data, which this feed does not carry. Returns na with a warning. - `request.currency_rate` (Supported): request.currency_rate(from, to, ignore_invalid_currency): 1 for a currency to itself (as on TradingView); otherwise there is no exchange-rate source, so na with a warning (see unsupportedRequest). - `request.quandl` (Not available): No source of Nasdaq Data Link / Quandl data (request.quandl): na, with a warning (see unsupportedRequest). - `request.seed` (Supported): No source of Pine Seeds data (request.seed): na, with a warning (see unsupportedRequest). - `request.splits` (Not available): No source of split data (request.splits): na, with a warning (see unsupportedRequest). ## strategy Orders and the backtest's running statistics. Declare strategy() instead of indicator() to use them. ### strategy.entry (Verified) ```pine strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message) ``` Opens or adds to a position. An entry in the opposite direction reverses it. - `id` (series string): Names the entry; exits refer to it. - `direction` (strategy_direction): strategy.long or strategy.short. ```pine //@version=6 strategy("strategy.entry", overlay = true) if ta.crossover(ta.ema(close, 9), ta.ema(close, 21)) strategy.entry("Long", strategy.long) if ta.crossunder(ta.ema(close, 9), ta.ema(close, 21)) strategy.close("Long") ``` ### strategy.exit (Verified) ```pine strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, …) ``` Attaches a take-profit and/or stop-loss to an entry. limit/stop are prices; profit/loss are ticks. ### strategy.close (Verified) ```pine strategy.close(id, comment, qty, qty_percent, alert_message, immediately) ``` Closes the position from entry id at market. ### strategy.close_all (Supported) ```pine strategy.close_all(comment, alert_message, immediately) ``` Closes every open position. ### strategy.order (Supported) ```pine strategy.order(id, direction, qty, limit, stop, …) ``` A raw order without entry's reversal logic. ### strategy.cancel (Supported) ```pine strategy.cancel(id) · strategy.cancel_all() ``` Cancels pending orders. ### strategy.position_size (Supported) ```pine strategy.position_size ``` Current position: positive long, negative short, 0 flat. ### strategy.netprofit (Supported) ```pine strategy.netprofit ``` Profit of closed trades so far. ### strategy.openprofit (Supported) ```pine strategy.openprofit ``` Unrealised profit of the open position. ### strategy.equity (Supported) ```pine strategy.equity ``` Initial capital + net profit + open profit. - `strategy.account_currency` (Supported): Account currency configured in the strategy() declaration's `currency=`. - `strategy.avg_losing_trade` (Supported): Average loss across losing closed trades, returned as a POSITIVE number (Pine convention: average loss is unsigned). - `strategy.avg_losing_trade_percent` (Supported): Average per-trade loss (as a SIGNED negative percent) across losing closed trades. - `strategy.avg_trade` (Supported): Average profit/loss across all closed trades (post-commission). - `strategy.avg_trade_percent` (Supported): Average per-trade return as a percent. - `strategy.avg_winning_trade` (Supported): Average profit across winning closed trades. - `strategy.avg_winning_trade_percent` (Supported): Average per-trade return (as a percent) across winning closed trades. - `strategy.cancel_all` (Supported): Cancel all pending orders — entries AND exits, as on TradingView. - `strategy.cash` (Supported): Constant for order sizing type: cash Used in default_qty_type parameter - `strategy.closedtrades` (Supported): Pine's `strategy.closedtrades` serves a dual role: - As a scalar: a series int count of closed trades. - `strategy.convert_to_account` (Supported): Convert a value from the symbol's currency to the account currency. - `strategy.convert_to_symbol` (Supported): Inverse of convert_to_account: from account currency → symbol currency. - `strategy.default_entry_qty` (Supported): Returns the qty that would be used for an entry at the given fill price, given the strategy's `default_qty_type` and `default_qty_value`. - `strategy.eventrades` (Supported): Count of breakeven (profit === 0) closed trades. - `strategy.fixed` (Supported): Constant for order sizing type: fixed Used in default_qty_type parameter - `strategy.grossloss` (Supported): Total currency value of all completed losing trades, as a POSITIVE number (the absolute sum of losses). - `strategy.grossloss_percent` (Supported): strategy.grossloss as a percent of initial capital. - `strategy.grossprofit` (Supported): Total currency value of all completed winning trades (post-commission). - `strategy.grossprofit_percent` (Supported): strategy.grossprofit as a percent of initial capital. - `strategy.initial_capital` (Supported): The initial capital configured on the strategy() declaration. - `strategy.long` (Verified): Constant representing long direction - `strategy.losstrades` (Supported): Count of closed trades with profit < 0. - `strategy.margin_liquidation_price` (Supported): Price at which the current leveraged position would be force-liquidated. - `strategy.max_contracts_held_all` (Supported): Peak |position_size| seen across the run. - `strategy.max_contracts_held_long` (Supported): Peak long-side position_size seen. - `strategy.max_contracts_held_short` (Supported): Peak |short-side position_size| seen. - `strategy.max_drawdown` (Supported): Maximum peak-to-trough equity drawdown over the whole run (currency). - `strategy.max_drawdown_percent` (Supported): Maximum drawdown percent. - `strategy.max_runup` (Supported): Maximum equity run-up over the whole run (currency). - `strategy.max_runup_percent` (Supported): Maximum equity run-up percent. - `strategy.netprofit_percent` (Supported): Realized net profit expressed as a percent of initial capital. - `strategy.openprofit_percent` (Supported): Unrealized P&L expressed as a percent of initial capital. - `strategy.opentrades` (Supported): Pine's `strategy.opentrades` mirrors strategy.closedtrades' dual-role pattern — see that file's header for the rationale. - `strategy.percent_of_equity` (Verified): Constant for order sizing type: percent_of_equity Used in default_qty_type parameter - `strategy.position_avg_price` (Supported): Weighted-average entry price of the current open position. - `strategy.position_entry_name` (Supported): Id string of the entry that initially opened the current position. - `strategy.risk` (Supported): `strategy.risk` is a nested namespace with 6 setter functions that configure pre-trade risk rules. - `strategy.short` (Verified): Constant representing short direction - `strategy.wintrades` (Supported): Count of closed trades with profit > 0. ## color Named colours and functions to make your own. Transparency runs 0 (opaque) to 100 (invisible). ### color.new (Verified) ```pine color.new(color, transp) ``` The same colour with transparency transp (0 to 100). ### color.rgb (Supported) ```pine color.rgb(red, green, blue, transp) ``` A colour from 0 to 255 channels. ### color.from_gradient (Verified) ```pine color.from_gradient(value, bottom_value, top_value, bottom_color, top_color) ``` A colour between two, by where value sits in a range. ```pine //@version=6 indicator("color.from_gradient") r = ta.rsi(close, 14) plot(r, "RSI", color = color.from_gradient(r, 30, 70, color.red, color.teal), linewidth = 3) ``` ### color.r (Supported) ```pine color.r(color) · color.g · color.b · color.t ``` Read one channel or the transparency. - `color.aqua` (Supported) - `color.b` (Supported) - `color.black` (Supported) - `color.blue` (Supported) - `color.fuchsia` (Supported) - `color.g` (Supported) - `color.gray` (Verified) - `color.green` (Supported) - `color.lime` (Supported) - `color.maroon` (Supported) - `color.navy` (Supported) - `color.olive` (Supported) - `color.orange` (Verified) - `color.purple` (Verified) - `color.red` (Verified) - `color.silver` (Supported) - `color.t` (Supported) - `color.teal` (Verified) - `color.white` (Verified) - `color.yellow` (Supported) ## Drawings: label, line, box, table Objects placed at coordinates. Create with *.new(), keep the id to update or delete it. See the Drawings guide. ### label.new (Verified) ```pine label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, force_overlay) ``` A text label at a bar and price. ### line.new (Verified) ```pine line.new(x1, y1, x2, y2, xloc, extend, color, style, width, force_overlay) ``` A straight line between two points. extend.right/left/both continues it. ### box.new (Verified) ```pine box.new(left, top, right, bottom, border_color, border_width, border_style, extend, xloc, bgcolor, text, …) ``` A rectangle. ### table.new (Verified) ```pine table.new(position, columns, rows, bgcolor, frame_color, frame_width, border_color, border_width, force_overlay) ``` A grid pinned to a corner: position.top_right and so on. ### table.cell (Verified) ```pine table.cell(table_id, column, row, text, width, height, text_color, text_halign, text_valign, text_size, bgcolor, tooltip) ``` Sets one cell. Columns and rows count from 0. ### linefill.new (Supported) ```pine linefill.new(line1, line2, color) ``` Shades between two lines. ### polyline.new (Supported) ```pine polyline.new(points, curved, closed, xloc, line_color, fill_color, line_style, line_width, force_overlay) ``` A path through an array of chart.point. - `label.all` (Supported) - `label.copy` (Supported) - `label.delete` (Supported) - `label.get_text` (Supported) - `label.get_x` (Supported) - `label.get_y` (Supported) - `label.set_color` (Supported) - `label.set_point` (Supported) - `label.set_size` (Supported) - `label.set_style` (Supported) - `label.set_text` (Supported) - `label.set_text_font_family` (Supported) - `label.set_text_formatting` (Supported) - `label.set_textalign` (Supported) - `label.set_textcolor` (Supported) - `label.set_tooltip` (Supported) - `label.set_x` (Supported) - `label.set_xloc` (Supported) - `label.set_xy` (Supported) - `label.set_y` (Supported) - `label.set_yloc` (Supported) - `label.style_arrowdown` (Supported) - `label.style_arrowup` (Supported) - `label.style_circle` (Supported) - `label.style_cross` (Supported) - `label.style_diamond` (Supported) - `label.style_flag` (Supported) - `label.style_label_center` (Supported) - `label.style_label_down` (Verified) - `label.style_label_left` (Supported) - `label.style_label_lower_left` (Supported) - `label.style_label_lower_right` (Supported) - `label.style_label_right` (Supported) - `label.style_label_up` (Verified) - `label.style_label_upper_left` (Supported) - `label.style_label_upper_right` (Supported) - `label.style_none` (Supported) - `label.style_square` (Supported) - `label.style_text_outline` (Supported) - `label.style_triangledown` (Supported) - `label.style_triangleup` (Supported) - `label.style_xcross` (Supported) - `line.all` (Supported) - `line.copy` (Supported) - `line.delete` (Supported) - `line.get_price` (Supported) - `line.get_x1` (Supported) - `line.get_x2` (Supported) - `line.get_y1` (Supported) - `line.get_y2` (Supported) - `line.linefills` (Supported) - `line.set_color` (Supported) - `line.set_extend` (Supported) - `line.set_first_point` (Supported) - `line.set_second_point` (Supported) - `line.set_style` (Supported) - `line.set_width` (Supported) - `line.set_x1` (Supported) - `line.set_x2` (Supported) - `line.set_xloc` (Supported) - `line.set_xy1` (Supported) - `line.set_xy2` (Supported) - `line.set_y1` (Supported) - `line.set_y2` (Supported) - `line.style_arrow_both` (Supported) - `line.style_arrow_left` (Supported) - `line.style_arrow_right` (Supported) - `line.style_dashed` (Supported) - `line.style_dotted` (Supported) - `line.style_solid` (Supported) - `box.all` (Supported) - `box.copy` (Supported) - `box.delete` (Supported) - `box.get_bottom` (Supported) - `box.get_left` (Supported) - `box.get_right` (Supported) - `box.get_top` (Supported) - `box.set_bgcolor` (Supported) - `box.set_border_color` (Supported) - `box.set_border_style` (Supported) - `box.set_border_width` (Supported) - `box.set_bottom` (Supported) - `box.set_bottom_right_point` (Supported) - `box.set_extend` (Supported) - `box.set_left` (Supported) - `box.set_lefttop` (Supported) - `box.set_right` (Supported) - `box.set_rightbottom` (Supported) - `box.set_text` (Supported) - `box.set_text_color` (Supported) - `box.set_text_font_family` (Supported) - `box.set_text_formatting` (Supported) - `box.set_text_halign` (Supported) - `box.set_text_size` (Supported) - `box.set_text_valign` (Supported) - `box.set_text_wrap` (Supported) - `box.set_top` (Supported) - `box.set_top_left_point` (Supported) - `box.set_xloc` (Supported) - `table.all` (Supported) - `table.cell_set_bgcolor` (Supported) - `table.cell_set_height` (Supported) - `table.cell_set_text` (Supported) - `table.cell_set_text_color` (Supported) - `table.cell_set_text_font_family` (Supported) - `table.cell_set_text_formatting` (Supported) - `table.cell_set_text_halign` (Supported) - `table.cell_set_text_size` (Supported) - `table.cell_set_text_valign` (Supported) - `table.cell_set_tooltip` (Supported) - `table.cell_set_width` (Supported) - `table.clear` (Supported) - `table.delete` (Supported) - `table.merge_cells` (Supported) - `table.set_bgcolor` (Supported) - `table.set_border_color` (Supported) - `table.set_border_width` (Supported) - `table.set_frame_color` (Supported) - `table.set_frame_width` (Supported) - `table.set_position` (Supported) - `linefill.all` (Supported) - `linefill.delete` (Supported) - `linefill.get_line1` (Supported) - `linefill.get_line2` (Supported) - `linefill.set_color` (Supported) - `polyline.all` (Supported) - `polyline.delete` (Supported) ## array, matrix, map Collections of values. Up to 100,000 elements each. ### array.new (Verified) ```pine array.new(size, initial_value) · array.new_float(size, initial_value) ``` Creates an array. ### array.push (Supported) ```pine array.push(id, value) ``` Adds to the end. ### array.get (Supported) ```pine array.get(id, index) ``` Reads an element. Out of range is a runtime error. ### array.size (Supported) ```pine array.size(id) ``` Number of elements. ### array.shift (Supported) ```pine array.shift(id) ``` Removes and returns the first element; with push, makes a rolling window. ### matrix.new (Supported) ```pine matrix.new(rows, columns, initial_value) ``` Creates a matrix. ### map.new (Supported) ```pine map.new() ``` Creates a map. ### map.put (Supported) ```pine map.put(id, key, value) ``` Sets a key. - `array.abs` (Supported) - `array.avg` (Supported) - `array.binary_search` (Supported) - `array.binary_search_leftmost` (Supported) - `array.binary_search_rightmost` (Supported) - `array.clear` (Supported) - `array.concat` (Supported) - `array.copy` (Supported) - `array.covariance` (Supported) - `array.every` (Supported) - `array.fill` (Supported) - `array.first` (Supported) - `array.from` (Supported) - `array.includes` (Supported) - `array.indexof` (Supported) - `array.insert` (Supported) - `array.join` (Supported): Joins the elements of the array into a string, separated by the separator (default: none). - `array.last` (Supported) - `array.lastindexof` (Supported) - `array.max` (Supported) - `array.median` (Supported) - `array.min` (Supported) - `array.mode` (Supported) - `array.new_bool` (Supported) - `array.new_box` (Supported) - `array.new_color` (Supported) - `array.new_float` (Supported) - `array.new_int` (Supported) - `array.new_label` (Supported) - `array.new_line` (Supported) - `array.new_linefill` (Supported) - `array.new_string` (Supported) - `array.new_table` (Supported) - `array.percentile_linear_interpolation` (Supported) - `array.percentile_nearest_rank` (Supported) - `array.percentrank` (Supported) - `array.pop` (Supported) - `array.range` (Supported) - `array.remove` (Supported) - `array.reverse` (Supported) - `array.set` (Supported) - `array.slice` (Supported) - `array.some` (Supported) - `array.sort` (Supported) - `array.sort_indices` (Supported) - `array.standardize` (Supported) - `array.stdev` (Supported) - `array.sum` (Supported) - `array.unshift` (Supported) - `array.variance` (Supported) - `matrix.add_col` (Supported) - `matrix.add_row` (Supported) - `matrix.avg` (Supported) - `matrix.col` (Supported) - `matrix.columns` (Supported) - `matrix.concat` (Supported) - `matrix.copy` (Supported) - `matrix.det` (Supported) - `matrix.diff` (Supported) - `matrix.eigenvalues` (Supported) - `matrix.eigenvectors` (Supported) - `matrix.elements_count` (Supported) - `matrix.fill` (Supported) - `matrix.get` (Supported) - `matrix.inv` (Supported) - `matrix.is_antidiagonal` (Supported) - `matrix.is_antisymmetric` (Supported) - `matrix.is_binary` (Supported) - `matrix.is_diagonal` (Supported) - `matrix.is_identity` (Supported) - `matrix.is_square` (Supported) - `matrix.is_stochastic` (Supported) - `matrix.is_symmetric` (Supported) - `matrix.is_triangular` (Supported) - `matrix.is_zero` (Supported) - `matrix.kron` (Supported) - `matrix.max` (Supported) - `matrix.median` (Supported) - `matrix.min` (Supported) - `matrix.mode` (Supported) - `matrix.mult` (Supported) - `matrix.pinv` (Supported): Moore-Penrose pseudoinverse. - `matrix.pow` (Supported) - `matrix.rank` (Supported) - `matrix.remove_col` (Supported) - `matrix.remove_row` (Supported) - `matrix.reshape` (Supported) - `matrix.reverse` (Supported) - `matrix.row` (Supported) - `matrix.rows` (Supported) - `matrix.set` (Supported) - `matrix.sort` (Supported) - `matrix.submatrix` (Supported) - `matrix.sum` (Supported) - `matrix.swap_columns` (Supported) - `matrix.swap_rows` (Supported) - `matrix.trace` (Supported) - `matrix.transpose` (Supported) - `map.clear` (Supported) - `map.contains` (Supported) - `map.copy` (Supported) - `map.get` (Supported) - `map.keys` (Supported) - `map.put_all` (Supported) - `map.remove` (Supported) - `map.size` (Supported) - `map.values` (Supported) ## Bar states, time, timeframe, session What the script knows about the bar, the chart and the clock. The feed trades 24x7 on UTC. ### barstate.islast (Verified) ```pine barstate.islast ``` true on the last bar on the chart. ### barstate.isconfirmed (Verified) ```pine barstate.isconfirmed ``` true once a bar has closed. Use for signals that must not change. ### barstate.isfirst (Supported) ```pine barstate.isfirst ``` true on the first bar. ### barstate.isrealtime (Supported) ```pine barstate.isrealtime ``` true on bars that formed while the chart was open. ### timeframe.period (Supported) ```pine timeframe.period ``` The chart's timeframe as a Pine string, for example "5" or "15S". ### timeframe.in_seconds (Supported) ```pine timeframe.in_seconds(timeframe) ``` A timeframe string in seconds. ### timeframe.change (Supported) ```pine timeframe.change(timeframe) ``` true on the first chart bar of a new higher-timeframe bar. ### runtime.error (Supported) ```pine runtime.error(message) ``` Stops the script with your message, shown in the console. - `barstate.ishistory` (Supported) - `barstate.islastconfirmedhistory` (Supported) - `barstate.isnew` (Supported) - `timeframe.from_seconds` (Supported) - `timeframe.isdaily` (Supported) - `timeframe.isdwm` (Supported) - `timeframe.isintraday` (Supported) - `timeframe.isminutes` (Supported) - `timeframe.ismonthly` (Supported) - `timeframe.isseconds` (Supported) - `timeframe.isticks` (Supported) - `timeframe.isweekly` (Supported) - `timeframe.main_period` (Supported) - `timeframe.multiplier` (Supported) - `session.isfirstbar` (Supported) - `session.isfirstbar_regular` (Supported) - `session.islastbar` (Supported) - `session.islastbar_regular` (Supported) - `session.ismarket` (Supported) - `session.ispostmarket` (Supported) - `session.ispremarket` (Supported) - `ticker.heikinashi` (Supported) - `ticker.inherit` (Supported) - `ticker.kagi` (Supported) - `ticker.linebreak` (Supported) - `ticker.modify` (Supported) - `ticker.new` (Supported) - `ticker.pointfigure` (Supported) - `ticker.renko` (Supported) - `ticker.standard` (Supported) - `log.error` (Supported) - `log.info` (Supported) - `log.warning` (Supported)