Docs

Deepwick Script reference

Deepwick Script is the language of Deepwick's charts and backtests. It runs a subset of Pine Script: most ta.*, math.*, str.*, input.*, plot* and strategy.* functions run as-is, and unsupported lines are flagged with line and column. This page lists everything the engine supports today and what it does not.

New to Deepwick? Start with the step-by-step guide: How to backtest a Pine Script strategy for free.

Building an AI assistant that writes Deepwick Script? This reference as one Markdown document.

Updated:

Language

Deepwick Script runs a subset of Pine Script, including enums, user-defined types, methods and maps; the //@version line is not enforced. A script runs once per bar, from the oldest bar to the newest, and every variable keeps its history.

SyntaxWhat it does
x = expr / x := exprDeclare a variable, then reassign it with :=. An optional type (int, float, bool, string, color, series, simple, const, line, label) may precede the name.
var / varipInitialise once on the first bar and keep the value across bars. varip behaves like var, since scripts run on closed bars.
x[n]History operator: the value of x n bars ago (na before the first bar).
if / elseConditional blocks, indented by four spaces. if can also be used as an expression.
cond ? a : bTernary operator.
switchMulti-way branch, with or without a value to match.
for i = a to b [by step]Counted loop. break and continue are supported.
while condLoop while a condition holds.
f(x, y) => exprUser-defined function, on one line or as an indented block whose last expression is returned. Each call site keeps its own ta.* state, as in Pine.
[a, b] = f()Tuples: functions can return several values, and built-ins like ta.macd() and ta.bb() do.
and / or / notLogical operators. Arithmetic: + - * / %; comparison: == != < <= > >=.
iff(cond, a, b)Pine v4's conditional, which Pine v5 replaced with the ternary. TradingView still runs v4 scripts, so we do too: iff(cond, a, b) is exactly cond ? a : b.

Declarations

SyntaxWhat it does
indicator(title, shorttitle, overlay, precision)Declares an indicator: it draws on the chart and has nothing to backtest. study() is accepted as an alias.
strategy(title, overlay, initial_capital, default_qty_type, default_qty_value, commission_type, commission_value, slippage, pyramiding)Declares a strategy. Defaults: initial_capital 1000000, 1 contract per order, commission 0, slippage 0 ticks, pyramiding 1. Other arguments, such as calc_on_order_fills, are ignored. With process_orders_on_close the market orders fill at the close of the bar that issued them.
library(title)Declares a library: a script whose definitions are published and can be used by other scripts. The definitions it exports are marked with export.

Inputs

Inputs appear next to the editor and in the indicator's settings, so you can change them without touching the code.

SyntaxWhat it does
input.int(defval, title, minval, maxval, step)Whole number.
input.float(defval, title, minval, maxval, step)Decimal number.
input.bool(defval, title)Checkbox.
input.string(defval, title, options)Text, or a list of options.
input.session(defval, title)A trading session like "0930-1600", or days like "23456". Feed it to session.ismarket() and the other session.* predicates.
input.source(defval, title)A price source: open, high, low, close, hl2, hlc3, ohlc4 or hlcc4.
input.color(defval, title)Colour picker.
input(defval, title)Generic input; the type follows the default value.
input.timeframe()The chart's timeframe, as an input.
input.enum(defval, title, options), input.price(defval, title), input.symbol(defval, title), input.text_area(defval, title), input.time(defval, title)The inputs that are not a number: a choice between options, a price, a symbol, a block of text, and a date and time.

Bar data and time

Times are UTC milliseconds. hour() and the other time functions take an optional time; hour() also takes a time zone from a fixed list of offsets, without daylight saving.

