Wintrading

Navy: reference

Navy quick reference

Everything built into Navy on one page: the language, series and variables, inputs, all ta.* functions, math and text, colors, outputs, drawing objects, collections, Wintrading data, limits, errors.

The language at a glance

Everything built in, by namespace, with counts from the compiler's registry: ta.* 51, math.* 21, str.* 11, color.* 19, input.* 8, array, map, line, box and label methods, Wintrading data fields
Everything built in, counted from the compiler's registry.

The editor's hover help and completion show the same entries with parameters and examples.

WriteMeaningMore
//@navy 2.0The first line of every scriptAnatomy
overlay('T', { … }), indicator('T', { … })The declaration, exactly one, right after the first line: on the price chart / in its own panePlacement
const, let, var, varipDeclarations: per bar and fixed; per bar and reassignable; kept from bar to bar; kept between ticks tooVariables
let x: float = na, var l: line = naAn optional type after the nameTypes
x[k], (high - low)[1]The value k bars agoSeries
+ - * / %, == != < <= > >=, && || !, c ? a : b, x ?? yOperators; + also joins strings; &&, ||, ? : are lazy; x ?? y is y where x is naTypes
= += -= *= /= %=Assignment; ++ and -- only in a for headerVariables
if (c) { … } else if (c2) { … } else { … }A condition; c is a boolControl
for (let i = 0; i < n; i++) { … }, while (c) { … }, break, continueLoops; every iteration spends fuelControl
function f(a: float, n: int = 14): float { return … }A function at the top level; each call has its own stateFunctions
const [a, b, c] = ta.macd(close, 12, 26, 9)Several results of a built-inFunctions
type P = { price: float, bar: int }, P.new(…), enum Mode { A, B }Your own record type and choicesCollections
// …, /* … */Comments; ; at the end of a line is optional

Built-in series and variables

NameWhat it isType
open, high, low, closePrices of the bar; close is the last price on the live barfloat
volumeVolume of the barfloat
timeOpen time of the bar, ms since 1970 (UTC)float
bar_indexNumber of the bar: 0 on the first loaded bar, then 1, 2 …int
hl2, hlc3, ohlc4, hlcc4(high + low) / 2, (high + low + close) / 3, (open + high + low + close) / 4, (high + low + 2 × close) / 4float
barstate.isfirstThe first bar of the databool
barstate.islastThe last (live) bar: draw «current state» objects herebool
barstate.ishistoryA closed bar of the historybool
barstate.isrealtimeThe bar that updates with live ticksbool
barstate.isnewThe first run of a barbool
barstate.isconfirmedThe last run of a bar: it has closedbool
syminfo.ticksize, syminfo.mintickThe symbol's tick size, its smallest price move (mintick is Pine's name)float
syminfo.tickerThe chart's symbol, e.g. 'BTCUSDT'string
timeframe.msLength of one bar, msint
na(x)True where x is missingbool
nz(x, replacement = 0)The value, or replacement where it is nafloat
fixnan(x)The last value that was not na (keeps state)float
int(x), float(x)Drops the fraction / the value as a floatint, float
true, false, naConstants

Declaration, inputs, other timeframes

CallWhat it doesGives
indicator(title, { precision, maxBarsBack, fuel, overlay })A script in its own pane (overlay: true puts it on the price chart)
overlay(title, { precision, maxBarsBack, fuel })A script on the price chart
input.int(title, default, { min, max, step, options, tooltip, group })A whole number; with options a drop-downint
input.float(title, default, { min, max, step, options, tooltip, group })A numberfloat
input.bool(title, default, { tooltip, group })A checkboxbool
input.string(title, default, { options, tooltip, group })Text; with options a drop-downstring
input.color(title, default, { tooltip, group })A colorcolor
input.source(title, default, { tooltip, group })A built-in series: close, hl2, ohlc4 …float
input.timeframe(title, default, { tooltip, group })A timeframe such as '1h'string
input.enum(title, default, { tooltip, group })A choice among an enum's membersenum
security(timeframe, () => expression, { lookahead })The expression computed on another timeframe of the chart's coin; no repainting unless lookahead: truefloat, bool
request.security(syminfo.tickerid, timeframe, expression, { lookahead })Pine's form of security(): the chart's symbol onlyfloat, bool

