Edge Script documentation
Edge Script is Bulledge's own scripting language: you write your own indicator in a few lines, it runs on our servers and is drawn on the Edge Chart. It reads like Pine Script with less ceremony, and most Pine indicators run unchanged.
Your first script
- Open the Edge Chart and press the
</>icon on the right edge: the Edge Script panel opens. - Press New script. The panel opens with a working example.
- Press Draw (or Ctrl+Enter). The script runs on the server over the chart's candles without being saved, and its lines land on the chart; Save it (Ctrl+S) when you like it.
- The eye in the list turns a script on or off the chart; your saved scripts are also under My scripts in the Indicators menu beside the periods. Several scripts can be drawn at once.
indicator("EMA crossover", overlay = true)
fast = ema(close, 12)
slow = ema(close, 26)
plot(fast, "Fast", color = orange)
plot(slow, "Slow", color = blue)
mark(crossover(fast, slow), "BUY", position = "below", color = green)
mark(crossunder(fast, slow), "SELL", position = "above", color = red)As you type, the editor checks the code with the server's own compiler: the faulty line is underlined, and the line underneath says what is wrong, with its line and column, in your language. A misspelt name gets the nearest right one suggested.
How it runs
The script runs once per bar, top to bottom, from the oldest bar to the newest. On any line, close is the close of the bar being run. The chart opens on the newest 1,000 bars and loads older ones as you scroll back; the script runs over a longer history, so a long average is already warm on the first bar on screen.
Every value is a series: it has a value on every bar, and its history is read with []. close[1] is the previous bar's close, and ema(close, 20)[3] is the average three bars back.
An unknown value is na: before an average has filled, before the start of history, or from a division by zero. na turns a sum into na and is not drawn; nz(x) turns it into zero and fixnan(x) into the last known value.
The chart is read again every minute and the script runs again with the new bars. It also sees the newest, still-forming bar; a crossing on that bar can change until it closes.
Values and types
| TYPE | WRITTEN AS | NOTE |
|---|---|---|
| number | 14, 2.5, 1e-3 | No separate integer and float. |
| boolean | true, false | Conditions and mark take these. |
| text | "Rising", 'BUY' | Labels, titles, alert messages. |
| colour | red, #26a69a, #26a69a80 | The last two digits are transparency; rgb() and color.new() give colours too. |
| na | na | The unknown value. |
Named colours: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, yellow — also with the color. prefix.
Variables and history
A variable is made by giving a name a value with =; no type needs declaring. It is computed afresh on every bar. Assign it again with = or :=, and add to it with +=, -=, *=, /=.
A variable declared with var is set only on the first bar and carries its value from bar to bar: a counter, the price of the last signal, or a state.
var count = 0
var lastSignal = na
if crossover(close, sma(close, 50))
count += 1
lastSignal := close
change = (close - lastSignal) / lastSignal * 100
plot(change, "% since the last signal", pane = "Signal")Every variable's history is read with [], up to 20,000 bars back.
Operators
| OPERATOR | MEANING |
|---|---|
+ - * / % | Arithmetic; + joins two texts. |
== != < > <= >= | Comparison. |
and or not | Logic. |
a ? b : c | b when a is true, c otherwise. |
x[n] | x as it was n bars ago. |
Conditions and loops
Blocks are written by indentation (four spaces or a tab): there are no braces and no end.
r = rsi(close, 14)
state = 0
if r > 70
state := 1
else if r < 30
state := -1
else
state := 0
// how many of the last 10 bars closed up
up = 0
for i = 0 to 9
if close[i] > open[i]
up += 1
plot(up, "Up bars", pane = "Count", style = "histogram")kind = input("ema", "Average")
avg = switch kind
"ema" => ema(close, 20)
"sma" => sma(close, 20)
=> wma(close, 20)
tint = switch
close > avg => green
close < avg => red
=> gray
plot(avg, "Average", color = tint)for i = a to bcounts from a to b inclusive;by stepsets the step, and it counts down when b is below a.while conditionloops while the condition holds.breakleaves the loop,continuegoes to the next turn.- A loop turns at most 100,000,000 times on one bar.
- Functions that keep a history (
ema,crossover, …) cannot be called inside a loop: compute them before it. for x in xswalks an array's elements,for [i, x] in xswith their index, andfor [k, v] in ma map's keys and values.switchgives the value of the first arm that matches; written without a subject, of the first whose condition is true. A=>with nothing before it is the default arm and comes last.
Your own functions
A function is defined with name(parameters) =>: one expression on the same line, or an indented block whose last line is its value. Several values are returned as [a, b] and taken with [x, y] = f().
band(src, len, mult) =>
mid = sma(src, len)
dev = stdev(src, len)
[mid + mult * dev, mid - mult * dev]
[upper, lower] = band(close, 20, 2)
plot(upper, "Upper", color = teal)
plot(lower, "Lower", color = teal)Every call site keeps its own history: band(close, 20, 2) and band(high, 50, 3) never mix their averages. A function is defined only at the top level. It may call itself — fib(n) => n < 2 ? n : fib(n - 1) + fib(n - 2) — as long as it keeps no history (no [], no indicator, no var), at most 500 levels deep.
Your own types and methods
type defines a record: its fields indented beneath it, each with a type and, if you like, a default. Name.new(…) makes a new object — the fields in order or by name — and an object is a reference, like an array: z.top reads, z.top := x writes, z.copy() gives a copy. A method is a function whose first parameter has a type, called on a value of that type as z.width(); built-in types such as array, map and matrix can have methods too.
type Zone
float top
float bottom
int touches = 0
method width(Zone z) => z.top - z.bottom
var zone = Zone.new(high, low)
if high > zone.top
zone.top := high
if low < zone.bottom
zone.bottom := low
zone.touches += 1
plot(zone.width(), "Width", pane = "Zone")
plot(zone.touches, "New lows", pane = "Zone")Function parameters can carry a type and a default too: band(float src, int len = 20) =>; a caller may give only some of them, by name: band(close, len = 50). Reading a field of an na object is an error.
enum defines a set of choices: its fields indented beneath it, each with = "Title" if you like. A field is written Trend.up; two fields compare with == and != (a field equals only itself), work in a switch and as a map's key, and str.tostring gives the title (or the field's name when it has none). input.enum makes an enum field a setting: its choices are the fields' titles, and options = […] narrows them.
enum Trend
up = "Rising"
down = "Falling"
flat = "Flat"
colourWhen = input.enum(Trend.up, "Colour when")
avg = ema(close, 20)
trend = close > avg ? Trend.up : close < avg ? Trend.down : Trend.flat
plot(avg, "EMA", color = trend == colourWhen ? color.green : color.gray)
if barstate.islast
label.new(bar_index, high, str.tostring(trend))Libraries
A library is a script that writes library("Title") instead of indicator(). The functions, types, constants and methods it marks export are used from other scripts with import; what it does not mark — its own example code included — stays inside it. Your own library is found by its library() title or by the name you saved it under; a library published openly on TradingView (import TradingView/ta/12 as ta) is fetched and used too.
library("Tools")
export type Band
float upper
float lower
export band(float src, int len = 20, float mult = 2) =>
mid = sma(src, len)
dev = stdev(src, len)
Band.new(mid + mult * dev, mid - mult * dev)
export method percent(Band b, float price) => (price - b.lower) / (b.upper - b.lower) * 100import me/Tools/1 as t
b = t.band(close, 20)
plot(b.upper, "Upper", color = teal)
plot(b.lower, "Lower", color = teal)
plot(b.percent(close), "%B", pane = "%B")import user/Name/version as alias is Pine's form: when the user is a TradingView publisher the library is fetched from there at that version; otherwise the name in the middle is looked for among your own libraries, and import Tools as t works too. A library may import others; the same library reached two ways is one copy. An error in a library is reported with the library's own line.
Arrays and maps
An array holds values in order, a map values by key. Both are references: var xs = array.new<float>() carries one array from bar to bar, and two names can hold the same one. Their functions are called two ways: array.push(xs, close) and xs.push(close) are the same, and it works on a call's result too: array.from(3, 1, 2).max().
var closes = array.new<float>()
closes.push(close)
if closes.size() > 20
closes.shift()
plot(closes.median(), "Median", color = orange)
tally = map.new<string, int>()
for x in closes
side = x > closes.avg() ? "above" : "below"
tally.put(side, nz(tally.get(side)) + 1)
plot(nz(tally.get("above")), "Above the average", pane = "Count")An index outside the array is an error, and so is pop on an empty one. A script can make at most 100,000,000,000 array and map elements in all — arrays it drops are freed, so the count bounds the work rather than what is held — and one array grows to 1,000,000. Matrix elements count too.
Matrices
A matrix holds numbers in rows and columns and is a reference, like an array. matrix.new<float>(rows, columns, value) makes one and get / set read and write an element; transpose, mult, inv, det, pow and rank do the linear algebra, add_row, submatrix and sort the rearranging. Method syntax works here too: X.transpose().mult(X).
indicator("Regression line", overlay = true)
n = input(50, "Length", minval = 2)
if barstate.islast
X = matrix.new<float>(n, 2, 1)
y = matrix.new<float>(n, 1, 0)
for i = 0 to n - 1
X.set(i, 1, i)
y.set(i, 0, close[n - 1 - i])
Xt = X.transpose()
b = Xt.mult(X).inv().mult(Xt).mult(y)
line.new(bar_index - n + 1, b.get(0, 0), bar_index, b.get(0, 0) + b.get(1, 0) * (n - 1), color = orange, width = 2)Every new matrix counts toward the same element budget as arrays; a script that makes a large one on every bar meets it on a deep history — compute on the last bar, as above, or make it once with var and update it in place. The inverse of a singular matrix is na.
Inputs
input() declares a setting of the script; its kind comes from its default: a number, true/false, a text, or a source such as close. minval and maxval bound a number. The editor shows the script's inputs and their values underneath.
length = input(20, "Length", minval = 1)
source = input(close, "Source")
show = input(true, "Show the bands")Other symbols and timeframes
request.security(symbol, timeframe, expression) computes the expression on another symbol or timeframe and lines it up with this chart's bars. The script runs over that series once more from its start, so the expression may use the script's own variables and functions.
daily = request.security(syminfo.tickerid, "1D", ema(close, 20))
plot(daily, "Daily EMA 20", color = orange)
btc = request.security("BINANCE:BTCUSDT", timeframe.period, close)
plot(close / btc, "Ratio to BTC", pane = "Ratio")- It does not look ahead: a bar gets the value of the newest requested bar that had closed when it closed. On an hourly chart the daily close is the previous day's until the day's last hour.
lookahead = barmerge.lookahead_ongives the bar it opened in instead — the future, on history, which is why it is not the default. - The symbol and timeframe are written out (
"BINANCE:ETHUSDT","1D"),syminfo.tickerid/timeframe.periodor aninput()— or computed as the script runs: a function's parameter, a symbol read from an array in a loop, a higher timeframe chosen from the chart's. A series that could not be known in advance reads na on the first run; the server fetches it and runs the script again. A symbol written without its exchange —input.symbol("NQ1!")too — is read as TradingView reads it, the symbol search's match (CME_MINI:NQ1!). - The timeframes read are 1S, 5S, 10S, 15S, 30S, 1, 5, 15, 30, 60, 120, 240, 1D, 1W and 1M (D, W and M work too); any other number of seconds, minutes, days, weeks or months (
"20S","24","3D","3M") is built from the largest of them that divides it. Write[close, volume]and take several values with[c, v] = request.security(…). A request's expression may make another request: the inner one is read lined up with the outer one's bars. - A script reads at most 128 other series; the two functions below count toward it too.
currency = currency.USDconverts the requested series' numbers from that symbol's currency to USD, at FX_IDC's rate lined up bar by bar likerequest.security. It converts a ratio or a count too, so use it for prices and amounts only.
request.security_lower_tf(symbol, timeframe, expression) gives a lower timeframe's values as an array per chart bar: one element for every lower bar that opened inside it, oldest first — as deep as on TradingView: the newest 100,000 lower bars (as many as a chart of that timeframe holds when the script sets calc_bars_count). request.currency_rate("USD", "TRY") gives how many units one unit buys, on this chart's bars.
parts = request.security_lower_tf(syminfo.tickerid, "15", high - low)
plot(parts.size() > 0 ? parts.max() : na, "Widest 15 min", pane = "Range")
plot(request.currency_rate("USD", "TRY"), "USD/TRY", pane = "Rate")The lower timeframe is read to as many bars as the chart, so its history is shorter and the array is empty on older bars. Rates come from FX_IDC; the same currency gives 1.
Company data
request.financial(symbol, id, period) gives a company's reported figure — revenue, net income, debt, margins, ratios — as a series. request.earnings gives the earnings per share at each release (actual or estimate), request.dividends the dividend and request.splits the stock splits. A value changes when a new period arrives and stays the same in between; gaps = barmerge.gaps_on gives it only on the bar it arrives.
revenue = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ")
eps = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "TTM")
plot(revenue / 1e9, "Revenue (billions)", pane = "Revenue", style = "columns")
plot(close / eps, "P/E", pane = "P/E")
plot(request.dividends(syminfo.tickerid), "Dividend", pane = "Dividend", style = "stepline")- Dates: a statement is dated at its period's END — a quarter ending 30 June shows from 30 June — although the company publishes it weeks later; TradingView draws it the same way. Earnings per share arrives at the release, a dividend on its ex-date. A value holds from the first bar that closes after it.
- Periods:
FQthe last 32 quarters,FYthe last 20 years,FHhalf-years (for companies that report them),TTMthe last 8 quarters and only for: EARNINGS_PER_SHARE_DILUTED, EBITDA, FREE_CASH_FLOW, GROSS_PROFIT, NET_INCOME, TOTAL_REVENUE. Earnings per share covers the last 8 releases. - Units: money is in the company's reporting currency (a London share quoted in pence reports in pounds), in the major unit; margins and returns are percentages. A crypto pair, an index or a fund has no data, and the series is na throughout.
request.splits(symbol, splits.numerator)gives the shares after a split andsplits.denominatorthe shares before (10 and 1 in a 10-for-1); it reaches back about 20 years.earnings.standardizedanddividends.netare not in the source and give an error.- A script reads at most 128 different company figures.
request.economic(country, field) reads an economic series — "US", "GDP" the US GDP, "TR", "INTR" Turkey's policy rate, "US", "CPI" inflation, "US", "UR" unemployment. Each observation is dated at its period's end and holds until the next; nothing before 1970 is read.
rate = request.economic("US", "INTR")
plot(rate, "Policy rate %", pane = "Rate", style = "stepline")The 174 ids request.financial can read
- ACCOUNTS_PAYABLE
- ACCOUNTS_RECEIVABLES_NET
- ACCRUED_PAYROLL
- ACCUM_DEPREC_TOTAL
- ADDITIONAL_PAID_IN_CAPITAL
- AFTER_TAX_OTHER_INCOME
- AMORTIZATION
- ASSET_TURNOVER
- BASIC_SHARES_OUTSTANDING
- BOOK_TANGIBLE_PER_SHARE
- BOOK_VALUE_PER_SHARE
- CAPITAL_EXPENDITURES
- CAPITAL_EXPENDITURES_FIXED_ASSETS
- CAPITAL_EXPENDITURES_OTHER_ASSETS
- CAPITAL_LEASE_OBLIGATIONS
- CAPITAL_OPERATING_LEASE_OBLIGATIONS
- CASH_F_FINANCING_ACTIVITIES
- CASH_F_INVESTING_ACTIVITIES
- CASH_F_OPERATING_ACTIVITIES
- CASH_N_EQUIVALENTS
- CASH_N_SHORT_TERM_INVEST
- CHANGES_IN_WORKING_CAPITAL
- CHANGE_IN_ACCOUNTS_PAYABLE
- CHANGE_IN_ACCOUNTS_RECEIVABLE
- CHANGE_IN_ACCRUED_EXPENSES
- CHANGE_IN_INVENTORIES
- CHANGE_IN_OTHER_ASSETS
- CHANGE_IN_TAXES_PAYABLE
- COMMON_DIVIDENDS_CASH_FLOW
- COMMON_EQUITY_TOTAL
- COMMON_STOCK_PAR
- COST_OF_GOODS
- CURRENT_PORT_DEBT_CAPITAL_LEASES
- CURRENT_RATIO
- DEBT_TO_ASSET
- DEBT_TO_EQUITY
- DEFERRED_INCOME_CURRENT
- DEFERRED_INCOME_NON_CURRENT
- DEFERRED_TAX_ASSESTS
- DEFERRED_TAX_LIABILITIES
- DEPRECIATION_DEPLETION
- DEP_AMORT_EXP_INCOME_S
- DILUTED_NET_INCOME
- DILUTED_SHARES_OUTSTANDING
- DILUTION_ADJUSTMENT
- DISCONTINUED_OPERATIONS
- DIVIDENDS_PAYABLE
- DIVIDENDS_YIELD
- DIVIDEND_PAYOUT_RATIO
- DPS_COMMON_STOCK_PRIM_ISSUE
- EARNINGS_PER_SHARE_BASIC
- EARNINGS_PER_SHARE_DILUTED
- EBIT
- EBITDA
- EBITDA_MARGIN
- ENTERPRISE_VALUE
- ENTERPRISE_VALUE_EBITDA
- EQUITY_IN_EARNINGS
- FLOAT_SHARES_OUTSTANDING
- FREE_CASH_FLOW
- FUNDS_F_OPERATIONS
- GOODWILL
- GROSS_MARGIN
- GROSS_PROFIT
- INCOME_TAX
- INCOME_TAX_PAYABLE
- INTANGIBLES_NET
- INTEREST_CAPITALIZED
- INTEREST_EXPENSE_ON_DEBT
- INVENTORY_FINISHED_GOODS
- INVENTORY_PROGRESS_PAYMENTS
- INVENTORY_RAW_MATERIALS
- INVENTORY_WORK_IN_PROGRESS
- INVENT_TURNOVER
- INVESTMENTS_IN_UNCONCSOLIDATE
- ISSUANCE_OF_DEBT_NET
- ISSUANCE_OF_LONG_TERM_DEBT
- ISSUANCE_OF_OTHER_DEBT
- ISSUANCE_OF_SHORT_TERM_DEBT
- ISSUANCE_OF_STOCK_NET
- LONG_TERM_DEBT
- LONG_TERM_DEBT_EXCL_CAPITAL_LEASE
- LONG_TERM_DEBT_TO_ASSETS
- LONG_TERM_DEBT_TO_EQUITY
- LONG_TERM_INVESTMENTS
- LONG_TERM_NOTE_RECEIVABLE
- LONG_TERM_OTHER_ASSETS_TOTAL
- MARKET_CAP
- MINORITY_INTEREST
- MINORITY_INTEREST_EXP
- NET_DEBT
- NET_INCOME
- NET_INCOME_BEF_DISC_OPER
- NET_INCOME_STARTING_LINE
- NET_MARGIN
- NON_CASH_ITEMS
- NON_OPER_INCOME
- NON_OPER_INTEREST_EXP
- NON_OPER_INTEREST_INCOME
- NUMBER_OF_EMPLOYEES
- NUMBER_OF_SHAREHOLDERS
- OPERATING_EXPENSES
- OPERATING_LEASE_LIABILITIES
- OPERATING_MARGIN
- OPER_INCOME
- OTHER_COMMON_EQUITY
- OTHER_CURRENT_ASSETS_TOTAL
- OTHER_CURRENT_LIABILITIES
- OTHER_FINANCING_CASH_FLOW_ITEMS_TOTAL
- OTHER_FINANCING_CASH_FLOW_SOURCES
- OTHER_FINANCING_CASH_FLOW_USES
- OTHER_INCOME
- OTHER_INTANGIBLES_NET
- OTHER_INVESTING_CASH_FLOW_ITEMS_TOTAL
- OTHER_INVESTING_CASH_FLOW_SOURCES
- OTHER_INVESTING_CASH_FLOW_USES
- OTHER_INVESTMENTS
- OTHER_LIABILITIES_TOTAL
- OTHER_OPER_EXPENSE_TOTAL
- OTHER_RECEIVABLES
- OTHER_SHORT_TERM_DEBT
- PAID_IN_CAPITAL
- PPE_TOTAL_GROSS
- PPE_TOTAL_NET
- PREFERRED_DIVIDENDS
- PREFERRED_DIVIDENDS_CASH_FLOW
- PREFERRED_STOCK_CARRYING_VALUE
- PREPAID_EXPENSES
- PRETAX_EQUITY_IN_EARNINGS
- PRETAX_INCOME
- PRICE_BOOK_RATIO
- PRICE_EARNINGS_RATIO
- PRICE_SALES_RATIO
- PROVISION_F_RISKS
- PURCHASE_OF_BUSINESS
- PURCHASE_OF_INVESTMENTS
- PURCHASE_OF_STOCK
- PURCHASE_SALE_BUSINESS
- PURCHASE_SALE_INVESTMENTS
- QUICK_RATIO
- REDUCTION_OF_LONG_TERM_DEBT
- RESEARCH_AND_DEV
- RETAINED_EARNINGS
- RETURN_ON_ASSETS
- RETURN_ON_EQUITY
- RETURN_ON_INVESTED_CAPITAL
- SALES_OF_BUSINESS
- SALES_OF_INVESTMENTS
- SALE_OF_STOCK
- SELL_GEN_ADMIN_EXP_OTHER
- SELL_GEN_ADMIN_EXP_TOTAL
- SHORT_TERM_DEBT
- SHORT_TERM_DEBT_EXCL_CURRENT_PORT
- SHORT_TERM_INVEST
- SHRHLDRS_EQUITY
- SUPPLYING_OF_LONG_TERM_DEBT
- TOTAL_ASSETS
- TOTAL_CASH_DIVIDENDS_PAID
- TOTAL_CURRENT_ASSETS
- TOTAL_CURRENT_LIABILITIES
- TOTAL_DEBT
- TOTAL_EQUITY
- TOTAL_INVENTORY
- TOTAL_LIABILITIES
- TOTAL_LIABILITIES_SHRHLDRS_EQUITY
- TOTAL_NON_CURRENT_ASSETS
- TOTAL_NON_CURRENT_LIABILITIES
- TOTAL_NON_OPER_INCOME
- TOTAL_OPER_EXPENSE
- TOTAL_RECEIVABLES_NET
- TOTAL_REVENUE
- TOTAL_SHARES_OUTSTANDING
- TREASURY_STOCK_COMMON
- UNUSUAL_EXPENSE_INC
The forming bar: varip and calculating on every tick
On every historical bar a script runs once. On the newest, forming bar it runs again as the price moves: var goes back to its value at the bar's start each time, while varip keeps what it gathered on the bar's earlier ticks. When a script declares varip or writes calc_on_every_tick = true, the chart runs it again every few seconds with the live price; each run is a tick.
varip lastPrice = 0.0
varip ups = 0
if barstate.isnew
ups := 0
if barstate.isrealtime and lastPrice > 0 and close > lastPrice
ups += 1
lastPrice := close
plot(ups, "Up ticks", pane = "Ticks", style = "columns")barstate.isnewis true on a bar's first tick (always, on historical bars);barstate.isrealtimeandbarstate.isconfirmedsay whether the newest bar is still open;barstate.islastconfirmedhistorymarks the last closed bar.- A tick is a run, not every price change: the chart runs every few seconds. What
varipgathered starts over when the page is reloaded — as on TradingView — or the script changes; it is kept for two hours for the same script, symbol and timeframe. - Only top-level
varipis carried; avaripinside a function behaves likevar, and a drawing's id does not carry into the next run.
Drawing, marks and alerts
indicator("Name", overlay = true)names the script.overlay = truedraws over the price,falsein its own pane; left out, a script draws over the price — and one with a//@versionline, which is Pine, in its own pane, as on TradingView.plot()draws a line;style = "histogram","area"or"circles"are the other shapes.pane = "Name"puts it in a named pane under the price; plots naming the same pane share it.colormay change bar by bar:color = close > open ? green : red.hline()draws a horizontal line at a fixed price — RSI's 70/30 in a pane, say.mark()puts an arrow, circle or square on the bars where its condition is true, with a short text if you like.alert()records the bars where its condition is true; the editor lists this chart's latest.
indicator("MACD", overlay = false)
[m, signal, hist] = macd(close, 12, 26, 9)
plot(hist, "Histogram", color = hist >= 0 ? green : red, style = "histogram")
plot(m, "MACD", color = blue)
plot(signal, "Signal", color = orange)
hline(0, "Zero", color = gray)fill(p1, p2, color) fills between two plot() or two hline() results (keep them, as p1 = plot(…)); bgcolor(color) colours behind the bar and barcolor(color) the chart's own candle. plotchar draws a character, plotarrow an arrow, plotcandle and plotbar candles of your own. indicator("…", currency = currency.USD) converts the chart's prices into that currency; drawn over the price, the script gets a price scale of its own on the left.
indicator("Band and trend", overlay = true)
[mid, upper, lower] = bb(close, 20, 2)
p1 = plot(upper, "Upper", color = teal)
p2 = plot(lower, "Lower", color = teal)
fill(p1, p2, color = color.new(teal, 85))
up = close > ema(close, 50)
bgcolor(up ? color.new(green, 92) : color.new(red, 92))
barcolor(close > upper ? yellow : na)
plotchar(crossover(close, upper), "Breakout", "▲", location.belowbar, color = yellow)Strategies and backtests
A script that writes strategy() instead of indicator() places orders: strategy.entry opens a position, strategy.exit sets a take-profit and a stop, strategy.close closes it. The orders are filled over the bars; the chart shows buys as green arrows and sells as red ones, and the editor shows the backtest — net profit, trades, win rate, profit factor, largest drawdown — and the trades themselves.
strategy("EMA cross", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1)
fast = ema(close, 12)
slow = ema(close, 26)
if crossover(fast, slow)
strategy.entry("Long", strategy.long)
strategy.exit("Exit", "Long", limit = close * 1.04, stop = close * 0.98)
if crossunder(fast, slow)
strategy.close("Long")
plot(strategy.equity, "Equity", pane = "Equity")- An order fills on the bar AFTER the one that placed it: the script decides having seen a bar's close, and a market order fills at the next bar's open.
process_orders_on_close = truefills it at the same bar's close. - A limit or stop order fills at its price when a bar's range reaches it — at the open when the bar opened past it. With a target and a stop on the same bar, price is assumed to go to the extreme nearer the open first — TradingView's assumption.
- Size:
default_qty_type=strategy.fixed(units),strategy.cash(an amount) orstrategy.percent_of_equity;default_qty_valuesets it,qtyone order's.commission_valueis a percent per trade (per unit or per order withcommission_type).pyramidingis how many entries may open in one direction. - A script can read
strategy.position_size,strategy.position_avg_price,strategy.equity,strategy.netprofit,strategy.openprofit,strategy.opentrades,strategy.closedtrades,strategy.wintradesandstrategy.losstrades; functions such asstrategy.opentrades.entry_price(0)orstrategy.closedtrades.profit(n)read one trade. - Trailing stops:
strategy.exit'strail_price(ortrail_points, in ticks from the entry) arms the stop once reached; it then follows the best pricetrail_offsetticks behind and only ever moves in your favour. slippagemoves every market and stop fill that many ticks against you. When one of the orders sharing anoca_namefills,oca_type = strategy.oca.cancelcancels the others andstrategy.oca.reduceshrinks them. Withmargin_long/margin_short(a percent), a position the equity can no longer carry is closed as "Margin call".currency = currency.EURis the account's currency: the initial capital, profit and equity are in EUR; each trade's profit is converted at the rate of the bar it closed on, open profit at the current one. Without it every amount is in the symbol's own currency. A backtest tells the past, not the future.- Orders fill as TradingView's strategy engine fills them — compared trade by trade on the same bars. What the script does not set is the Pine version's default:
//@version=6(or no version line) is 100% of the equity on a 100% margin with 100,000 of capital; v5 one contract, no margin, 1,000,000; v4 and older one contract, no margin, 100,000. A size is fixed on the close the order is placed on and rounded down to the symbol's smallest quantity (0.00001 BTC on Binance); the price step and a point's value are the symbol's too (0.25 and 50 on ES1!). - Margin is checked three times: when the order is placed (if the position it would open cannot be held at that close, it only closes the one it reverses — which is why a short stop below the close, sized to all the equity, never goes short), when it fills (if it cannot be held, the whole order is refused), and at every point of the bar (a "Margin call" closes four times the quantity that covers the shortfall, and at least one unit).
Labels, lines, boxes, polylines and tables
label.new, line.new and box.new put an object on the chart and give its id; with the id it is changed later (label.set_text(lbl, "…") or lbl.set_text("…")) or deleted. The chart shows the objects still alive when the script ends. An x is a bar index (bar_index), a time with xloc = xloc.bar_time; an x past the newest bar reaches into the future.
indicator("Range", overlay = true)
var b = box.new(na, na, na, na, bgcolor = color.new(blue, 85), border_color = blue)
var lbl = label.new(na, na, "", style = label.style_label_left, color = color.new(blue, 20), textcolor = white)
top = highest(high, 50)
bottom = lowest(low, 50)
if barstate.islast
b.set_lefttop(bar_index - 49, top)
b.set_rightbottom(bar_index, bottom)
lbl.set_xy(bar_index + 2, (top + bottom) / 2)
lbl.set_text("Range: " + str.tostring(top - bottom, "#.##"))- The newest 50 of each kind are kept and the oldest deleted — as in Pine.
max_labels_count,max_lines_countandmax_boxes_countinindicator()orstrategy()raise it up to 1000. - Label styles are
label.style_label_down(the default),label_up,label_left,label_right,label_center,none, and shapes:circle,square,diamond,triangleup,triangledown,arrowup,arrowdown,cross,xcross,flag. Sizessize.tiny…size.huge. table.new(position.top_right, columns, rows)opens a table pinned to a corner or an edge of the chart;table.cellwrites a cell. Keep it in avarso it is made once, and fill it onbarstate.islast.- A change on
naor on a deleted id does nothing, so starting withvar line l = naand writingline.delete(l)thenl := line.new(…)is safe. polyline.new(points)draws a line through an array ofchart.point, in order:curved = truesmooths it,closed = truecloses the shape andfill_colorfills it. The newest 50 are kept, up to 200 withmax_polylines_count.
indicator("Last ten lows", overlay = true)
var points = array.new<chart.point>()
if low == lowest(low, 5)
points.push(chart.point.from_index(bar_index, low))
if points.size() > 10
points.shift()
var polyline pl = na
if barstate.islast
polyline.delete(pl)
pl := polyline.new(points, curved = true, line_color = teal, line_width = 2)Built-in values
| NAME | VALUE |
|---|---|
open high low close volume | The bar's open, high, low, close and volume. |
hl2 hlc3 ohlc4 hlcc4 | The bar's average prices. |
tr obv | True range and on-balance volume (ta.tr, ta.obv). |
time | The bar's opening instant, in Unix milliseconds (as in Pine). |
currency.USD currency.EUR currency.TRY … | Currencies, for currency =. |
bar_index last_bar_index | The bar's position (from 0) and the last one's. |
barstate.isfirst barstate.islast | true on the first or the last bar. |
barstate.isnew barstate.isrealtime barstate.isconfirmed barstate.ishistory barstate.islastconfirmedhistory | The forming bar and its ticks (the "forming bar" section above). |
syminfo.ticker syminfo.tickerid timeframe.period | The symbol and the timeframe, as text. |
hour minute second dayofmonth dayofweek month year weekofyear | Parts of the bar's opening time, in the exchange's zone; dayofweek is 1 = Sunday … 7 = Saturday (dayofweek.sunday …). |
time_close time_tradingday last_bar_time timenow | The bar's close, the start of its trading day (UTC midnight), the last bar's open and now; all in Unix milliseconds. |
ta.vwap | The day's volume-weighted average price of hlc3, starting over at each exchange day. |
timeframe.isintraday timeframe.isminutes timeframe.isseconds timeframe.isdaily timeframe.isweekly timeframe.ismonthly timeframe.isdwm timeframe.multiplier timeframe.main_period | The kind of the chart's timeframe, its multiplier (240 for "240") and, even inside a request, the chart's own timeframe. |
syminfo.mintick syminfo.pricescale syminfo.pointvalue syminfo.currency syminfo.basecurrency syminfo.type syminfo.prefix syminfo.root syminfo.description syminfo.timezone syminfo.session | The symbol's price step, currencies, kind (crypto, stock, forex …), exchange, root, description and time zone (UTC when not known). |
session.isfirstbar session.islastbar session.isfirstbar_regular session.islastbar_regular session.ismarket session.ispremarket session.ispostmarket | The first and last bar of the trading day, by the symbol's own calendar on TradingView: its hours, holidays and early closes (ES's trading day opens at 17:00 the evening before). On a chart carrying extended-hours bars, pre- and post-market are told apart too. A symbol with no calendar has every bar a market bar and its day turn at midnight. |
strategy.direction.all strategy.direction.long strategy.direction.short | The directions for strategy.risk.allow_entry_in. |
chart.bg_color chart.fg_color chart.is_standard chart.is_heikinashi chart.is_renko chart.is_kagi chart.is_linebreak chart.is_pnf chart.is_range | The Edge Chart: a standard candle chart, white on the dark theme's black. The server does not know which theme the reader chose; kinds such as Heikin Ashi or Renko are asked for through ticker.*. |
chart.left_visible_bar_time chart.right_visible_bar_time | The first and last bar the chart draws the script over, in Unix milliseconds — the range the script is reported for, not the part the reader has scrolled into view. |
syminfo.sector syminfo.industry syminfo.country syminfo.employees syminfo.shares_outstanding_float syminfo.shares_outstanding_total syminfo.shareholders | The company behind the symbol, fetched only when the script reads one of them. na when not known (a crypto pair has none of them); shareholders is never known here. |
syminfo.recommendations_buy_strong …_buy …_hold …_sell …_sell_strong …_total …_date | The analysts' recommendations in five tiers (strong buy, buy, hold, sell, strong sell) and their total; na for a company nobody covers. The date is not known here. |
syminfo.target_price_average …_high …_low …_median …_estimates …_date | The analysts' price targets; estimates is the number of analysts covering the company. The date is not known here. |
syminfo.cftc_code | A future's CFTC code (088691 for gold), to read TradingView's COT data with; fetched only when the script reads it, na for a symbol without one. |
syminfo.main_tickerid syminfo.mincontract syminfo.volumetype syminfo.expiration_date | The chart's symbol even inside a request; the smallest quantity the symbol trades in (0.00001 BTC on Binance, 1 for a share); what volume counts ("base", "tick" for forex, "undefined" for an index); and na (no expiry is known). |
strategy.eventrades strategy.avg_trade strategy.avg_winning_trade strategy.avg_losing_trade and their _percent forms | Break-even trades and the averages per trade; the losing average is a positive amount. na while there is no trade. |
strategy.netprofit_percent strategy.grossprofit_percent strategy.grossloss_percent strategy.openprofit_percent | As a percentage of the initial capital; the open profit as a percentage of the realised equity (capital plus net profit). |
strategy.max_runup strategy.max_runup_percent strategy.max_drawdown_percent strategy.max_contracts_held_all …_long …_short | The largest rise of equity from its lowest point before, the deepest fall from a peak (as a percentage), and the largest position held. |
strategy.position_entry_name strategy.account_currency strategy.margin_liquidation_price strategy.opentrades.capital_held | The order that opened the position, the account's currency, the price at which a margin call would close the position (na without margin), and the capital the open trades hold. |
display.* format.* scale.* adjustment.* text.wrap_* text.format_* font.family_* plot.style_* | Accepted as the words they name. plot.style_stepline draws TradingView's step line (stepline_diamond with a diamond on each new value, steplinebr breaking on a bar with no value), areabr an area; the drawing setters read the text.* and font.* words; display and scale change nothing. |
math.pi math.e | Constants. |
Function reference
Parameters marked ? are optional. Any parameter can be given by name: plot(x, color = red). The ta. and math. prefixes are optional: ta.ema and ema are the same. The indicators follow TradingView's own definitions.
Indicators
- sma(source, length)
- Simple moving average. na until the window is full, and while any value in it is na.
- ema(source, length)
- Exponential moving average, seeded with the simple average of its first length values — TradingView's own seeding.
- rma(source, length)
- Wilder's moving average (the one RSI and ATR use), seeded like ema.
- wma(source, length)
- Weighted moving average: the newest value weighs most.
- vwma(source, length)
- Volume-weighted moving average.
- hma(source, length)
- Hull moving average.
- rsi(source, length)
- Relative strength index, Wilder's (0–100). Both averages at zero read 50.
- macd(source, fastlen?, slowlen?, siglen?)
- Gives three values: [macd, signal, histogram]. Defaults 12, 26, 9.
- bb(source, length, mult?)
- Bollinger bands. Gives three values: [middle, upper, lower]; population deviation, mult 2 by default.
- stoch(source, high, low, length)
- Raw stochastic %K (0–100). Smooth it with sma for %D.
- atr(length)
- Average true range, Wilder's.
- cci(source, length)
- Commodity channel index.
- mfi(source, length)
- Money flow index (0–100), from the source and the bar's volume.
- supertrend(factor, atrPeriod)
- Gives two values: [line, direction]. Direction is −1 in an uptrend and 1 in a downtrend, as in Pine.
- stdev(source, length, biased?)
- Standard deviation over the window; biased (population) by default.
- variance(source, length, biased?)
- Variance over the window.
- highest(source, length?)
- The highest value of the last length bars. With one argument it is a length over high.
- lowest(source, length?)
- The lowest value of the last length bars. With one argument it is a length over low.
- highestbars(source, length?)
- How many bars back the highest value was (0 or negative, as in Pine).
- lowestbars(source, length?)
- How many bars back the lowest value was.
- sum(source, length)
- Sum of the last length values.
- cum(source)
- Running total since the first bar.
- ta.max(source)
- The highest value source has had since the first bar.
- ta.min(source)
- The lowest value source has had since the first bar.
- change(source, length?)
- source − source[length] (length 1 by default).
- mom(source, length?)
- Momentum: the same as change.
- roc(source, length)
- Rate of change, in percent.
- percentrank(source, length)
- Percent of the previous length values at or below the current one.
- pivothigh(source, leftbars, rightbars?)
- A swing high, reported rightbars bars after it (it needs them to be sure); na elsewhere. pivothigh(left, right) reads high; a side longer than the chart gives na, as on TradingView.
- pivotlow(source, leftbars, rightbars?)
- A swing low, reported rightbars bars after it. pivotlow(left, right) reads low.
- vwap(source, anchor?, stdev_mult?)
- Volume-weighted average price, starting over whenever anchor is true — by default at each exchange day. With stdev_mult it gives three values: [vwap, upper, lower], bands that many standard deviations away. The value ta.vwap is the day's VWAP of hlc3.
- dmi(diLength, adxSmoothing)
- Directional movement: three values, [+DI, −DI, ADX], Wilder's smoothing as in Pine.
- sar(start, inc, max)
- Parabolic SAR: the acceleration starts at start, grows by inc at each new extreme and stops at max.
- kc(series, length, mult, useTrueRange?) · kcw(…)
- Keltner channels: three values, [middle, upper, lower] — an EMA and mult times an EMA of the true range (of high − low when useTrueRange is false). kcw is the channel's width over its middle.
- bbw(series, length, mult)
- Bollinger band width: the distance between the bands as a percentage of the middle one.
- cmo(series, length)
- Chande momentum oscillator, from −100 to 100.
- cog(source, length)
- Center of gravity: each of the last length values weighted by how far back it is.
- wpr(length)
- Williams %R, from −100 to 0: where the close sits in the last length bars' range.
- tsi(source, short_length, long_length)
- True strength index, from −1 to 1: the change smoothed twice (long, then short) over its absolute value smoothed the same way.
- alma(series, length, offset, sigma, floor?)
- Arnaud Legoux moving average: Gaussian weights centred at offset (0–1) along the window, sigma setting their spread.
- swma(source)
- Symmetrically weighted average of the last four values, weights 1, 2, 2, 1.
- linreg(source, length, offset)
- The least-squares line through the last length values, read offset bars back from the newest.
- correlation(source1, source2, length)
- Pearson correlation of two series over the last length bars, from −1 to 1.
- median(source, length) · mode · range · dev
- Over the last length bars: the median, the most frequent value (the smallest when several tie), the highest minus the lowest, and the mean absolute deviation.
- rci(source, length)
- Rank correlation index, from −100 to 100: how closely the values' ranks follow time — 100 when every bar is higher than the one before.
- percentile_linear_interpolation(source, length, percentage) · percentile_nearest_rank
- The given percentile of the last length values: interpolated between the two nearest ranks, or the nearest rank itself.
- tr(handle_na?)
- The true range as a function: on the first bar, with no previous close, high − low when handle_na is true and na otherwise (the default). The value tr is tr(true).
- pivot_point_levels(type, anchor, developing?)
- An array of eleven levels, [P, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5], from the previous period's high, low and close — a period starting whenever anchor is true, e.g. timeframe.change("1D"). type: "Traditional", "Fibonacci", "Woodie", "Classic", "DM" or "Camarilla"; a level a type has not is na. developing reads the period still running.
Conditions and history
- crossover(a, b)
- true on the bar a moves above b (it was at or below on the bar before).
- crossunder(a, b)
- true on the bar a moves below b.
- cross(a, b)
- true on either crossing.
- rising(source, length)
- true when source rose on each of the last length bars.
- falling(source, length)
- true when source fell on each of the last length bars.
- barssince(condition)
- Bars since condition was last true; na until it has been.
- valuewhen(condition, source, occurrence?)
- The value source had when condition was true — the latest time, or the occurrence-th before it.
- fixnan(x)
- The last value of x that was not na.
- nz(x, replacement?)
- x, or replacement (0 by default) when x is na.
- na(x)
- true when x is na. The bare word na is the value itself.
- hour(time, timezone?) · minute · second · dayofmonth · dayofweek · month · year · weekofyear
- A part of a moment given in Unix milliseconds, in the exchange's zone or the one named ("UTC+3", "Europe/Istanbul"). dayofweek counts 1 = Sunday … 7 = Saturday; weekofyear is the ISO week. Written without brackets they read the bar's own opening time.
- time(timeframe?, session?, timezone?) · time_close(…)
- When the period of timeframe that this bar is in opened (or closes), in Unix milliseconds — na when the bar is outside session ("0930-1600", "0930-1600:23456").
- timestamp(timezone?, year, month, day, hour?, minute?, second?)
- A date as Unix milliseconds, in the exchange's zone unless one is named first. timestamp("2024-03-15T09:30:00+03:00") reads a written date.
- timeframe.in_seconds(timeframe?) · from_seconds(seconds)
- A timeframe's length in seconds (the chart's by default; a month is 2,628,003), and the timeframe text for a number of seconds.
- timeframe.change(timeframe?)
- true on the first bar of a new period of timeframe — a new day for "1D", a new week for "1W".
Maths
- abs(x)
- Absolute value.
- sqrt(x)
- Square root.
- pow(base, exponent)
- base to the power exponent.
- exp(x)
- e to the power x.
- log(x)
- Natural logarithm.
- log10(x)
- Base-10 logarithm.
- round(x, precision?)
- Rounded to precision decimals (0 by default).
- floor(x)
- Rounded down.
- ceil(x)
- Rounded up.
- sign(x)
- −1, 0 or 1.
- max(a, b, …)
- The largest of up to 8,000 values (TradingView ran 4,100).
- min(a, b, …)
- The smallest of up to 8,000 values.
- avg(a, b, …)
- The average of up to 8,000 values.
- sin(x)
- Sine, in radians.
- cos(x)
- Cosine, in radians.
- tan(x)
- Tangent, in radians.
- random(min?, max?, seed?)
- A pseudo-random number from min (0) up to max (1). The same on every run of the script, so a chart does not flicker; the same seed gives the same sequence anywhere.
- round_to_mintick(number)
- Rounded to the symbol's price step, syminfo.mintick.
- acos(x) · asin · atan
- Inverse cosine, sine and tangent, in radians.
- todegrees(x) · toradians(x)
- Radians to degrees, and back.
Text and colour
- str(x, decimals?)
- A number as text, for a mark or an alert. Also str.tostring.
- rgb(red, green, blue, transp?)
- A colour from 0–255 channels; transp 0–100. Also color.rgb.
- color.new(color, transp?)
- The same colour at a transparency from 0 (solid) to 100.
- color.r(color) · color.g · color.b · color.t
- A colour's red, green and blue channels (0–255) and its transparency (0–100). A colour keeps its alpha in 8 bits, so a transparency reads back to the whole percent: color.t(color.new(c, 50)) is 50.
- color.from_gradient(value, bottom_value, top_value, bottom_color, top_color)
- The colour between bottom_color and top_color at value's place between the two values — each channel and the transparency mixed in a straight line, held at the ends. na when value is na.
- int(x) · float(x) · bool(x) · string(x) · color(x)
- Pine's casts. int drops the fraction toward zero (int(-3.7) is -3); bool is false for na and 0 and true otherwise; string and color pass a text or a colour through, and a text like "#FF0000" becomes a colour. na stays na, except in bool.
- str.length(source)
- How many characters a text has.
- str.upper(source) · str.lower(source)
- The text in capitals, or in small letters.
- str.contains(source, str) · startswith · endswith
- true when the text holds str anywhere, at its start or at its end.
- str.pos(source, str)
- Where str first appears (from 0), or na.
- str.replace_all(source, target, replacement)
- Every target replaced.
- str.substring(source, begin_pos, end_pos?)
- The characters from begin_pos up to (not including) end_pos.
- str.split(source, separator)
- The pieces between the separators, as an array of texts.
- str.tonumber(source)
- The number a text writes, or na.
- str.format(format, arg0, arg1, …)
- The format with {0}, {1}, … replaced by the arguments — up to 8,000 of them (TradingView ran 300).
- str.format_time(time, format?, timezone?)
- A moment as text, with Java's letters: "yyyy-MM-dd HH:mm", "dd MMM yy", "EEE"; 'quoted' text as it is.
- str.match(source, regex)
- The first part of the text the regular expression matches, or "". Java's patterns, look-around and back-references included, as on TradingView.
- str.repeat(source, repeat, separator?)
- The text repeated, with separator between the copies.
- str.replace(source, target, replacement, occurrence?) · str.trim(source)
- Replaces one occurrence of target (the first, or the occurrence-th from 0); trim takes the spaces off both ends.
Inputs
- input(defval, title?, minval?, maxval?, step?)
- A setting of the script, its kind taken from defval: a number, true/false, a text or a source such as close. input.int, input.float, input.bool, input.string and input.source all work, and so do input.color (a colour), input.time (an instant in Unix milliseconds; its default may be a timestamp(…)) and input.enum (a field of your own enum, its choices the fields' titles); options = […] lists the choices.
Drawing and alerts
- indicator(title?, overlay?, calc_bars_count?)
- Names the script and says where it draws: over the price (overlay = true) or in its own pane; left out it is over the price, or for a Pine script (one with a //@version line) its own pane, as on TradingView. calc_bars_count = n runs it over the newest n bars only, as on TradingView; the older ones read na.
- library(title, overlay?)
- Declares a library instead of an indicator: the functions, types and methods it exports can be imported by your other scripts, by this title.
- plot(series, title?, color?, linewidth?, style?, pane?)
- Draws a line. style: "line", "histogram", "area", "circles" or "stepline" (plot.style_* too; stepline_diamond and steplinebr draw a step line, areabr an area). color may change bar by bar. pane names a pane under the price.
- hline(price, title?, color?, linestyle?, pane?)
- A horizontal line at a fixed price: "solid", "dashed" (default) or "dotted".
- mark(condition, text?, position?, color?, shape?)
- A marker on each bar where condition is true: position "above" or "below", shape "arrowUp", "arrowDown", "circle" or "square".
- plotshape(series, title?, style?, location?, color?, offset?, text?, textcolor?, editable?, size?)
- A shape on each bar where series is true: style is one of TradingView's twelve (shape.xcross by default, shape.labelup, shape.diamond, shape.flag…), location one of location.abovebar, belowbar, top, bottom or absolute (series' value), offset moves it that many bars. Each call is a row on the settings dialog's Style tab, where its colour, shape and location can be changed.
- plotchar(series, title?, char?, location?, color?, offset?, text?, textcolor?, editable?, size?)
- A character (★ by default) over or under each bar where series is true or non-zero; location.absolute puts it at series' value, location.top and location.bottom on the pane's edges. A Style tab row like plotshape's, with the character in place of the shape.
- plotarrow(series, title?, colorup?, colordown?)
- An up arrow under the bar where series is positive, a down arrow over it where negative.
- plotcandle(open, high, low, close, title?, color?, wickcolor?, bordercolor?) · plotbar(open, high, low, close, title?, color?)
- Candles (or OHLC bars) of your own four series — over the price, or in the script's pane.
- bgcolor(color)
- Colours the background behind the bar; na leaves it clear. In the script's own pane when it has one.
- barcolor(color)
- Colours the chart's own candle on that bar.
- fill(plot1, plot2, color?, title?) · fill(hline1, hline2, color?)
- Fills the band between two plot() or two hline() results — keep them, as p1 = plot(…). The colour may change per bar; with top_color the gradient's top colour is used.
- alert(condition, message?)
- Records an alert on each bar where condition is true; the editor lists this chart's. alert("message") inside an if works too.
- alertcondition(condition, title?, message?)
- Pine's spelling of alert.
- log.info(message, …) · log.warning · log.error
- Writes a message to the script's log, with the bar's time; {0}, {1} … are filled from the arguments as in str.format. The newest 500 are kept.
- runtime.error(message)
- Stops the script with your own error message, on the line that called it.
- max_bars_back(var, num)
- Accepted and changes nothing: every series already keeps its history up to the limit below.
Arrays
- array.new(size?, initial_value?)
- A new array of size elements, all initial_value (na by default). array.new_float, array.new_int, … and array.new<float>() are the same; array.from(a, b, …) makes one from up to 8,000 values (TradingView takes 4,000).
- array.size(id)
- How many elements the array has.
- array.push(id, value) · unshift · insert(id, index, value)
- Adds a value at the end, at the start, or at an index.
- array.pop(id) · shift · remove(id, index)
- Takes out and gives the last element, the first, or the one at an index.
- array.get(id, index) · set(id, index, value)
- Reads or writes the element at an index; a negative index counts from the end. An index outside the array is an error.
- array.first(id) · last(id)
- The first or the last element.
- array.clear(id)
- Empties the array.
- array.includes(id, value) · indexof · lastindexof
- Whether the array holds value, and where it first or last does (−1 when not).
- array.sum(id) · avg · median · stdev · variance
- Statistics of the numbers in the array, na elements skipped.
- array.max(id, nth?) · min(id, nth?)
- The largest or smallest number — or the nth after it.
- array.sort(id, order?) · reverse(id)
- Sorts in place, ascending unless order.descending; reverses in place.
- array.copy(id) · slice(id, from, to) · concat(id, id2)
- copy is a new array; slice is a view of the elements from `from` up to `to` — a change through either shows in both, as in Pine; concat appends id2 to id.
- array.fill(id, value, index_from?, index_to?)
- Sets every element (or a range) to value.
- array.join(id, separator?)
- The elements as one text.
- array.binary_search(id, val) · binary_search_leftmost · binary_search_rightmost
- Where val is in an array sorted ascending, −1 when absent. leftmost gives the element just below it when absent, rightmost the one just above.
- array.every(id) · some(id)
- true when every element is true, or when at least one is.
- array.mode(id) · range · covariance(id, id2, biased?)
- The most frequent number (the smallest when several tie), the largest minus the smallest, and the covariance with another array.
- array.percentile_linear_interpolation(id, percentage) · percentile_nearest_rank · percentrank(id, index)
- A percentile of the numbers, interpolated or at the nearest rank; percentrank is the percentage of the other elements at or below the one at index.
- array.abs(id) · sort_indices(id, order?) · standardize(id)
- New arrays: the absolute values, the indices that would sort the array, and each value's distance from the mean in standard deviations.
Maps
- map.new()
- A new, empty map. map.new<string, float>() is the same.
- map.put(id, key, value) · put_all(id, id2)
- Sets key to value (giving the old value, or na); put_all copies another map in.
- map.get(id, key) · contains(id, key)
- The value under key (na when there is none), and whether there is one.
- map.remove(id, key) · clear(id)
- Takes out one key (giving its value) or all of them.
- map.size(id) · keys · values · copy
- How many keys; the keys or the values as an array, in the order they were first put; a copy.
Matrices
- matrix.new(rows?, columns?, initial_value?)
- A new matrix of rows × columns, every element initial_value (na by default); matrix.new<float>(…) is the same. A reference, like an array.
- matrix.get(id, row, column) · set(id, row, column, value)
- Reads or writes one element; a row or column outside the matrix is an error.
- matrix.rows(id) · columns · elements_count
- Its shape.
- matrix.row(id, row) · col(id, column)
- One row or column, as a new array.
- matrix.add_row(id, row?, array_id?) · add_col · remove_row(id, row?) · remove_col
- Inserts a row or column (of na, or of an array's values) at an index — the end by default — or takes one out.
- matrix.fill(id, value, from_row?, to_row?, from_column?, to_column?)
- Sets every element, or a block of them, to value.
- matrix.copy(id) · submatrix(id, from_row?, to_row?, from_column?, to_column?) · transpose · reshape(id, rows, columns) · reverse
- A copy, a block of it, its transpose; reshape and reverse change it in place.
- matrix.swap_rows(id, row1, row2) · swap_columns · concat(id, id2) · sort(id, column?, order?)
- Swaps two rows or columns, appends id2's rows, or sorts the rows by one column.
- matrix.avg(id) · max · min · median
- Statistics of every element, na skipped.
- matrix.sum(id, id2) · diff · mult(id, id2)
- Element by element with a matrix or a number; mult with a matrix is the matrix product, with an array the matrix times a vector.
- matrix.det(id) · inv · pow(id, power) · rank · trace
- Linear algebra on a square matrix: determinant, inverse (na when singular), integer power, rank and trace.
- matrix.is_square(id) · is_zero · is_identity · is_symmetric
- true when the matrix is of that kind.
- matrix.is_diagonal(id) · is_antidiagonal · is_antisymmetric · is_triangular · is_stochastic · is_binary
- true when the matrix is of that kind. All but is_binary need a square matrix; is_stochastic means no negative element and every row summing to 1; an na element fails every check.
- matrix.abs(id) · mode(id)
- A new matrix of the absolute values, and the most frequent value — the smallest of a tie, na when there is no number.
- matrix.kron(id1, id2)
- The Kronecker product: every element of the first matrix times the whole second one.
- matrix.pinv(id)
- The Moore–Penrose pseudo-inverse, through a singular value decomposition — for any shape, rank-deficient matrices included.
- matrix.eigenvalues(id) · eigenvectors(id)
- A square matrix's eigenvalues as an array, largest first, and its eigenvectors as unit columns in the same order, each with its largest component positive. Exact for a symmetric matrix; for any other, the real parts — a complex pair's vector columns are na.
Other symbols and timeframes
- request.security(symbol, timeframe, expression, gaps?, lookahead?, ignore_invalid_symbol?, currency?)
- The expression computed on another symbol or timeframe, lined up with this chart's bars without looking ahead. The symbol and timeframe may be written out or computed as the script runs — inside a function, from an array in a loop. Also security.
- request.security_lower_tf(symbol, timeframe, expression)
- The expression on a lower timeframe, as an array per chart bar: one element for every lower bar that opened inside it, oldest first — an empty array on a bar with none. Read as deep as TradingView reads it: the newest 100,000 lower bars, or, when the script sets calc_bars_count, as many as a chart of that timeframe holds; older chart bars get an empty array. A timeframe above the chart's stops the script, or reads na with `ignore_invalid_timeframe = true`.
- request.currency_rate(from, to)
- How many units of `to` one unit of `from` buys, on this chart's bars (FX_IDC rates, lined up like request.security); 1 for the same currency.
- request.financial(symbol, financial_id, period, gaps?)
- A company's reported figure — TOTAL_REVENUE, NET_INCOME, EARNINGS_PER_SHARE_DILUTED, … — for period "FQ" (quarter), "FY" (year), "FH" (half-year), "TTM" or "D" (daily, read at the finest period the id is reported for), as a series that changes when a new period is dated. The symbol and id may be computed as the script runs. na for an instrument with no statements.
- request.earnings(ticker, field?, gaps?)
- Earnings per share at each release: earnings.actual (the default) or earnings.estimate.
- request.dividends(ticker, field?, gaps?)
- The dividend per share, from each ex-date: dividends.gross (the default).
- request.splits(ticker, field, gaps?)
- A split's ratio from its date: splits.numerator and splits.denominator.
- request.economic(country_code, field, gaps?)
- An economic series — "US", "GDP" reads ECONOMICS:USGDP — one value per observation, from the end of its period.
- request.seed(source, symbol, expression)
- The expression on a published seed series, SEED_<SOURCE>:<SYMBOL>. The seeds still answer, but their data stops in February 2023.
- request.quandl(ticker, gaps?, index?, ignore_invalid_symbol?)
- What TradingView does with it: the symbol it builds (QUANDL:ticker|index) no longer resolves there, so the script stops with "Invalid symbol" — or reads na with ignore_invalid_symbol = true. request.economic and request.financial cover the common series.
- __dividends_tickerid(symbol) · __earnings_tickerid(symbol) · __splits_tickerid(symbol)
- TradingView's undocumented event series of a symbol — ESD_FACTSET:EXCHANGE;TICKER;DIVIDENDS and its kin — for request.security(…, "D", high): a dividend's bar has its ex-date as high and its amount as close.
- request.footprint(ticks_per_row, va_percent?, imbalance_percent?)
- The bar's footprint, read from TradingView's own: buy_volume, sell_volume, delta, total_volume and the poc, vah and val rows (the value area holds va_percent of the volume) are TradingView's to the digit, and na on a bar TradingView built none for (it gives none on many of BTCUSDT's busiest bars). The rows in between are estimated from the lower-timeframe bars inside the bar and scaled to TradingView's totals. A footprint answers buy_volume, sell_volume, delta, total_volume, poc, vah, val, rows and get_row_by_price; a volume_row answers up_price, down_price, buy_volume, sell_volume, delta, total_volume, has_buy_imbalance and has_sell_imbalance (imbalance_percent against the diagonal row). If TradingView cannot be reached the whole footprint is estimated from the lower bars.
- ticker.heikinashi(symbol) · renko(symbol, style, param, request_wicks?, source?) · linebreak(symbol, number_of_lines) · kagi(symbol, reversal) · pointfigure(symbol, source, style, param, reversal)
- A ticker id for another chart type, to read with request.security: Heikin Ashi candles, Renko bricks (style "Traditional", "ATR" or "PercentageLTP"), line break, Kagi or point & figure. A brick is seen at the close of the bar that completed it; wicks are not drawn.
- syminfo.prefix(symbol) · syminfo.ticker(symbol)
- The exchange and the name of a symbol given as text: syminfo.prefix("NASDAQ:AAPL") is "NASDAQ", syminfo.ticker(…) "AAPL".
- ticker.new(prefix, ticker, session?, adjustment?) · standard(symbol?) · modify(tickerid, …) · inherit(from_tickerid, symbol)
- Builds a ticker id: from an exchange and a ticker, back to the plain chart type, or with another symbol's chart type. Session and adjustment change nothing here.
Strategies
- strategy(title, shorttitle?, overlay?, …, pyramiding?, …, default_qty_type?, default_qty_value?, initial_capital?, currency?, slippage?, commission_type?, commission_value?, process_orders_on_close?, …, margin_long?, margin_short?, …)
- Declares a strategy instead of an indicator: its orders are filled over the bars and the editor shows the backtest.
- strategy.entry(id, direction, qty?, limit?, stop?, oca_name?, oca_type?, comment?)
- Opens (or adds to) a position: strategy.long or strategy.short. Without limit or stop it fills at the next bar's open; an entry against the position reverses it.
- strategy.exit(id, from_entry?, qty?, qty_percent?, profit?, limit?, loss?, stop?, trail_price?, trail_points?, trail_offset?, oca_name?, comment?, comment_profit?, comment_loss?, comment_trailing?, …)
- A take-profit and a stop for an entry: limit and stop as prices, or profit and loss in ticks; trail_price (or trail_points in ticks) arms a trailing stop that follows the best price trail_offset ticks behind. Cancelled once its position is closed.
- strategy.close(id, comment?, qty?, qty_percent?, …, immediately?) · close_all(comment?, …, immediately?)
- Closes an entry, or everything, at the next bar's open — or at this close with immediately = true.
- strategy.cancel(id) · cancel_all()
- Cancels orders and exits still waiting.
- strategy.opentrades.entry_price(trade_num) · entry_bar_index · entry_time · entry_id · size · profit
- One open trade, trade_num 0 the oldest: its entry price, bar, time, order id, size (negative when short) and open profit. na past the last.
- strategy.closedtrades.entry_price(trade_num) · exit_price · entry_bar_index · exit_bar_index · entry_time · exit_time · entry_id · exit_id · profit · size
- One closed trade, trade_num 0 the first: where and when it entered and exited, its order ids, its profit and size.
- strategy.closedtrades.commission(trade_num) · profit_percent · max_runup · max_runup_percent · max_drawdown · max_drawdown_percent · entry_comment · exit_comment
- A closed trade's fees on both sides, its profit as a percentage of its entry value, the most it was ever up and down while open — in money and as a percentage of the entry — and its orders' comments. Run-up and drawdown come from the bars' highs and lows: the bar a trade closed on counts only its exit price.
- strategy.opentrades.commission(trade_num) · profit_percent · max_runup · max_runup_percent · max_drawdown · max_drawdown_percent · entry_comment
- The same figures for a trade still open, its profit read at the current close.
- strategy.risk.allow_entry_in(value)
- Only entries in strategy.direction.long (or short) open a position; an entry the other way only closes the one open.
- strategy.risk.max_drawdown(value, type) · max_intraday_loss(value, type) · max_intraday_filled_orders(count) · max_cons_loss_days(count)
- Past the limit, every waiting order is cancelled, every position closes at the next bar's open and no entry fills — for good for a drawdown or losing days, until the next day for the intraday ones. type: strategy.percent_of_equity or strategy.cash.
- strategy.risk.max_position_size(contracts)
- The largest position allowed; an entry past it is trimmed to fit.
- strategy.convert_to_account(value) · convert_to_symbol(value) · default_entry_qty(fill_price)
- An amount turned from the symbol's currency into the account's, and back; and the quantity an entry would take at fill_price with the declared default size.
Labels, lines and boxes
- linefill.new(line1, line2, color) · set_color · get_line1 · get_line2 · delete
- Fills the space between two lines made with line.new.
- label.new(x, y, text?, xloc?, yloc?, color?, style?, textcolor?, size?, textalign?, tooltip?, text_font_family?, text_formatting?)
- A label at bar x (or a time, with xloc.bar_time) and price y; yloc.abovebar / belowbar put it over or under the bar. Gives its id.
- label.set_text(id, text) · set_x · set_y · set_xy · set_color · …
- Changes one property of a label; na or a deleted id changes nothing.
- label.set_point(id, point) · set_text_font_family · set_text_formatting
- Moves a label to a chart.point — its time when the label's xloc is xloc.bar_time, its index otherwise — and sets its face (font.family_default or font.family_monospace) and weight (text.format_bold, text.format_italic, added together for both).
- label.get_text(id) · get_x · get_y
- Reads a label back.
- line.new(x1, y1, x2, y2, xloc?, extend?, color?, style?, width?)
- A line between two points; extend.right (left, both) carries it on. Styles: line.style_solid, dashed, dotted, arrow_left, arrow_right, arrow_both.
- line.set_xy1(id, x, y) · set_xy2 · set_x1 · … · set_color · set_width
- Changes one property of a line.
- line.set_first_point(id, point) · set_second_point(id, point)
- Moves a line's first or second end to a chart.point, read as the line reads x.
- line.get_price(id, x) · get_x1 · get_y1 · get_x2 · get_y2
- The line's price at bar x, and its points.
- box.new(left, top, right, bottom, border_color?, border_width?, border_style?, extend?, xloc?, bgcolor?, text?, text_size?, text_color?, text_halign?, text_valign?, text_wrap?, text_font_family?, text_formatting?)
- A rectangle from bar left to bar right between two prices, with a text inside if you like.
- box.set_lefttop(id, left, top) · set_rightbottom · set_left · … · set_bgcolor · set_text
- Changes one property of a box.
- box.set_top_left_point(id, point) · set_bottom_right_point · set_xloc(id, left, right, xloc)
- Moves a box's corners to chart.points, or its two sides with an xloc.
- box.set_text_wrap(id, text_wrap) · set_text_valign · set_text_font_family · set_text_formatting
- The box's text: text.wrap_auto breaks it into lines that fit the box, text_valign puts it at the top, middle or bottom, and the face and weight as on a label.
- box.get_top(id) · get_bottom · get_left · get_right
- Reads a box back.
- label.delete(id) · line.delete · box.delete · label.copy · line.copy · box.copy
- Removes a drawing, or makes a copy of it and gives the copy's id.
- chart.point.new(time, index, price) · from_index(index, price) · from_time(time, price) · now(price?) · copy(id)
- A point on the chart — a bar (index) or a time, and a price — with .time, .index and .price fields; now() is this bar at its close (or the given price).
- label(na) · line(na) · box(na) · linefill(na) · polyline(na) · table(na)
- A typed na, to declare an object before it exists: label l = label(na). An object of the same kind passes through.
- polyline.new(points, curved?, closed?, xloc?, line_color?, fill_color?, line_style?, line_width?) · polyline.delete(id)
- A line through an array of chart.point, in order: curved smooths it, closed joins the last point to the first and fill_color fills the shape. xloc.bar_time places the points by their time.
Tables
- table.new(position, columns, rows, bgcolor?, frame_color?, frame_width?, border_color?, border_width?)
- A table pinned to the chart: position.top_right, middle_center, bottom_left, …. Any shape up to 20,000 cells (TradingView: 10,000).
- table.cell(table_id, column, row, text?, width?, height?, text_color?, text_halign?, text_valign?, text_size?, bgcolor?, tooltip?, text_font_family?, text_formatting?)
- Writes one cell; rows and columns nobody writes to take no room.
- table.cell_set_text(table_id, column, row, text) · cell_set_bgcolor · cell_set_text_color · …
- Changes one property of a cell.
- table.set_position(table_id, position) · set_bgcolor · set_border_color · set_frame_color
- Changes the table itself.
- table.merge_cells(table_id, start_column, start_row, end_column, end_row)
- Joins a range of cells into one that shows its top-left cell; a later merge that overlaps an earlier one replaces it.
- table.cell_set_width(table_id, column, row, width) · cell_set_height · cell_set_tooltip · cell_set_text_valign · cell_set_text_font_family · cell_set_text_formatting
- A cell's width and height as percentages of the chart (0 fits the text), the tooltip shown when the pointer rests on it, and its vertical alignment, face and weight.
- table.set_border_width(table_id, width) · set_frame_width
- The width of the lines between cells and of the frame around the table.
- table.clear(table_id, start_column?, start_row?, end_column?, end_row?) · table.delete(table_id)
- Empties cells (all of them by default), or removes the table.
Coming from Pine Script
Most Pine indicators and strategies run as they are — every Pine version from v1 to v6 (v1–v4's study, security, unprefixed names and input(…, type = …) included; up to v5 and/or evaluate both sides, as on TradingView): the //@version line, the ta. and math. prefixes, input.int and friends, typed declarations such as float x = 1 or array<float> xs = …, :=, switch, arrays, maps and matrices, type, enum and method, library / export / import, request.security (with currency =), request.security_lower_tf, request.currency_rate, request.financial, request.earnings, request.dividends, request.splits, request.economic and request.seed, varip and calc_on_every_tick, strategy.* (trailing stops, OCA, slippage, margin and the account currency included), label / line / box / polyline / table, plotshape and alertcondition are all accepted; Pine arguments that mean nothing here (tooltip, group, offset…) are quietly ignored.
Not there, or approximate, and why:
request.quandl: TradingView no longer serves it either — the symbol it builds does not resolve there — so here, as there, the script stops with "Invalid symbol", or reads na withignore_invalid_symbol = true.request.economiccovers the common economic series andrequest.financialthe company figures.request.footprint's totals, point of control and value area are TradingView's own; the rows in between are estimated from lower-timeframe bars rather than the trades themselves (above): two trades at one price inside a second are one row, and which side took them is an estimate.- The strategy engine follows TradingView's rules; where the equity and the margin are exactly equal (all the equity on a 100% margin, at a price that is a whole number of ticks) the last bit of floating point can turn a one-unit margin call, or one unit of a size, either way — seen on AAPL's penny bars before 1990.
- Every other built-in name of Pine v6 is here.
Limits
A script runs on our servers, and every run is bounded so everybody's chart stays fast. A script that meets a limit stops with an error that says which.
| LIMIT | VALUE |
|---|---|
| Script length | 10240 KB |
| Run time | 80 seconds |
| Total steps | 50,000,000,000 |
| Loop turns on one bar | 100,000,000 |
History (x[n]) / length | 20,000 / 20,000 |
plot / hline | 128 / 128 |
mark calls / markers | 128 / 20,000 |
| Alerts | 2,000 |
| Inputs | 1000 |
| Array and map elements (made in all) / one array | 100,000,000,000 / 1,000,000 |
| Memory | A run stops when the server's memory nears full |
Series read with request.* | 128 |
Company figures (request.financial …) | 128 |
| Recursion depth | 500 |
| Labels / lines / boxes (each) | 50 — up to 1000 |
| Polylines | 50 — up to 200 |
| Tables / cells in one table | 18 / 20,000 |
Arguments of array.from, math.max, str.format … | 8,000 |
Lower-timeframe bars (request.security_lower_tf) | 100,000 |
| Strategy trades | 18,000 |
| Saved scripts | 50 |
The limits are at least twice TradingView's (bar count alone excepted). Numeric loops — at the top level and in functions that draw or write their object's fields too — run with their numbers held as numbers, and the heavy published ML indicators finish sooner than on TradingView over the same bars. Edge Script is an analysis tool; what it draws is computed from past prices and is not investment advice.