SyntaxWhat it does
open, high, low, close, volumePrices and volume of the current bar.
hl2, hlc3, ohlc4, hlcc4Common price averages.
bar_index, last_bar_indexIndex of the current bar (0 is the oldest) and of the last bar.
time, time_closeOpen and close time of the bar. As functions — time("D"), time(timeframe.period, "0000-0900:23456", "UTC") — the start (or end) of the higher-timeframe bar that holds this one, or na when the bar is outside the session. Sessions: "HHMM-HHMM", overnight ones too, comma-separated windows, optional days after a colon (1 = Sunday … 7 = Saturday), "24x7".
timeframe.change(timeframe)True on the first bar of each new period, e.g. timeframe.change("D") on the first bar of every day (weeks start on Monday).
timestamp(timezone?, year, month, day, hour, minute, second)A time in milliseconds from its parts, or from a date string: timestamp("2026-01-05T09:30:00Z").
max_bars_back(series, length)Pine uses it to ask the engine to keep that much history of a variable. Deepwick sizes the history as the script runs, so the call changes nothing: what matters is that a script that uses it compiles and its history is there.
dayofweek.sunday … dayofweek.saturdayDay constants to compare with dayofweek (1 … 7).
session.ismarket, isfirstbar, islastbar, ispremarket, ispostmarketSession state. Markets here trade around the clock, so every bar is in the market session; isfirstbar / islastbar mark the first and last bar of each UTC day.
year, month, weekofyear, dayofmonth, dayofweek, hour, minute, secondCalendar parts of the bar's time; also callable with a time, e.g. hour(time, "America/New_York"). dayofweek: 1 = Sunday … 7 = Saturday.
barstate.isfirst, islast, isnew, isconfirmed, ishistory, isrealtimeWhere the script is in the bar history.
timeframe.period, multiplier, isintraday, isdaily, isweekly, ismonthlyThe chart's timeframe.
timeframe.in_seconds(period)Seconds in a timeframe: a bare number is minutes, D a day, W a week, M a month.
syminfo.ticker, tickerid, mintick, pointvalueThe chart's symbol, its price step and its point value.
syminfo.prefix, main_tickerid, description, currency, basecurrency, root, typeWhat the instrument is: the exchange prefix (empty here, our symbols carry none), its description, the currency it is quoted in, the one it is quoted against, and what kind of instrument it is.
syminfo.mincontract, minmove, pricescale, session, timezone, volumetype, countryThe instrument's contract size, tick step, price scale, session, time zone, volume type and country.
barstate.isfirst, islast, isnew, isconfirmed, ishistory, isrealtime, islastconfirmedhistoryWhere the script is running: the first bar, the last one, the realtime bar, and the last bar the market has confirmed.
timeframe.main_period, timeframe.isdwm, timeframe.isminutes, timeframe.isseconds, timeframe.isticksThe chart's own resolution: its period, and whether it is daily, weekly or monthly, in minutes, in seconds, or in ticks.
timeframe.from_seconds(seconds)The Pine timeframe that covers that many seconds, rounding up to the next one that exists.
chart.is_standard, chart.is_heikinashi, chart.is_renko, chart.is_kagi, chart.is_pnf, chart.is_linebreak, chart.is_range, chart.is_pointfigureWhat kind of chart this is. Ours is always the standard one, so the first is true and the rest are false.
chart.bg_color, chart.fg_colorThe colours of the chart's background and foreground.
chart.left_visible_bar_time, chart.right_visible_bar_timeThe time of the leftmost and rightmost bar on screen. The engine does not know which window is being watched, so they are na.
session.isfirstbar_regular, session.islastbar_regularThe first and the last bar of the trading day.
syminfo.isinThe symbol's ISIN, the 12-character code of a security. Crypto pairs, forex and metals have none, so it is an empty string.
aggressor_side, aggressor.buy, aggressor.sellWhich side took the trade: aggressor.buy (1) or aggressor.sell (2). Pine fills it only on the 1T tick timeframe; charts here are bars, so it is na.
last_bar_time, timenow, time_tradingday, ask, bidThe time of the last bar of the chart, the wall clock, the beginning of the trading day, and the best offer and demand. Without a tick feed the last two are na.
currency.*The currencies, as their codes.
position.*The nine places of the grid where a table anchors itself.
display.*Where an indicator is added: on the price scale, in a panel, in the status line, in the data window, or nowhere.
scale.*Which side of the chart an indicator's scale sits on.
backadjustment.*Whether the price history is adjusted for splits.
splits.*How the history of splits is asked for.
settlement_as_close.*Whether the liquidation price uses the close of the session.
font.family_default, font.family_monospaceThe families of letter.
text.format_none, text.format_bold, text.format_italic, text.wrap_none, text.wrap_autoBold, italic, and the two ways of wrapping a text.
format.price, format.percent, format.volume, format.mintick, format.inheritHow the values of an indicator are shown: as a price, as a percent, as a volume, by the price tick, or as the script says.
math.phi, math.rphiThe golden ratio and its conjugate.
syminfo.target_price_*, syminfo.recommendations_*The analyst data a data vendor would carry. We have no such feed, so these are na rather than a number that looks like one.

Technical analysis (ta.*)

Every call site keeps its own state, as in Pine: two ta.ema() calls on different lines are two independent averages. Results are na until enough bars exist.