Inputs and their options: Inputs; security(): Other timeframes.

Technical analysis: ta.*

All of them keep state between bars: call them at the top level, on every bar (why). Lengths are constants or inputs. A tuple is unpacked with const [a, b, c] = ….

Moving averages

CallWhat it doesGives
ta.sma(source, length)Simple moving average: the mean of the last length valuesfloat
ta.ema(source, length)Exponential (alpha = 2 / (length + 1))float
ta.rma(source, length)Wilder's (alpha = 1 / length), as in RSI and ATRfloat
ta.wma(source, length)Weighted: linear weights, the newest heaviestfloat
ta.vwma(source, length)Weighted by volumefloat
ta.hma(source, length)Hull moving averagefloat
ta.alma(source, length, offset = 0.85, sigma = 6)Arnaud Legoux moving averagefloat
ta.swma(source)Symmetric weights over the last 4 values (1/6, 2/6, 2/6, 1/6)float
ta.linreg(source, length, offset = 0)Linear regression of the last length values, at offset bars backfloat
ta.vwap(source = hlc3)VWAP, reset at 00:00 UTC every day; also the variable ta.vwapfloat

Oscillators

CallWhat it doesGives
ta.rsi(source, length)Relative strength index, 0…100float
ta.macd(source, fast, slow, signal)MACD: the line, its signal line and the histogram[macd, signal, hist]
ta.stoch(source, high, low, length)Stochastic %K, 0…100float
ta.cci(source, length)Commodity channel indexfloat
ta.cmo(source, length)Chande momentum oscillator, −100…100float
ta.mfi(source, length)Money flow index, 0…100float
ta.mom(source, length)Momentum: source − source[length]float
ta.roc(source, length)Rate of change, %float
ta.tsi(source, shortLength, longLength)True strength index, −1…1float
ta.wpr(length)Williams %R, −100…0float
ta.cog(source, length)Center of gravityfloat
ta.percentrank(source, length)Percent of the previous length values at or below the current onefloat

Volatility and channels