SyntaxWhat it does
ta.sma(source, length)Simple moving average.
ta.ema(source, length)Exponential moving average.
ta.rma(source, length)Wilder's moving average, used by RSI and ATR.
ta.wma(source, length)Weighted moving average.
ta.vwma(source, length)Volume-weighted moving average.
ta.hma(source, length)Hull moving average.
ta.linreg(source, length, offset)Linear regression line value.
ta.vwap(source)Volume-weighted average price, restarting at 00:00 UTC each day.
ta.rsi(source, length)Relative Strength Index, 0 to 100.
ta.macd(source, fastlen, slowlen, siglen)Returns [macd, signal, histogram].
ta.stoch(source, high, low, length)Stochastic %K, 0 to 100.
ta.cci(source, length)Commodity Channel Index.
ta.mfi(series, length)Money Flow Index.
ta.wpr(length)Williams %R, -100 to 0.
ta.dmi(diLength, adxSmoothing)Returns [+DI, -DI, ADX].
ta.supertrend(factor, atrPeriod)Returns [supertrend, direction]; direction is -1 in an uptrend and 1 in a downtrend.
ta.sar(start, inc, max)Parabolic SAR.
ta.mom(source, length)Momentum: source minus source length bars ago.
ta.roc(source, length)Rate of change, in percent.
ta.change(source, length)Difference from length bars ago (1 by default).
ta.tr / ta.tr(handle_na)True range.
ta.atr(length)Average true range (Wilder).
ta.bb(series, length, mult)Bollinger Bands: returns [middle, upper, lower].
ta.bbw(series, length, mult)Bollinger Band width: (upper - lower) / middle.
ta.kc(series, length, mult)Keltner Channels: returns [middle, upper, lower], with an EMA of the true range.
ta.stdev(source, length, biased)Standard deviation.
ta.variance(source, length, biased)Variance.
ta.dev(source, length)Mean absolute deviation.
ta.median(source, length)Median.
ta.highest(source, length) / ta.highest(length)Highest value over length bars (the high by default).
ta.lowest(source, length) / ta.lowest(length)Lowest value over length bars (the low by default).
ta.highestbars(source, length)Offset to the highest value: 0 or negative.
ta.lowestbars(source, length)Offset to the lowest value: 0 or negative.
ta.rising(source, length)True if source is above each of its previous length values.
ta.falling(source, length)True if source is below each of its previous length values.
ta.crossover(source1, source2)True on the bar where source1 crosses above source2.
ta.crossunder(source1, source2)True on the bar where source1 crosses below source2.
ta.cross(source1, source2)True on a cross in either direction.
ta.pivothigh(source, leftbars, rightbars)The pivot high price, known rightbars bars after the pivot; na otherwise. The source is optional (the high by default).
ta.accdist()Accumulation/distribution: the money that moved into each bar, added to a running total.
ta.alma(series, length, offset, sigma)Arnaud Legoux moving average: a Gaussian window over the last `length` bars. A high `offset` leans on the recent bars.
ta.cmo(series, length)Chande momentum oscillator: 100 × (gains − losses) / (gains + losses) over the last `length` bars.
ta.cog(source, length)Centre of gravity of the last `length` bars; the most recent bar carries the least weight.
ta.correlation(source1, source2, length)Pearson correlation of two series over the last `length` bars.
ta.iii()Intraday intensity of the bar: where the close sits between the high and the low, scaled by the volume.
ta.kcw(series, length, mult)Width of the Keltner channel over its middle line.
ta.max(source, length)The highest value: with one argument the all-time high, with a length the highest of the last `length` bars.
ta.min(source, length)The lowest value: with one argument the all-time low, with a length the lowest of the last `length` bars.
ta.mode(source, length)The most frequent value of the last `length` bars; on a tie, the smallest one.
ta.nvi()Negative volume index: it moves only on the bars whose volume falls.
ta.obv()On balance volume: the volume of each bar, signed by the direction of the close.
ta.percentile_linear_interpolation(source, length, percentage)The percentile of the last `length` bars, read between the two ranks that straddle it; the result need not be a value of the series.
ta.percentile_nearest_rank(source, length, percentage)The percentile of the last `length` bars, taken from a whole rank; the result is always a value of the series.
ta.pivot_point_levels(type, anchor)The pivot levels of the period that just ended (P, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5). The type is "Traditional", "Fibonacci", "Woodie", "Classic", "DM" or "Camarilla".
ta.pvi()Positive volume index: it moves only on the bars whose volume rises.
ta.pvt()Price volume trend: the percentage change of the close weighted by the volume.
ta.range(source, length)The difference between the highest and the lowest of the last `length` bars.
ta.rci(source, length)Rank correlation index: Spearman's rho of the source against the bar index, scaled to −100…100.
ta.swma(source)Symmetrically weighted moving average over four bars, with the weights 1/6, 2/6, 2/6 and 1/6.
ta.tsi(source, short_length, long_length)True strength index: the momentum smoothed twice over the absolute momentum, between −1 and 1.
ta.wad()Williams accumulation/distribution: the distance the close travelled inside each bar, added to a running total.
ta.wvad()Williams variable accumulation/distribution: where the close sits inside the bar, weighted by the volume.
sma, ema, rma, wma, vwma, hma, alma, linreg, vwap, rsi, macd, stoch, cci, mfi, wpr, dmi, supertrend, sar, mom, roc, change, atr, bb, bbw, kc, variance, dev, median, highest, lowest, highestbars, lowestbars, rising, falling, crossover, crossunder, cross, pivothigh, pivotlow, valuewhen, cum, percentrank, range, correlation, mode, tsi, cog, kcw, swma, rci, barssince, cmo, wad, wvadThe globals of Pine v5: the same functions without the ta. prefix. Pine v6 took them away, but the scripts written for v5 still use them, and here they run too.
tr, accdist, nvi, obv, pvi, pvtThe globals that were variables in Pine v5. They are the same series as their ta.* counterparts.
ta.pivotlow(source, leftbars, rightbars)The pivot low price, known rightbars bars after the pivot; na otherwise. The source is optional (the low by default).
ta.valuewhen(condition, source, occurrence)Value of source on the occurrence-th most recent bar where condition was true.
ta.barssince(condition)Bars since condition was last true.
ta.cum(source)Running total since the first bar.
ta.percentrank(source, length)The percentage (0 to 100) of the PREVIOUS `length` values that were less than or equal to the current value. The current bar is not part of its own comparison set, so the result is na until `length` previous bars exist. This is how a strategy ranks the current volatility against its own recent history: `ta.percentrank(realisedVol, 160)` is the volatility percentile, and trading only between two percentiles keeps the trades inside a normal volatility regime.

Other timeframes (request.*)

A higher timeframe is built from the chart's own bars, so it needs no data the engine does not have. The value of a higher-timeframe bar only becomes visible on the chart bar AFTER it closed: a 4h bar is never readable from inside itself, which is what keeps a backtest honest.

SyntaxWhat it does
request.security(symbol, timeframe, expression)Runs expression on a higher timeframe of the SAME symbol and returns the last CLOSED value. Works on the chart's own symbol (or syminfo.tickerid, or an empty symbol); another symbol returns na, because the engine only ever holds the chart's bars. Timeframes accept Pine's notation ("60", "240", "D", "W", "M") and Deepwick's ("1h", "4h", "1d"). The expression may be a ta.* call, which is evaluated over the higher-timeframe series. Returns na until one such bar has closed.
request.security_lower_tf(symbol, timeframe, expression)The values the chart's bar was made of, on a lower timeframe. The engine holds the bars of the chart's own timeframe and no intrabar feed, so this returns na.
ticker.new(prefix, ticker, session, adjustment), ticker.modify(id, session, adjustment)Build the identifier that request.security() then asks for. A ticker id is a symbol plus its modifiers.
ticker.heikinashi(id), ticker.standard(id), ticker.inherit(from, symbol)Ask for the same symbol in Heikin-Ashi, in the standard chart, or with the modifiers of another ticker. Heikin-Ashi is a transformation of the bars: the close is the average of the four prices, the open the average of the previous open and close.
request.security(..., lookahead)Accepted and ignored. lookahead_on would let a backtest read the forming higher-timeframe bar, which is lookahead; the engine never peeks. gaps only affects intrabar plotting, which does not apply here.

Strategies (strategy.*)

Market orders fill at the next bar's open. Stop and limit orders fill along the bar: open, then the extreme nearer the open, then the other extreme, then close. If price gaps through an order, it fills at the open. Commission is charged on every fill; slippage applies to market and stop fills.