CallWhat it doesGives
ta.tr(handleNa = false)True range; also the variable ta.trfloat
ta.atr(length)Average true range (Wilder's average)float
ta.stdev(source, length)Standard deviation of the last length valuesfloat
ta.variance(source, length)Variance of the last length valuesfloat
ta.dev(source, length)Mean absolute deviation from the SMAfloat
ta.bb(source, length, mult)Bollinger bands[middle, upper, lower]
ta.bbw(source, length, mult)Bollinger band width: (upper − lower) / middlefloat
ta.kc(source, length, mult, useTrueRange = true)Keltner channels (around an EMA)[middle, upper, lower]
ta.kcw(source, length, mult, useTrueRange = true)Keltner channel width: (upper − lower) / middlefloat

Trend

CallWhat it doesGives
ta.dmi(diLength, adxSmoothing)Directional movement: +DI, −DI and ADX[plusDI, minusDI, adx]
ta.sar(start, inc, max)Parabolic SARfloat
ta.supertrend(factor, atrPeriod)Supertrend line and direction (< 0 up, > 0 down)[line, direction]

Windows, sums and volume

CallWhat it doesGives
ta.highest(source, length)Highest of the last length values, this bar includedfloat
ta.lowest(source, length)Lowest of the last length values, this bar includedfloat
ta.highestbars(source, length)Offset (0 or negative) to the bar with the highest valueint
ta.lowestbars(source, length)Offset (0 or negative) to the bar with the lowest valueint
ta.change(source, length = 1)source − source[length]float
ta.sum(source, length)Sum of the last length valuesfloat
ta.cum(source)Running total since the first barfloat
ta.obv()On-balance volume; also the variable ta.obvfloat

Events and pivots

CallWhat it doesGives
ta.cross(a, b)a crossed b on this bar, either waybool
ta.crossover(a, b)a crossed above b (was ≤, now >)bool
ta.crossunder(a, b)a crossed below b (was ≥, now <)bool
ta.rising(source, length)Above each of its previous length valuesbool
ta.falling(source, length)Below each of its previous length valuesbool
ta.barssince(condition)Bars since the condition was last true (na before it first was)int
ta.valuewhen(condition, source, occurrence = 0)source on the bar where the condition was true, occurrence times back (0: the latest)float
ta.pivothigh(source, leftbars, rightbars)The pivot high, reported rightbars bars after it, na elsewhere; its bar is bar_index - rightbarsfloat
ta.pivotlow(source, leftbars, rightbars)The pivot low, the same wayfloat

Math and text: math.*, str.*

CallWhat it doesGives
math.abs(x)Absolute valuefloat
math.sqrt(x)Square rootfloat
math.pow(base, exponent)base to the power exponentfloat
math.exp(x)e to the power xfloat
math.log(x), math.log10(x)Natural and base-10 logarithmfloat
math.floor(x), math.ceil(x)Down and up to a whole numberint
math.round(x, precision = 0)Rounds to precision decimals; the result is a floatfloat
math.sign(x)−1, 0 or 1float
math.min(a, b, …), math.max(a, b, …), math.avg(a, b, …)The smallest, the largest, the mean of the argumentsfloat
math.sin(x), math.cos(x), math.tan(x), math.asin(x), math.acos(x), math.atan(x)Trigonometry, in radiansfloat
math.pi, math.eConstantsfloat
CallWhat it doesGives
str.tostring(x, format = -1)A number as text; format: decimals (−1: as needed), Pine's '#.##', format.mintick, format.percent, format.volumestring
str.format('{0} at {1}', a, b)Text with {0}, {1} … replaced by the arguments; {0,number,#.##} with a patternstring
str.length(s)Number of charactersint
str.contains(s, part), str.startswith(s, part), str.endswith(s, part)part is in s / at its start / at its endbool
str.upper(s), str.lower(s)Upper and lower casestring
str.substring(s, begin, end?)The part from begin up to (not including) endstring
str.replace(s, target, replacement)Every target replaced by replacementstring
str.tonumber(s)The number written in s, or nafloat

Colors

CallWhat it doesGives
color.rgb(r, g, b, a = 1)A color from red, green, blue (0…255) and opacity a (0…1)color
color.new(color, alpha)The color with opacity alpha: 0 invisible … 1 solid (above 1: Pine's transparency in %)color
color.red, color.green, color.blue, color.orange, color.yellow, color.purple, color.fuchsia, color.aqua, color.teal, color.lime, color.maroon, color.navy, color.olive, color.silver, color.gray, color.white, color.blackNamed colorscolor
'#rrggbb', '#rrggbbaa'A hex string where a color is expectedcolor

Note the opacity: Colors.

Outputs

Top level only, up to 64. Per bar: the colors of plot, fill, bgcolor and markers, and the values. Constants: plot width and style, hline options, marker text, shape, size and text color, titles, alert messages.

CallWhat it doesGives
plot(series, { title, color, width, style, base, colorDown })Draws a series. style: 'line', 'step', 'columns', 'histogram', 'area', 'circles', 'cross'a handle
hline(price, { title, color, width, style })A level at a constant value; style: 'solid', 'dashed', 'dotted'a handle
fill(a, b, { title, color, topValue, bottomValue, topColor, bottomColor })Fills between two plots or hlines; a per-bar color draws a cloud, the top/bottom options a vertical gradient
bgcolor(color, { title })The bar's background across the pane; na leaves it clear
marker.above(condition, 'text', { color, shape, size, textColor, title })A shape (and text) over the high of the bars where the condition holds
marker.below(condition, 'text', { … })The same under the low
marker.at(price, 'text', { … })A shape at a price, on the bars where it is not na
alert(condition, 'message', { freq, title })An alert on live bars; freq: 'bar', 'close', 'all'
alertcondition(condition, 'Title', 'message')A condition for the alerts dialog; silent in Wintrading for now

Drawing objects: line, box, label

x is a bar index (xloc: 'time' — a time in ms), y a price. Everything about an object may change per bar; a method on an na handle does nothing and reads na. Up to 500 of each kind.

CallWhat it doesGives
line.new(x1, y1, x2, y2, { color, width, style, extend, xloc })A line; style: 'solid', 'dashed', 'dotted'; extend: 'none', 'right', 'left', 'both'line
box.new(left, top, right, bottom, { color, borderColor, borderWidth, borderStyle, extend, text, textColor, textSize, xloc })A rectangle; color is its fillbox
label.new(x, y, text, { style, color, textColor, size, xloc })A label; style: 'down' (a plate above the point), 'up', 'left', 'right', 'center', 'none' (text only)label
line.all, box.all, label.allThe script's objects on the chart, oldest first (a copy)array
MethodsWhat they doOf
set(x1, y1, x2, y2), setXY1(x, y), setXY2(x, y), setX1, setY1, setX2, setY2Move the pointsline
setColor, setWidth, setStyle, setExtendChange the lookline
x1(), y1(), x2(), y2(), priceAt(x)Read the points; priceAt — the price of the (extended) line at a bar: a trendline break is close > l.priceAt(bar_index)line
set(left, top, right, bottom), setLeftTop, setRightBottom, setLeft, setTop, setRight, setBottomMove the edgesbox
setColor, setBorderColor, setBorderWidth, setBorderStyle, setExtend, setText, setTextColor, setTextSizeChange the look and the textbox
left(), top(), right(), bottom()Read the edgesbox
setXY(x, y), setX, setYMove itlabel
setText, setColor, setTextColor, setStyle, setSizeChange the text and the looklabel
x(), y(), text()Read itlabel
delete(), copy()Remove it from the chart; a new object like itall three

Pine's forms are accepted: line.set_xy1(l, x, y), label.set_text(lb, s), line.style_dashed, label.style_label_down, extend.right, size.small, xloc.bar_time.

Collections: array, map

CallWhat it doesGives
array.new<T>(size = 0, init)A list of size elements equal to init; T is a number, bool, color, string, a drawing object or your typearray
array.from(a, b, …)A list of these values; its type comes from them (whole numbers with fractions make floats)array
array.new_float, array.new_int, array.new_bool, array.new_string, array.new_color, array.new_line, array.new_box, array.new_labelPine's forms of array.newarray
map.new<K, V>()An empty dictionary; keys are int or stringmap
MethodsWhat they doOf
get(i), set(i, x), first(), last()Read and replace elements (0 is the first)array
push(x), pop(), unshift(x), shift(), insert(i, x), remove(i), clear()Add and remove: at the end, at the start, at a positionarray
size(), includes(x), indexOf(x), lastIndexOf(x)Size and search (−1: not found)array
slice(from, to), copy(), reverse(), sort('asc'), fill(x), join(sep)Copy, order, fill, join into textarray
sum(), avg(), min(), max(), stdev(), median()Statistics of numbers (na skipped)array
get(key), put(key, value), has(key), remove(key), clear(), size(), keys(), values(), copy()Values by key (get of a missing key is na)map

Methods are called on the value (a.push(x)) or, as in Pine, through the namespace (array.push(a, x)).

Wintrading data

Columns (vol, liq, oi, fp, book) are per bar with history; walls is a live list (i from 0 to walls.size() - 1). na where there is no data. Where each one has data: Scripts → Data.

NameWhat it isUnit
vol.buy, vol.sellAggressive buy / sell volume of the bar (market orders)coins
vol.deltavol.buy − vol.sellcoins
liq.long, liq.shortLongs (forced sells) / shorts (forced buys) liquidated in the bar; final once the next bar opens$
liq.totalliq.long + liq.short$
oi.open, oi.high, oi.low, oi.closeOpen interest at the bar's open, its high and low within the bar, at its closecoins
oi.deltaoi.close − oi.open: positions opened (> 0) or closed (< 0)coins
oi.usdoi.close × close$
fp.buy, fp.sellAggressive buys / sells from the bar's clusterscoins
fp.delta, fp.volumefp.buy − fp.sell, fp.buy + fp.sellcoins
fp.pocThe price where the bar traded the most volumeprice
book.bid, book.askResting within 1% below / above the bar's close$
book.imbalance(bid − ask) / (bid + ask), from −1 (all asks) to 1 (all bids)−1 … 1
book.bidWall, book.askWallPrice of the largest bid / ask levelprice
book.bidWallSize, book.askWallSizeIts size$
walls.size()Number of densities now (0: none, or the symbol is not tracked)count
walls.price(i), walls.usd(i)Price and size of density iprice, $
walls.side(i)1 — a bid (below the price), −1 — an ask (above it)±1
walls.age(i)Minutes since it appearedmin
walls.dist(i)Distance from the current price, always ≥ 0%

Limits and error codes

WhatLimit
The code of one script256 KB
Outputs: plot, hline, fill, bgcolor, markers, alerts64
Lines, boxes, labels (past that the oldest goes first)500 of each
Text of one object4 096 characters
Loop iterations per bar (fuel)1 000 000, up to 10 000 000
History x[k], lengths of ta.*20 000 bars
Array, map, string100 000 / 50 000 pairs / 100 000 characters
Time to run the whole history, one update3 s, 250 ms
Candles of another timeframe5000 bars, 3000 for seconds

The editor reports problems as CODE line:column message; the most common:

MeansWhat to doCode
The first line is not //@navy 2.0 — or the code is TradingView Pine ScriptStart with //@navy 2.0; port Pine with AINV1001
Unexpected textAlmost always Pine syntax: :=, name=value, switchNV1020, NV1021
A Pine named argument: title='EMA'Options in an object: { title: 'EMA' }NV1022
:=, f(x) =>, if cond, for … to, and / or / not=, function, if (cond), a C-style for, && / || / !NV1023–NV1027
No declaration, or more than oneExactly one overlay(…) or indicator(…) after the first lineNV2001, NV2002
Unknown nameThe message suggests the closest one; a first use needs let / const / varNV2003
An output inside a blockTop level, with a conditional value: plot(cond ? x : na)NV2005
Wrong number of arguments, an unknown optionCheck the signature hereNV2010, NV2011
Incompatible typesA number to text: str.tostring(x); to an int: int(x); an input's title comes firstNV2100
The condition is not a boolCompare: x > 0, !na(x)NV2101
Must be a constant or an inputA length of ta.*: a number, an input or + - * of themNV2201
Must be a constantMarker text, plot width and style, hline options, titles, alert messagesNV2202
Assigning to a const; a name declared twiceUse let or var; rename oneNV2301, NV2302
No history hereAssign the call or the block variable to a top-level const firstNV2403
A function reads a top-level seriesPass it as a parameterNV2502
security() reads the chart's variable or dataCompute it inside the arrowNV2505
ta.* in a branch (a warning)Move the call to a top-level constNV3001
A loop ran out of fuel; too slowBound the loop; fewer nested loops over historyNV4001, NV4005
An index outside the array; a method on an na arrayCheck size(); create it first: var a = array.new<float>(0)NV4003, NV4007