SyntaxWhat it does
strategy.entry(id, direction, qty, limit, stop, comment)Open or add to a position; market order unless limit or stop is given.
strategy.order(id, direction, qty, limit, stop, comment)Same arguments as strategy.entry().
strategy.exit(id, from_entry, qty_percent, profit, limit, loss, stop, trail_points, trail_offset, comment)Take-profit, stop-loss and trailing stop for an entry: profit and loss in ticks, limit and stop as prices. trail_points is the distance in TICKS from the best price reached; trail_offset is the profit in ticks that must be cleared before the trailing stop arms. The stop only ever ratchets in your favour and moves on CLOSED bars, so a bar can never fill the stop that its own high set.
strategy.close(id, comment, qty_percent)Close an entry at market on the next bar.
strategy.close_all(comment)Close every open position.
strategy.cancel(id) / strategy.cancel_all()Cancel pending orders.
strategy.position_size, position_avg_priceCurrent position (positive long, negative short) and its average price.
strategy.opentrades.entry_bar_index(n), entry_price, entry_time, entry_id, size, profit, commission, max_runup, max_drawdownDetails of open trade n (0 = oldest); na if there's no such trade. size is negative for shorts. E.g. exit after 10 bars: bar_index - strategy.opentrades.entry_bar_index(0) >= 10.
strategy.closedtrades.entry_bar_index(n), exit_bar_index, entry_price, exit_price, entry_time, exit_time, entry_id, size, profit, commission, max_runup, max_drawdownDetails of closed trade n (0 = oldest; the last one is strategy.closedtrades - 1).
strategy.equity, netprofit, openprofit, grossprofit, grossloss, initial_capitalAccount figures.
strategy.closedtrades, opentrades, wintrades, losstradesTrade counts.
strategy.long, strategy.shortDirections.
strategy.fixed, strategy.cash, strategy.percent_of_equityValues for default_qty_type.
strategy.commission.percent, cash_per_order, cash_per_contractValues for commission_type.
strategy.oca.none, cancel, reduceWhat happens to the other orders of a group when one of them fills.
strategy.direction.all, long, shortThe direction filters the order functions accept.
strategy.risk.allow_entry_in(direction), max_position_size(value, type), max_intraday_loss(value, type), max_drawdown(value, type), max_cons_loss_days(count), max_intraday_filled_orders(count)The rules the strategy sets on itself: only enter in one direction, never hold more than a given size, never lose more than a given amount in a day or in total, stop after a number of losing days in a row, or place at most a number of orders a day. When a rule is reached the pending orders are cancelled, the open positions are closed and no new order is placed.
strategy.convert_to_account(value), strategy.convert_to_symbol(value)Convert a value between the symbol's currency and the account's. Without a currency feed there is nothing to convert, so the value comes back unchanged.
strategy.margin_liquidation_priceThe price at which a leveraged account would be liquidated. We do not simulate leverage, so it is na.
strategy.default_entry_qty(fill_price)The size an entry would have if it filled at that price. A script may also assign to it, and then that value is the one every entry gets.
strategy.netprofit_percent, openprofit_percent, grossprofit_percent, grossloss_percent, avg_trade, avg_trade_percentThe account figures in percent of the initial capital.
strategy.avg_winning_trade, avg_winning_trade_percent, avg_losing_trade, avg_losing_trade_percentThe average result of the trades that won and of the ones that lost.
strategy.max_drawdown, max_drawdown_percent, max_runup, max_runup_percentHow deep the equity fell below its peak, and how high it rose above its floor. Read from the same equity curve the report draws.
strategy.max_contracts_held_all, max_contracts_held_long, max_contracts_held_shortThe largest position the strategy ever held, in contracts.
strategy.eventrades, strategy.position_entry_name, strategy.account_currencyOpen plus closed trades, the id of the entry that opened the position, and the currency of the account.
strategy.opentrades.entry_comment(n), profit_percent, capital_held, max_runup_percent, max_drawdown_percentThe rest of an open trade: its comment, its result in percent, the capital it holds and its excursions in percent.
strategy.closedtrades.entry_comment(n), exit_comment(n), exit_id, profit_percent, max_runup_percent, max_drawdown_percent, first_indexThe rest of a closed trade: the comment and id of the order that closed it, its result in percent, its excursions in percent, and the number of the oldest trade in the list.

Plots and alerts

SyntaxWhat it does
plot(series, title, color, linewidth, style, ..., linestyle)Draw a series on the chart or in a pane.
plotshape(series, title, style, location, color, text)Draw a shape on bars where series is true.
plotchar(series, title, char, location, color)Draw a character on bars where series is true.
plotarrow(series, title, colorhead, colorbody, location)An arrow on the bars where the series is not na: up when the value is positive, down when it is negative.
plotbar(series, title, color)A bar from the zero line to the value of the series.
plotcandle(open, high, low, close, title, color)A candle drawn from four prices: the wick and the body.
hline(price, title, color, linestyle)Horizontal line at a fixed level.
fill(plot1, plot2, color)Fill between two plots or two hlines.
bgcolor(color)Colour the background of the bar.
barcolor(color)Colour the bar itself.
alertcondition(condition, title, message)Declare a condition you can turn into an alert by email, Telegram, Discord or webhook.
alert(message, freq)Fire an alert with a message. The frequency tells it how often it may fire: alert.freq_once_per_bar_close (the default), alert.freq_once_per_bar or alert.freq_all. In a backtest there is one tick per bar, so all three fire on every bar.
alert.freq_*The frequencies alert() takes.
plot.style_*line, linebr, stepline, stepline_diamond, histogram, columns, circles, cross, area, areabr, steplinebr.
plot.linestyle_*solid, dashed, dotted. The linestyle argument of plot() picks the stroke of the line it draws: it applies to the styles that draw a line (line, linebr, stepline, stepline_diamond and area), and the other styles ignore it.
hline.style_*solid, dashed, dotted.
shape.*triangleup, triangledown, arrowup, arrowdown, circle, xcross, cross, diamond, square, flag, labelup, labeldown.
location.*abovebar, belowbar, top, bottom, absolute.
size.*auto, tiny, small, normal, large, huge. Accepted, but shapes are drawn at one size.

Lines, boxes, labels and tables

SyntaxWhat it does
line.new(x1, y1, x2, y2, xloc, extend, color, style, width)Draw a line between two bar indexes and prices; returns its id. The arguments are in Pine's order. extend.right makes the line a ray that goes on past its second point, extend.both a full line through both points.
line.set_x1, set_y1, set_x2, set_y2, set_xy1, set_xy2, set_color, set_style, set_width, set_extendChange a line. set_extend changes how far it continues past its ends.
line.get_x1, get_x2, get_y1, get_y2, get_price(id, bar)Read a line. get_price gives the price the line has at a bar index, as if it were drawn with extend.both.
line.set_first_point(id, x, y), line.set_second_point(id, x, y), line.set_xloc(id, x1, x2, xloc)Move a line's ends. set_xloc sets both x values and where they live: a bar index or a bar time.
line.copy(id)A copy of a line, with its own id.
line.allThe array of every line the script has drawn.
line.delete(id)Remove a line.
linefill.new(line1, line2, color)Fill the area between two lines; returns its id. This is how a channel or a band is drawn when its edges are not horizontal.
linefill.get_line1(id), linefill.get_line2(id), linefill.set_color(id, color), linefill.delete(id)Read, recolour and remove a fill.
linefill.allThe array of every fill between two lines the script has drawn.
box.new(left, top, right, bottom, border_color, bgcolor, extend)Draw a rectangle; returns its id.
box.set_left, set_top, set_right, set_bottom, set_bgcolor, set_border_color, set_extendChange a box.
box.delete(id)Remove a box.
line.style_*, box.style_*solid, dashed, dotted, and the three arrow heads a line can wear.
extend.*none, left, right, both.
label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip)Put a text label on the chart; returns its id. The anchor is a bar index (xloc.bar_index) or a price (xloc.price), and it rides above or below the bar with yloc.
label.set_*, label.get_*, label.deleteChange, read and remove a label.
table.new(position_left, position_top, columns, rows, bgcolor, frame_color, frame_width, border_color, border_width)Create a table on the chart; returns its id. The position is in panel pixels, like Pine's.
label.copy(id), label.allA copy of a label with its own id, and the array of every label the script has drawn.
label.set_point(id, x, y), label.set_xloc(id, xloc), label.set_yloc(id, yloc), label.set_textalign(id, align)Move a label to another bar or price, anchor it to a time or to a price, and align its text.
label.set_text_formatting(id, format), label.set_text_font_family(id, family)Bold, italic, and the family of letter a label's text uses.
box.copy(id), box.all, box.get_left(id), box.get_top(id), box.get_right(id), box.get_bottom(id)A copy of a box, the array of every box, and its four corners.
box.set_lefttop(id, left, top), box.set_top_left_point(id, x, y), box.set_rightbottom(id, right, bottom), box.set_bottom_right_point(id, x, y)Move a box's corners, by price or by point.
box.set_text(id, text), box.set_text_color(id, color), box.set_text_size(id, size), box.set_text_halign(id, align), box.set_text_valign(id, align), box.set_text_wrap(id, wrap), box.set_text_formatting(id, format), box.set_text_font_family(id, family)The text inside a box: what it says, how it is coloured, how big it is, where it sits and how it wraps.
box.set_border_width(id, width), box.set_border_style(id, style), box.set_xloc(id, xloc)The thickness and the style of a box's border, and whether its sides are bar indexes or bar times.
polyline.new(x1, y1, x2, y2, ...), polyline.delete(id), polyline.allA chain of points joined by a line: the drawing for a path that is not a straight segment.
table.set_position(id, position), table.cell_set_text_font_family(id, column, row, family), table.cell_set_text_formatting(id, column, row, format)Move a table inside the chart, and the family of letter and the formatting of a cell's text.
table.allThe array of every table the script has drawn.
table.cell(...), table.cell_set_*, table.set_*, table.merge_cells, table.clear, table.deleteWrite a cell, change the table, merge a rectangle of cells, clear it or remove it.
label(x), box(x), line(x), linefill(x), table(x)The casts of Pine v6: they turn na into a drawing of that type, so a script can declare one before it has drawn it (`var label l = label(na)`). The drawing itself is made with label.new, box.new, line.new, linefill.new and table.new.

Math, strings and colours

SyntaxWhat it does
math.abs, ceil, floor, round(number, precision), sign, sqrt, exp, log, log10, pow(base, exponent)Arithmetic.
math.max(...), math.min(...), math.avg(...)Of any number of values.
math.sum(source, length)Sum over the last length bars.
math.pi, math.eConstants.
na, na(x), nz(x, replacement), fixnan(x)The missing value, a test for it, a replacement for it, and the last non-na value.
int(x), float(x), bool(x)Conversions.
str.tostring(value, format), str.format(text, ...), str.length(s), str.contains(s, part)Strings. str.format replaces {0}, {1}… with the arguments.
str.upper(source), str.lower(source), str.replace_all(source, target, replacement), str.substring(source, begin_pos, end_pos)Case and text editing.
str.split(source, separator)Cut a text into an array of pieces.
str.replace(source, target, replacement, occurrence)Replace one occurrence, counting from zero. str.replace_all replaces them all.
str.tonumber(source), str.trim(source), str.startswith(source, part), str.endswith(source, part)Read a text as a number, cut its spaces, and ask whether it starts or ends with something.
str.repeat(source, repeat, separator), str.pos(source, part), str.match(source, regex)Repeat a text, find where a part starts, and get the first match of a regular expression.
str.format_time(value, format, timezone)Formats a UNIX timestamp with a Java-like pattern: yyyy, MM, dd, HH, mm, ss.
math.acos(value), math.asin(value), math.atan(value), math.cos(value), math.sin(value), math.tan(value), math.todegrees(radians), math.toradians(degrees)The trigonometry, and the conversion between radians and degrees.
math.round_to_mintick(value)The nearest multiple of the chart's price tick, with the ties rounding up.
math.random(min, max, step, seed)A pseudo-random number in that range. The same seed gives the same sequence, so a backtest with random numbers stays reproducible.
log.info(message), log.warning(message), log.error(message)Write a line in the script's log, with {0}-style placeholders.
map.clear(m), map.copy(m), map.put_all(m, other)Empty a map, copy it, or pour another map into it.
color.r(color), color.g(color), color.b(color), color.t(color)One channel of a colour: red, green, blue, or the transparency.
color.from_gradient(value, bottom_value, top_value, bottom_color, top_color)The colour a value takes in a gradient, between two colours.
color.new(color, transp), color.rgb(red, green, blue, transp)Build a colour; transparency from 0 to 100.
color.*red, green, blue, orange, yellow, purple, aqua, lime, fuchsia, teal, maroon, navy, olive, gray, silver, white, black.

Arrays (array.*)

SyntaxWhat it does
array.new_float, new_int, new_bool, new_string, new_color, new_line, new_box, new_label, new_table(size)Create an array.
array.new<type>(size, initial_value)The generic constructor: an array of the given type, with the elements filled with the initial value. The type does not change anything at runtime.
array.get, set, insert, push, pop, shift, unshiftRead and change elements.
array.size, first, last, sum, avg, min, max, stdevSize and statistics.
array.from(...), array.clear(id), array.remove(id, index)An array from its elements, an empty one, and the removal of an element (a negative index counts from the end).
array.fill(id, value, start_index, end_index)Overwrite elements with a value: all of them, from an index on, or a range.
array.concat(id1, id2), array.slice(id, from, to), array.copy(id)concat pushes the second array's elements into the first and returns it; slice and copy give a new array.
array.sort(id, order), array.sort_indices(id, order), array.reverse(id)Put the elements in order, get the indices that would read them in order, or turn them around.
array.includes(id, value), array.indexof(id, value), array.lastindexof(id, value), array.join(id, separator)Look for an element and join the elements into a text.
array.every(id), array.some(id)Whether all the elements are true, or whether at least one is. In a number array, zero is false.
array.median(id), array.mode(id), array.range(id), array.variance(id, biased), array.covariance(id1, id2, biased), array.standardize(id), array.abs(id)Statistics over the elements. mode is the most frequent value; standardize returns (x - mean) / stdev; variance and covariance are biased by default, as in Pine.
array.percentrank(id, index), array.percentile_linear_interpolation(id, percentage), array.percentile_nearest_rank(id, percentage)Where an element sits in the array's order, and the value at a percentile.
array.binary_search(id, value), array.binary_search_leftmost(id, value), array.binary_search_rightmost(id, value)Look for a value in a sorted array: the index it has, or -1.
matrix.new(rows, columns, initial_value), matrix.get, matrix.set, matrix.rows, matrix.columns, matrix.elements_count, matrix.row, matrix.col, matrix.copy, matrix.fillBuild a matrix and read it: its cells, its size, its rows and its columns.
matrix.add_row, matrix.add_col, matrix.remove_row, matrix.remove_col, matrix.reshape, matrix.transpose, matrix.reverse, matrix.swap_rows, matrix.swap_columns, matrix.sort, matrix.submatrixChange its shape: add or remove a row or a column, reorder the cells, swap rows or columns, sort the rows by a column, or take a rectangle out of it.
matrix.mult, matrix.concat, matrix.diff, matrix.kronCombine two matrices: the product, the rows of one appended to the other, the difference cell by cell, and the Kronecker product.
matrix.sum, matrix.avg, matrix.min, matrix.max, matrix.median, matrix.modeThe statistics over all the cells.
matrix.det, matrix.inv, matrix.pinv, matrix.rank, matrix.trace, matrix.pow, matrix.eigenvalues, matrix.eigenvectorsThe linear algebra: the determinant, the inverse, the pseudo-inverse, the rank, the trace, a power, the eigenvalues and the eigenvectors.
matrix.is_square, matrix.is_zero, matrix.is_identity, matrix.is_diagonal, matrix.is_antisymmetric, matrix.is_symmetric, matrix.is_triangular, matrix.is_antidiagonal, matrix.is_binary, matrix.is_stochasticWhat shape the matrix has: square, zero, the identity, diagonal, antisymmetric, symmetric, triangular, antidiagonal, binary or stochastic.
chart.point.new(time, index, price), chart.point.now(), chart.point.copy, chart.point.from_index, chart.point.from_timeA point of the chart: a bar and a price. The drawing functions take one as their x coordinate, and the drawing hangs from the bar it names.
array.new_linefill(size)An array of linefills.

Maps and user-defined types

User-defined types and the `map.<fn>` collection are supported. Both are top-level declarations; instance methods on a value use the `obj.method(args...)` syntax.

SyntaxWhat it does
enum Name Member Member = N ...Top-level enum declaration. Members without a value auto-increment from 0; explicit values may be numbers or strings. Access as `Name.Member` in any expression position. Enum values are plain numbers (or strings), so they work with comparison operators and with `int()` without conversion.
type Name field1 field2: int field3 = defaultTop-level user-defined type. Fields are listed one per line; the `: type` and `= default` parts are accepted for forward compatibility but not yet validated. Construct with `Type.new(arg1, arg2, ...)` and read fields with `instance.field`.
m = map.new<int, float>()Create an empty map. Type-args `<K, V>` are accepted but ignored at runtime.
m = map.put(m, key, value)Set a key. Returns the map so calls can chain or be reassigned.
v = map.get(m, key)Read a value. Returns na if the key is missing.
n = map.size(m)Number of entries.
keys = map.keys(m), values = map.values(m)Return the keys or values as a Pine array (insertion order).
map.contains(m, key), map.remove(m, key)Membership test and deletion. Both return the map.

Deepwick Script

The Deepwick dialect: Pine v6 plus what Pine does not have. Mark the script with //@deepwick to use it — in Pine these names are an error, so a script can be written in either dialect.

SyntaxWhat it does
spread.now(), spread.bps(), cost.round_trip(size)The spread the market charged on this bar, in price and in basis points, and what moving a size round trip costs with your commission and your slippage.
import "lib/position"Imports a module. lib/position brings position_size(), position_entry(), position_open_pnl(), position_equity() and position_cost(size) into scope. A module is compiled with your script, so its names have to be unique on the site. A module that needs the Deepwick dialect can only be imported by a script marked with //@deepwick.

Runtime (runtime.*)

What the script can say about its own execution.

SyntaxWhat it does
runtime.error(message)Stop the script with a message of your own. Useful in an if that should never be true.

Not supported yet

A function the engine does not know stops the script with "Unknown function" and the line and column.

SyntaxWhat it does
import, request.dividends, request.earnings, request.financial, request.splits, request.economic, request.quandl, request.currency_rate, earnings.*, dividends.*, ticker.renko, ticker.kagi, ticker.linebreak, ticker.pointfigureLibraries are not implemented yet. The functions that need a data feed we do not have — dividends, earnings, analyst data and currency rates — return na, and the chart types we do not build (Renko, Kagi, line break and point & figure) are not there either.
strategy.risk.*The risk rules (max_position_size, max_intraday_loss, max_drawdown, allow_entry_in) are not supported. Trailing stops in strategy.exit() are: use trail_points and trail_offset.

Questions

Is Deepwick Script the same as Pine Script?

No. It is Deepwick's own engine, which runs a subset of Pine Script: the functions on this page. Most ta.*, math.*, str.*, input.*, plot* and strategy.* calls run as-is; unsupported lines are flagged with line and column. Deepwick is not affiliated with TradingView; Pine Script is a trademark of TradingView, Inc.

Which Pine Script features does Deepwick Script support?

Deepwick Script runs a subset of Pine Script, including enums, user-defined types (`type`), the `matrix.*` and `map.*` collections, user-defined functions, and the `library()` declaration with its `export` keyword. Not implemented yet: importing a published library (`import`), because there is no library to import from; the editor reports them with the exact line and column. The functions that need a data feed we do not have (dividends, earnings, analyst data, currency rates) return na, and the chart types we do not build (Renko, Kagi, line break, point & figure) are not there either. The //@version line is not enforced. Paste a script into the editor to see which lines run.

Does Deepwick support request.security()?

Yes, for a higher timeframe of the chart's own symbol. request.security(syminfo.tickerid, "240", close) returns the last CLOSED 4h close, and the expression can be a ta.* call. Another symbol still returns na: the engine only ever holds the chart's own bars, and a plausible-looking wrong number would be worse than none.

Why does request.security() return na on the first bars?

Because no higher-timeframe bar has closed yet. A 4h bar only becomes readable on the chart bar after it closes, which is exactly what prevents a backtest from reading a bar that is still forming. Once one has closed, the value repeats until the next one closes.

How are strategy orders filled in a backtest?

Market orders fill at the next bar's open. Stops and limits fill along the bar (open, nearer extreme, farther extreme, close), and an order the price gaps through fills at the open. Commission is charged on every fill and slippage on market and stop fills, as set in strategy(); both default to zero.

Where do scripts run?

On the chart, in your browser, over the bars loaded on the chart. Saved backtests run on Deepwick's servers over up to 10,000 bars.