//@version=5
indicator("bar_index")
plot(bar_index)
plot(bar_index > 5000 ? close : 0)
//@version=5
indicator("box.all")
//delete all boxes
box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
a_allboxes = box.all
if array.size(a_allboxes) > 0
for i = 0 to array.size(a_allboxes) - 1
box.delete(array.get(a_allboxes, i))
//@version=5
indicator("label.all")
//delete all labels
label.new(bar_index, close)
a_alllabels = label.all
if array.size(a_alllabels) > 0
for i = 0 to array.size(a_alllabels) - 1
label.delete(array.get(a_alllabels, i))
//@version=5
strategy("mark Last X bars For backtesting", overlay = true, calc_on_every_tick = true)
lastbarsFilterinput = input.int(100, "bars Count:")
// Here, we store the 'last_bar_index' value that is known from the beginning of the script's calculation.
// the 'last_bar_index' will change when new real-time bars appear, so we declare 'lastbar' with the 'var' keyword.
var lastbar = last_bar_index
// Check if the current bar_index is 'lastbarsFilterinput' removed from the last bar on the chart, or the chart is traded in real-time.
allowedtotrade = (lastbar - bar_index <= lastbarsFilterinput) or barstate.isrealtime
bgcolor(allowedtotrade ? color.new(color.green, 80) : na)
//@version=5
indicator("line.all")
//delete all lines
line.new(bar_index - 10, close, bar_index, close)
a_alllines = line.all
if array.size(a_alllines) > 0
for i = 0 to array.size(a_alllines) - 1
line.delete(array.get(a_alllines, i))
//@version=5
indicator("na")
// CORRECT
// plot no value when on bars zero to nine. plot `close` on other bars.
plot(bar_index < 10 ? na : close)
// CORRECT aLTERNaTiVE
// initialize `a` to `na`. Reassign `close` to `a` on bars 10 and later.
float a = na
if bar_index >= 10
a := close
plot(a)
// iNCORRECT
// trying to test the preceding bar's `close` for `na`.
// Will not work correctly on bar zero, when `close[1]` is `na`.
plot(close[1] == na ? close : close[1])
// CORRECT
// use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// CORRECT aLTERNaTiVE
// `nz()` tests `close[1]` for `na`. it returns `close[1]` if it is not `na`, and `close` if it is.
plot(nz(close[1], close))
//@version=5
strategy("Margin call management", overlay = true, margin_long = 25, margin_short = 25,
default_qty_type = strategy.percent_of_equity, default_qty_value = 395)
float maFast = ta.sma(close, 14)
float maslow = ta.sma(close, 28)
if ta.crossover(maFast, maslow)
strategy.entry("Long", strategy.long)
if ta.crossunder(maFast, maslow)
strategy.entry("short", strategy.short)
changepercent(v1, v2) =>
float result = (v1 - v2) * 100 / math.abs(v2)
// exit when we're 10% away from a margin call, to prevent it.
if math.abs(changepercent(close, strategy.margin_liquidation_price)) <= 10
strategy.close("Long")
strategy.close("short")
//@version=5
indicator("syminfo.prefix")
// if current chart symbol is 'baTs:MsFT' then syminfo.prefix is 'baTs'.
if barstate.islastconfirmedhistory
label.new(bar_index, high, text=syminfo.prefix)
//@version=5
indicator("syminfo.root")
// if the current chart symbol is continuous futures ('Es1!'), it would display 'Es'.
if barstate.islastconfirmedhistory
label.new(bar_index, high, syminfo.root)
//@version=5
indicator("intraday intensity index")
plot(ta.iii, color=color.yellow)
// the same on pine
f_iii() =>
(2 * close - high - low) / ((high - low) * volume)
plot(f_iii())
//@version=5
indicator("Negative Volume index")
plot(ta.nvi, color=color.yellow)
// the same on pine
f_nvi() =>
float ta_nvi = 1.0
float prevNvi = (nz(ta_nvi[1], 0.0) == 0.0) ? 1.0: ta_nvi[1]
if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
ta_nvi := prevNvi
else
ta_nvi := (volume < nz(volume[1], 0.0)) ? prevNvi + ((close - close[1]) / close[1]) * prevNvi : prevNvi
result = ta_nvi
plot(f_nvi())
//@version=5
indicator("On balance Volume")
plot(ta.obv, color=color.yellow)
// the same on pine
f_obv() =>
ta.cum(math.sign(ta.change(close)) * volume)
plot(f_obv())
//@version=5
indicator("positive Volume index")
plot(ta.pvi, color=color.yellow)
// the same on pine
f_pvi() =>
float ta_pvi = 1.0
float prevpvi = (nz(ta_pvi[1], 0.0) == 0.0) ? 1.0: ta_pvi[1]
if nz(close, 0.0) == 0.0 or nz(close[1], 0.0) == 0.0
ta_pvi := prevpvi
else
ta_pvi := (volume > nz(volume[1], 0.0)) ? prevpvi + ((close - close[1]) / close[1]) * prevpvi : prevpvi
result = ta_pvi
plot(f_pvi())
//@version=5
indicator("price-Volume trend")
plot(ta.pvt, color=color.yellow)
// the same on pine
f_pvt() =>
ta.cum((ta.change(close) / close[1]) * volume)
plot(f_pvt())
//@version=5
indicator("Williams accumulation/Distribution")
plot(ta.wad, color=color.yellow)
// the same on pine
f_wad() =>
trueHigh = math.max(high, close[1])
trueLow = math.min(low, close[1])
mom = ta.change(close)
gain = (mom > 0) ? close - trueLow : (mom < 0) ? close - trueHigh : 0
ta.cum(gain)
plot(f_wad())
//@version=5
indicator("Williams variable accumulation/Distribution")
plot(ta.wvad, color=color.yellow)
// the same on pine
f_wvad() =>
(close - open) / (high - low) * volume
plot(f_wvad())
//@version=5
indicator("table.all")
//delete all tables
table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
a_alltables = table.all
if array.size(a_alltables) > 0
for i = 0 to array.size(a_alltables) - 1
table.delete(array.get(a_alltables, i))
alert(message, freq) → void
//@version=5
indicator("`alert()` example", "", true)
ma = ta.sma(close, 14)
xup = ta.crossover(close, ma)
if xup
// trigger the alert the first time a cross occurs during the real-time bar.
alert("price (" + str.tostring(close) + ") crossed over Ma (" + str.tostring(ma) + ").", alert.freq_once_per_bar)
plot(ma)
plotchar(xup, "xup", "▲", location.top, size = size.tiny)
alertcondition(condition, title, message) → void
//@version=5
indicator("alertcondition", overlay=true)
alertcondition(close >= open, title='alert on Green bar', message='Green bar!')
array.abs(id) → float[]
array.abs(id) → int[]
array.avg(id) → series float
array.avg(id) → series int
//@version=5
indicator("array.avg example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.avg(a))
array.binary_search(id, val) → series int
//@version=5
indicator("array.binary_search")
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search(a, 0) // 1
plot(position)
array.binary_search_leftmost(id, val) → series int
//@version=5
indicator("array.binary_search_leftmost")
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_leftmost(a, 3) // 2
plot(position)
//@version=5
indicator("array.binary_search_leftmost, repetitive elements")
a = array.from(4, 5, 5, 5)
// Returns the index of the first instance.
position = array.binary_search_leftmost(a, 5)
plot(position) // plots 1
array.binary_search_rightmost(id, val) → series int
//@version=5
indicator("array.binary_search_rightmost")
a = array.from(5, -2, 0, 9, 1)
array.sort(a) // [-2, 0, 1, 5, 9]
position = array.binary_search_rightmost(a, 3) // 3
plot(position)
//@version=5
indicator("array.binary_search_rightmost, repetitive elements")
a = array.from(4, 5, 5, 5)
// Returns the index of the last instance.
position = array.binary_search_rightmost(a, 5)
plot(position) // plots 3
array.clear(id) → void
//@version=5
indicator("array.clear example")
a = array.new_float(5,high)
array.clear(a)
array.push(a, close)
plot(array.get(a,0))
plot(array.size(a))
array.concat(id1, id2) → array<type>
//@version=5
indicator("array.concat example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
array.push(a, high[i])
array.push(b, low[i])
c = array.concat(a,b)
plot(array.size(a))
plot(array.size(b))
plot(array.size(c))
array.copy(id) → array<type>
//@version=5
indicator("array.copy example")
length = 5
a = array.new_float(length, close)
b = array.copy(a)
a := array.new_float(length, open)
plot(array.sum(a) / length)
plot(array.sum(b) / length)
array.covariance(id1, id2, biased) → series float
//@version=5
indicator("array.covariance example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
array.push(b, open[i])
plot(array.covariance(a, b))
array.fill(id, value, index_from, index_to) → void
//@version=5
indicator("array.fill example")
a = array.new_float(10)
array.fill(a, close)
plot(array.sum(a))
array.first(id) → series <type>
//@version=5
indicator("array.first example")
arr = array.new_int(3, 10)
plot(array.first(arr))
array.from(arg0, arg1, ...) → type[]
array.from(arg0, arg1, ...) → label[]
array.from(arg0, arg1, ...) → line[]
array.from(arg0, arg1, ...) → box[]
array.from(arg0, arg1, ...) → table[]
array.from(arg0, arg1, ...) → linefill[]
array.from(arg0, arg1, ...) → string[]
array.from(arg0, arg1, ...) → color[]
array.from(arg0, arg1, ...) → int[]
array.from(arg0, arg1, ...) → float[]
array.from(arg0, arg1, ...) → bool[]
//@version=5
indicator("array.from_example", overlay = false)
arr = array.from("Hello", "World!") // arr (string[]) will contain 2 elements: {Hello}, {World!}.
plot(close)
array.get(id, index) → series <type>
//@version=5
indicator("array.get example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i] - open[i])
plot(array.get(a, 9))
array.includes(id, value) → series bool
//@version=5
indicator("array.includes example")
a = array.new_float(5,high)
p = close
if array.includes(a, high)
p := open
plot(p)
array.indexof(id, value) → series int
//@version=5
indicator("array.indexof example")
a = array.new_float(5,high)
index = array.indexof(a, high)
plot(index)
array.insert(id, index, value) → void
//@version=5
indicator("array.insert example")
a = array.new_float(5, close)
array.insert(a, 0, open)
plot(array.get(a, 5))
array.join(id, separator) → series string
//@version=5
indicator("array.join example")
a = array.new_float(5, 5)
label.new(bar_index, close, array.join(a, ","))
array.last(id) → series <type>
//@version=5
indicator("array.last example")
arr = array.new_int(3, 10)
plot(array.last(arr))
array.lastindexof(id, value) → series int
//@version=5
indicator("array.lastindexof example")
a = array.new_float(5,high)
index = array.lastindexof(a, high)
plot(index)
array.max(id) → series float
array.max(id) → series int
array.max(id, nth) → series float
array.max(id, nth) → series int
//@version=5
indicator("array.max")
a = array.from(5, -2, 0, 9, 1)
thirdHighest = array.max(a, 2) // 1
plot(thirdHighest)
array.median(id) → series float
array.median(id) → series int
//@version=5
indicator("array.median example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.median(a))
array.min(id) → series float
array.min(id) → series int
array.min(id, nth) → series float
array.min(id, nth) → series int
//@version=5
indicator("array.min")
a = array.from(5, -2, 0, 9, 1)
secondlowest = array.min(a, 1) // 0
plot(secondlowest)
array.mode(id) → series float
array.mode(id) → series int
//@version=5
indicator("array.mode example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.mode(a))
array.new_bool(size, initial_value) → bool[]
//@version=5
indicator("array.new_bool example")
length = 5
a = array.new_bool(length, close > open)
plot(array.get(a, 0) ? close : open)
array.new_box(size, initial_value) → box[]
//@version=5
indicator("array.new_box example")
box[] boxes = array.new_box()
array.push(boxes, box.new(time, close, time+2, low, xloc=xloc.bar_time))
plot(1)
array.new_color(size, initial_value) → color[]
//@version=5
indicator("array.new_color example")
length = 5
a = array.new_color(length, color.red)
plot(close, color = array.get(a, 0))
array.new_float(size, initial_value) → float[]
//@version=5
indicator("array.new_float example")
length = 5
a = array.new_float(length, close)
plot(array.sum(a) / length)
array.new_int(size, initial_value) → int[]
//@version=5
indicator("array.new_int example")
length = 5
a = array.new_int(length, int(close))
plot(array.sum(a) / length)
array.new_label(size, initial_value) → label[]
//@version=5
indicator("array.new_label example")
var a = array.new_label()
l = label.new(bar_index, close, "some text")
array.push(a, l)
if close > close[1] and close[1] > close[2]
// remove all labels
size = array.size(a) - 1
for i = 0 to size
lb = array.get(a, i)
label.delete(lb)
array.new_line(size, initial_value) → line[]
//@version=5
indicator("array.new_line example")
// draw last 15 lines
var a = array.new_line()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
array.new_linefill(size, initial_value) → linefill[]
array.new_string(size, initial_value) → string[]
//@version=5
indicator("array.new_string example")
length = 5
a = array.new_string(length, "text")
label.new(bar_index, close, array.get(a, 0))
array.new_table(size, initial_value) → table[]
//@version=5
indicator("table array")
table[] tables = array.new_table()
array.push(tables, table.new(position = position.top_left, rows = 1, columns = 2, bgcolor = color.yellow, border_width=1))
plot(1)
array.new<type>(size, initial_value) → array<type>
//@version=5
indicator("array.new<string> example")
a = array.new<string>(1, "Hello, World!")
label.new(bar_index, close, array.get(a, 0))
//@version=5
indicator("array.new<color> example")
a = array.new<color>()
array.push(a, color.red)
array.push(a, color.green)
plot(close, color = array.get(a, close > open ? 1 : 0))
//@version=5
indicator("array.new<float> example")
length = 5
var a = array.new<float>(length, close)
if array.size(a) == length
array.remove(a, 0)
array.push(a, close)
plot(array.sum(a) / length, "sMa")
//@version=5
indicator("array.new<line> example")
// draw last 15 lines
var a = array.new<line>()
array.push(a, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(a) > 15
ln = array.shift(a)
line.delete(ln)
array.percentile_linear_interpolation(id, percentage) → series float
array.percentile_linear_interpolation(id, percentage) → series int
array.percentile_nearest_rank(id, percentage) → series float
array.percentile_nearest_rank(id, percentage) → series int
array.percentrank(id, index) → series float
array.percentrank(id, index) → series int
array.pop(id) → series <type>
//@version=5
indicator("array.pop example")
a = array.new_float(5,high)
removedel = array.pop(a)
plot(array.size(a))
plot(removedel)
array.push(id, value) → void
//@version=5
indicator("array.push example")
a = array.new_float(5, 0)
array.push(a, open)
plot(array.get(a, 5))
array.range(id) → series float
array.range(id) → series int
//@version=5
indicator("array.range example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.range(a))
array.remove(id, index) → series <type>
//@version=5
indicator("array.remove example")
a = array.new_float(5,high)
removedel = array.remove(a, 0)
plot(array.size(a))
plot(removedel)
array.reverse(id) → void
//@version=5
indicator("array.reverse example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.get(a, 0))
array.reverse(a)
plot(array.get(a, 0))
array.set(id, index, value) → void
//@version=5
indicator("array.set example")
a = array.new_float(10)
for i = 0 to 9
array.set(a, i, close[i])
plot(array.sum(a) / 10)
array.shift(id) → series <type>
//@version=5
indicator("array.shift example")
a = array.new_float(5,high)
removedel = array.shift(a)
plot(array.size(a))
plot(removedel)
array.size(id) → series int
//@version=5
indicator("array.size example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
// note that changes in slice also modify original array
slice = array.slice(a, 0, 5)
array.push(slice, open)
// size was changed in slice and in original array
plot(array.size(a))
plot(array.size(slice))
array.slice(id, index_from, index_to) → array<type>
//@version=5
indicator("array.slice example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
// take elements from 0 to 4
// *note that changes in slice also modify original array
slice = array.slice(a, 0, 5)
plot(array.sum(a) / 10)
plot(array.sum(slice) / 5)
array.sort(id, order) → void
//@version=5
indicator("array.sort example")
a = array.new_float(0,0)
for i = 0 to 5
array.push(a, high[i])
array.sort(a, order.descending)
if barstate.islast
label.new(bar_index, close, str.tostring(a))
array.sort_indices(id, order) → int[]
//@version=5
indicator("array.sort_indices")
a = array.from(5, -2, 0, 9, 1)
sortedindices = array.sort_indices(a) // [1, 2, 4, 0, 3]
indexOfsmallestValue = array.get(sortedindices, 0) // 1
smallestValue = array.get(a, indexOfsmallestValue) // -2
plot(smallestValue)
array.standardize(id) → float[]
array.standardize(id) → int[]
//@version=5
indicator("array.standardize example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
b = array.standardize(a)
plot(array.min(b))
plot(array.max(b))
array.stdev(id, biased) → series float
array.stdev(id, biased) → series int
//@version=5
indicator("array.stdev example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.stdev(a))
array.sum(id) → series float
array.sum(id) → series int
//@version=5
indicator("array.sum example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.sum(a))
array.unshift(id, value) → void
//@version=5
indicator("array.unshift example")
a = array.new_float(5, 0)
array.unshift(a, open)
plot(array.get(a, 0))
array.variance(id, biased) → series float
array.variance(id, biased) → series int
//@version=5
indicator("array.variance example")
a = array.new_float(0)
for i = 0 to 9
array.push(a, close[i])
plot(array.variance(a))
barcolor(color, offset, editable, show_last, title, display) → void
//@version=5
indicator("barcolor example", overlay=true)
barcolor(close < open ? color.black : color.white)
bgcolor(color, offset, editable, show_last, title, display) → void
//@version=5
indicator("bgcolor example", overlay=true)
bgcolor(close < open ? color.new(color.red,70) : color.new(color.green, 70))
bool(x) → const bool
bool(x) → input bool
bool(x) → simple bool
bool(x) → series bool
box.copy(id) → series box
//@version=5
indicator('Last 50 bars price ranges', overlay = true)
LOOKbaCK = 50
highest = ta.highest(LOOKbaCK)
lowest = ta.lowest(LOOKbaCK)
if barstate.islastconfirmedhistory
var boxLast = box.new(bar_index[LOOKbaCK], highest, bar_index, lowest, bgcolor = color.new(color.green, 80))
var boxprev = box.copy(boxLast)
box.set_lefttop(boxprev, bar_index[LOOKbaCK * 2], highest[50])
box.set_rightbottom(boxprev, bar_index[LOOKbaCK], lowest[50])
box.set_bgcolor(boxprev, color.new(color.red, 80))
box.delete(id) → void
box.get_bottom(id) → series float
box.get_left(id) → series int
box.get_right(id) → series int
box.get_top(id) → series float
box.new(top_left, bottom_right, border_color, border_width, border_style, extend, xloc, bgcolor, text, text_size, text_color, text_halign, text_valign, text_wrap, text_font_family) → series box
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) → series box
//@version=5
indicator("box.new")
var b = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
box.set_lefttop(b, time, 100)
box.set_rightbottom(b, time + 60 * 60 * 24, 500)
box.set_bgcolor(b, color.green)
box.set_bgcolor(id, color) → void
box.set_border_color(id, color) → void
box.set_border_style(id, style) → void
box.set_border_width(id, width) → void
box.set_bottom(id, bottom) → void
box.set_bottom_right_point(id, point) → void
box.set_extend(id, extend) → void
box.set_left(id, left) → void
box.set_lefttop(id, left, top) → void
box.set_right(id, right) → void
box.set_rightbottom(id, right, bottom) → void
box.set_text(id, text) → void
box.set_text_color(id, text_color) → void
box.set_text_font_family(id, text_font_family) → void
//@version=5
indicator("Example of setting the box font")
if barstate.islastconfirmedhistory
b = box.new(bar_index, open-ta.tr, bar_index-50, open-ta.tr*5, text="monospace")
box.set_text_font_family(b, font.family_monospace)
box.set_text_halign(id, text_halign) → void
box.set_text_size(id, text_size) → void
box.set_text_valign(id, text_valign) → void
box.set_text_wrap(id, text_wrap) → void
box.set_top(id, top) → void
box.set_top_left_point(id, point) → void
chart.point.copy(id) → chart.point
chart.point.from_index(index, price) → chart.point
chart.point.from_time(time, price) → chart.point
chart.point.new(time, index, price) → chart.point
chart.point.now(price) → chart.point
color(x) → const color
color(x) → input color
color(x) → simple color
color(x) → series color
color.b(color) → const float
color.b(color) → input float
color.b(color) → series float
//@version=5
indicator("color.b", overlay=true)
plot(color.b(color.blue))
color.from_gradient(value, bottom_value, top_value, bottom_color, top_color) → series color
//@version=5
indicator("color.from_gradient", overlay=true)
color1 = color.from_gradient(close, low, high, color.yellow, color.lime)
color2 = color.from_gradient(ta.rsi(close, 7), 0, 100, color.rgb(255, 0, 0), color.rgb(0, 255, 0, 50))
plot(close, color=color1)
plot(ta.rsi(close,7), color=color2)
color.g(color) → const float
color.g(color) → input float
color.g(color) → series float
//@version=5
indicator("color.g", overlay=true)
plot(color.g(color.green))
color.new(color, transp) → const color
color.new(color, transp) → input color
color.new(color, transp) → series color
//@version=5
indicator("color.new", overlay=true)
plot(close, color=color.new(color.red, 50))
color.r(color) → const float
color.r(color) → input float
color.r(color) → series float
//@version=5
indicator("color.r", overlay=true)
plot(color.r(color.red))
color.rgb(red, green, blue, transp) → const color
color.rgb(red, green, blue, transp) → input color
color.rgb(red, green, blue, transp) → series color
//@version=5
indicator("color.rgb", overlay=true)
plot(close, color=color.rgb(255, 0, 0, 50))
color.t(color) → const float
color.t(color) → input float
color.t(color) → series float
//@version=5
indicator("color.t", overlay=true)
plot(color.t(color.new(color.red, 50)))
dayofmonth(time) → series int
dayofmonth(time, timezone) → series int
dayofweek(time) → series int
dayofweek(time, timezone) → series int
fill(hline1, hline2, color, title, editable, fillgaps, display) → void
fill(plot1, plot2, color, title, editable, show_last, fillgaps, display) → void
fill(plot1, plot2, top_value, bottom_value, top_color, bottom_color, title, display, fillgaps, editable) → void
//@version=5
indicator("Fill between hlines", overlay = false)
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color = color.new(color.blue, 90))
//@version=5
indicator("Fill between plots", overlay = true)
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color = color.new(color.green, 90))
//@version=5
indicator("Gradient Fill between hlines", overlay = false)
topVal = input.int(100)
botVal = input.int(0)
topcol = input.color(color.red)
botcol = input.color(color.blue)
topline = hline(100, color = topcol, linestyle = hline.style_solid)
botline = hline(0, color = botcol, linestyle = hline.style_solid)
fill(topline, botline, topVal, botVal, topcol, botcol)
fixnan(source) → series color
fixnan(source) → series int
fixnan(source) → series float
fixnan(source) → series bool
float(x) → const float
float(x) → input float
float(x) → simple float
float(x) → series float
hline(price, title, color, linestyle, linewidth, editable, display) → hline
//@version=5
indicator("input.hline", overlay=true)
hline(3.14, title='pi', color=color.blue, linestyle=hline.style_dotted, linewidth=2)
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=color.new(color.green, 90))
hour(time) → series int
hour(time, timezone) → series int
indicator(title, shorttitle, overlay, format, precision, scale, max_bars_back, timeframe, timeframe_gaps, explicit_plot_zorder, max_lines_count, max_labels_count, max_boxes_count, max_polylines_count) → void
//@version=5
indicator("My script", shorttitle="script")
plot(close)
input(defval, title, tooltip, inline, group, display) → input color
input(defval, title, tooltip, inline, group, display) → input string
input(defval, title, tooltip, inline, group, display) → input int
input(defval, title, tooltip, inline, group, display) → input float
input(defval, title, inline, group, tooltip, display) → series float
input(defval, title, tooltip, inline, group, display) → input bool
//@version=5
indicator("input", overlay=true)
i_switch = input(true, "On/Off")
plot(i_switch ? open : na)
i_len = input(7, "Length")
i_src = input(close, "source")
plot(ta.sma(i_src, i_len))
i_border = input(142.50, "price border")
hline(i_border)
bgcolor(close > i_border ? color.green : color.red)
i_col = input(color.red, "plot color")
plot(close, color=i_col)
i_text = input("Hello!", "Message")
l = label.new(bar_index, high, text=i_text)
label.delete(l[1])
input.bool(defval, title, tooltip, inline, group, confirm, display) → input bool
//@version=5
indicator("input.bool", overlay=true)
i_switch = input.bool(true, "On/Off")
plot(i_switch ? open : na)
input.color(defval, title, tooltip, inline, group, confirm, display) → input color
//@version=5
indicator("input.color", overlay=true)
i_col = input.color(color.red, "plot color")
plot(close, color=i_col)
input.float(defval, title, options, tooltip, inline, group, confirm, display) → input float
input.float(defval, title, minval, maxval, step, tooltip, inline, group, confirm, display) → input float
//@version=5
indicator("input.float", overlay=true)
i_angle1 = input.float(0.5, "sin angle", minval=-3.14, maxval=3.14, step=0.02)
plot(math.sin(i_angle1) > 0 ? close : open, "sin", color=color.green)
i_angle2 = input.float(0, "Cos angle", options=[-3.14, -1.57, 0, 1.57, 3.14])
plot(math.cos(i_angle2) > 0 ? close : open, "cos", color=color.red)
input.int(defval, title, options, tooltip, inline, group, confirm, display) → input int
input.int(defval, title, minval, maxval, step, tooltip, inline, group, confirm, display) → input int
//@version=5
indicator("input.int", overlay=true)
i_len1 = input.int(10, "Length 1", minval=5, maxval=21, step=1)
plot(ta.sma(close, i_len1))
i_len2 = input.int(10, "Length 2", options=[5, 10, 21])
plot(ta.sma(close, i_len2))
input.price(defval, title, tooltip, inline, group, confirm, display) → input float
//@version=5
indicator("input.price", overlay=true)
price1 = input.price(title="Date", defval=42)
plot(price1)
price2 = input.price(54, title="Date")
plot(price2)
input.session(defval, title, options, tooltip, inline, group, confirm, display) → input string
//@version=5
indicator("input.session", overlay=true)
i_sess = input.session("1300-1700", "session", options=["0930-1600", "1300-1700", "1700-2100"])
t = time(timeframe.period, i_sess)
bgcolor(time == t ? color.green : na)
input.source(defval, title, tooltip, inline, group, display) → series float
//@version=5
indicator("input.source", overlay=true)
i_src = input.source(close, "source")
plot(i_src)
input.string(defval, title, options, tooltip, inline, group, confirm, display) → input string
//@version=5
indicator("input.string", overlay=true)
i_text = input.string("Hello!", "Message")
l = label.new(bar_index, high, i_text)
label.delete(l[1])
input.symbol(defval, title, tooltip, inline, group, confirm, display) → input string
//@version=5
indicator("input.symbol", overlay=true)
i_sym = input.symbol("delL", "symbol")
s = request.security(i_sym, 'D', close)
plot(s)
input.text_area(defval, title, tooltip, group, confirm, display) → input string
//@version=5
indicator("input.text_area")
i_text = input.text_area(defval = "Hello \nWorld!", title = "Message")
plot(close)
input.time(defval, title, tooltip, inline, group, confirm, display) → input int
//@version=5
indicator("input.time", overlay=true)
i_date = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date")
l = label.new(i_date, high, "Date", xloc=xloc.bar_time)
label.delete(l[1])
input.timeframe(defval, title, options, tooltip, inline, group, confirm, display) → input string
//@version=5
indicator("input.timeframe", overlay=true)
i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M'])
s = request.security("aapL", i_res, close)
plot(s)
int(x) → const int
int(x) → input int
int(x) → simple int
int(x) → series int
label.copy(id) → series label
//@version=5
indicator('Last 100 bars highest/lowest', overlay = true)
LOOKbaCK = 100
highest = ta.highest(LOOKbaCK)
highestbars = ta.highestbars(LOOKbaCK)
lowest = ta.lowest(LOOKbaCK)
lowestbars = ta.lowestbars(LOOKbaCK)
if barstate.islastconfirmedhistory
var labelHigh = label.new(bar_index + highestbars, highest, str.tostring(highest), color = color.green)
var labelLow = label.copy(labelHigh)
label.set_xy(labelLow, bar_index + lowestbars, lowest)
label.set_text(labelLow, str.tostring(lowest))
label.set_color(labelLow, color.red)
label.set_style(labelLow, label.style_label_up)
label.delete(id) → void
label.get_text(id) → series string
//@version=5
indicator("label.get_text")
my_label = label.new(time, open, text="Open bar text", xloc=xloc.bar_time)
a = label.get_text(my_label)
label.new(time, close, text = a + " new", xloc=xloc.bar_time)
label.get_x(id) → series int
//@version=5
indicator("label.get_x")
my_label = label.new(time, open, text="Open bar text", xloc=xloc.bar_time)
a = label.get_x(my_label)
plot(time - label.get_x(my_label)) //draws zero plot
label.get_y(id) → series float
label.new(point, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) → series label
label.new(x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family) → series label
//@version=5
indicator("label.new")
var label1 = label.new(bar_index, low, text="Hello, world!", style=label.style_circle)
label.set_x(label1, 0)
label.set_xloc(label1, time, xloc.bar_time)
label.set_color(label1, color.red)
label.set_size(label1, size.large)
label.set_color(id, color) → void
label.set_point(id, point) → void
label.set_size(id, size) → void
label.set_style(id, style) → void
label.set_text(id, text) → void
label.set_text_font_family(id, text_font_family) → void
//@version=5
indicator("Example of setting the label font")
if barstate.islastconfirmedhistory
l = label.new(bar_index, 0, "monospace", yloc=yloc.abovebar)
label.set_text_font_family(l, font.family_monospace)
label.set_textalign(id, textalign) → void
label.set_textcolor(id, textcolor) → void
label.set_tooltip(id, tooltip) → void
label.set_x(id, x) → void
label.set_xloc(id, x, xloc) → void
label.set_xy(id, x, y) → void
label.set_y(id, y) → void
label.set_yloc(id, yloc) → void
library(title, overlay) → void
//@version=5
// @description Math library
library("num_methods", overlay = true)
// Calculate "sinh()" from the float parameter `x`
export sinh(float x) =>
(math.exp(x) - math.exp(-x)) / 2.0
plot(sinh(0))
line.copy(id) → series line
//@version=5
indicator('Last 100 bars price range', overlay = true)
LOOKbaCK = 100
highest = ta.highest(LOOKbaCK)
lowest = ta.lowest(LOOKbaCK)
if barstate.islastconfirmedhistory
var lineTop = line.new(bar_index[LOOKbaCK], highest, bar_index, highest, color = color.green)
var linebottom = line.copy(lineTop)
line.set_y1(linebottom, lowest)
line.set_y2(linebottom, lowest)
line.set_color(linebottom, color.red)
line.delete(id) → void
line.get_price(id, x) → series float
//@version=5
indicator("Getprice", overlay=true)
var line l = na
if bar_index == 10
l := line.new(0, high[5], bar_index, high)
plot(line.get_price(l, bar_index), color=color.green)
line.get_x1(id) → series int
//@version=5
indicator("line.get_x1")
my_line = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
a = line.get_x1(my_line)
plot(time - line.get_x1(my_line)) //draws zero plot
line.get_x2(id) → series int
line.get_y1(id) → series float
line.get_y2(id) → series float
line.new(first_point, second_point, xloc, extend, color, style, width) → series line
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series line
//@version=5
indicator("line.new")
var line1 = line.new(0, low, bar_index, high, extend=extend.right)
var line2 = line.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, style=line.style_dashed)
line.set_x2(line1, 0)
line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
line.set_color(line2, color.green)
line.set_width(line2, 5)
line.set_color(id, color) → void
line.set_extend(id, extend) → void
line.set_first_point(id, point) → void
line.set_second_point(id, point) → void
line.set_style(id, style) → void
line.set_width(id, width) → void
line.set_x1(id, x) → void
line.set_x2(id, x) → void
line.set_xloc(id, x1, x2, xloc) → void
line.set_xy1(id, x, y) → void
line.set_xy2(id, x, y) → void
line.set_y1(id, y) → void
line.set_y2(id, y) → void
linefill.delete(id) → void
linefill.get_line1(id) → series line
linefill.get_line2(id) → series line
linefill.new(line1, line2, color) → series linefill
linefill.set_color(id, color) → void
log.error(message) → void
log.error(formatstring, arg0, arg1, ...) → void
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders_on_close = true)
bracketticksizeinput = input.int(1000, "stoploss/Take-profit distance (in ticks)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
log.info("Exit orders have been placed: Take-profit at {0}, stop-loss at {1}", close)
strategy.exit("Exit", "My Long Entry id", profit = bracketticksizeinput, loss = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc and not last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
log.info(message) → void
log.info(formatstring, arg0, arg1, ...) → void
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders_on_close = true)
bracketticksizeinput = input.int(1000, "stoploss/Take-profit distance (in ticks)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
log.info("Exit orders have been placed: Take-profit at {0}, stop-loss at {1}", close)
strategy.exit("Exit", "My Long Entry id", profit = bracketticksizeinput, loss = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc and not last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
log.warning(message) → void
log.warning(formatstring, arg0, arg1, ...) → void
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100, process_orders_on_close = true)
bracketticksizeinput = input.int(1000, "stoploss/Take-profit distance (in ticks)")
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
limitLevel = close * 1.01
log.info("Long limit order has been placed at {0}", limitLevel)
strategy.order("My Long Entry id", strategy.long, limit = limitLevel)
log.info("Exit orders have been placed: Take-profit at {0}, stop-loss at {1}", close)
strategy.exit("Exit", "My Long Entry id", profit = bracketticksizeinput, loss = bracketticksizeinput)
if strategy.opentrades > 10
log.warning("{0} positions opened in the same direction in a row. try adjusting `bracketticksizeinput`", strategy.opentrades)
last10perc = strategy.initial_capital / 10 > strategy.equity
if (last10perc and not last10perc[1])
log.error("the strategy has lost 90% of the initial capital!")
map.clear(id) → void
//@version=5
indicator("map.clear example")
oddmap = map.new<int, bool>()
oddmap.put(1, true)
oddmap.put(2, false)
oddmap.put(3, true)
map.clear(oddmap)
plot(oddmap.size())
map.contains(id, key) → series bool
//@version=5
indicator("map.includes example")
a = map.new<string, float>()
a.put("open", open)
p = close
if map.contains(a, "open")
p := a.get("open")
plot(p)
map.copy(id) → map<keyType, valueType>
//@version=5
indicator("map.copy example")
a = map.new<string, int>()
a.put("example", 1)
b = map.copy(a)
a := map.new<string, int>()
a.put("example", 2)
plot(a.get("example"))
plot(b.get("example"))
map.get(id, key) → <value_type>
//@version=5
indicator("map.get example")
a = map.new<int, int>()
size = 10
for i = 0 to size
a.put(i, size-i)
plot(map.get(a, 1))
map.keys(id) → type[]
//@version=5
indicator("map.keys example")
a = map.new<string, float>()
a.put("open", open)
a.put("high", high)
a.put("low", low)
a.put("close", close)
keys = map.keys(a)
ohlc = 0.0
for key in keys
ohlc += a.get(key)
plot(ohlc/4)
map.new<keyType, valueType>() → map<keyType, valueType>
//@version=5
indicator("map.new<string, int> example")
a = map.new<string, int>()
a.put("example", 1)
label.new(bar_index, close, str.tostring(a.get("example")))
map.put(id, key, value) → <value_type>
//@version=5
indicator("map.put example")
a = map.new<string, float>()
map.put(a, "first", 10)
map.put(a, "second", 15)
prevFirst = map.put(a, "first", 20)
currFirst = a.get("first")
plot(prevFirst)
plot(currFirst)
map.put_all(id, id2) → void
//@version=5
indicator("map.put_all example")
a = map.new<string, float>()
b = map.new<string, float>()
a.put("first", 10)
a.put("second", 15)
b.put("third", 20)
map.put_all(a, b)
plot(a.get("third"))
map.remove(id, key) → <value_type>
//@version=5
indicator("map.remove example")
a = map.new<string, color>()
a.put("firstcolor", color.green)
oldcolorValue = map.remove(a, "firstcolor")
plot(close, color = oldcolorValue)
map.size(id) → series int
//@version=5
indicator("map.size example")
a = map.new<int, int>()
size = 10
for i = 0 to size
a.put(i, size-i)
plot(map.size(a))
map.values(id) → type[]
//@version=5
indicator("map.values example")
a = map.new<string, float>()
a.put("open", open)
a.put("high", high)
a.put("low", low)
a.put("close", close)
values = map.values(a)
ohlc = 0.0
for value in values
ohlc += value
plot(ohlc/4)
math.abs(number) → const int
math.abs(number) → input int
math.abs(number) → const float
math.abs(number) → simple int
math.abs(number) → input float
math.abs(number) → series int
math.abs(number) → simple float
math.abs(number) → series float
math.acos(angle) → const float
math.acos(angle) → input float
math.acos(angle) → simple float
math.acos(angle) → series float
math.asin(angle) → const float
math.asin(angle) → input float
math.asin(angle) → simple float
math.asin(angle) → series float
math.atan(angle) → const float
math.atan(angle) → input float
math.atan(angle) → simple float
math.atan(angle) → series float
math.avg(number0, number1, ...) → simple float
math.avg(number0, number1, ...) → series float
math.ceil(number) → const int
math.ceil(number) → input int
math.ceil(number) → simple int
math.ceil(number) → series int
math.cos(angle) → const float
math.cos(angle) → input float
math.cos(angle) → simple float
math.cos(angle) → series float
math.exp(number) → const float
math.exp(number) → input float
math.exp(number) → simple float
math.exp(number) → series float
math.floor(number) → const int
math.floor(number) → input int
math.floor(number) → simple int
math.floor(number) → series int
math.log(number) → const float
math.log(number) → input float
math.log(number) → simple float
math.log(number) → series float
math.log10(number) → const float
math.log10(number) → input float
math.log10(number) → simple float
math.log10(number) → series float
math.max(number0, number1, ...) → input int
math.max(number0, number1, ...) → simple int
math.max(number0, number1, ...) → input float
math.max(number0, number1, ...) → series int
math.max(number0, number1, ...) → simple float
math.max(number0, number1, ...) → series float
//@version=5
indicator("math.max", overlay=true)
plot(math.max(close, open))
plot(math.max(close, math.max(open, 42)))
math.min(number0, number1, ...) → input int
math.min(number0, number1, ...) → simple int
math.min(number0, number1, ...) → input float
math.min(number0, number1, ...) → series int
math.min(number0, number1, ...) → simple float
math.min(number0, number1, ...) → series float
//@version=5
indicator("math.min", overlay=true)
plot(math.min(close, open))
plot(math.min(close, math.min(open, 42)))
math.pow(base, exponent) → const float
math.pow(base, exponent) → input float
math.pow(base, exponent) → simple float
math.pow(base, exponent) → series float
//@version=5
indicator("math.pow", overlay=true)
plot(math.pow(close, 2))
math.random(min, max, seed) → series float
math.round(number) → const int
math.round(number) → input int
math.round(number) → simple int
math.round(number) → series int
math.round(number, precision) → const float
math.round(number, precision) → input float
math.round(number, precision) → simple float
math.round(number, precision) → series float
math.round_to_mintick(number) → simple float
math.round_to_mintick(number) → series float
math.sign(number) → const float
math.sign(number) → input float
math.sign(number) → simple float
math.sign(number) → series float
math.sin(angle) → const float
math.sin(angle) → input float
math.sin(angle) → simple float
math.sin(angle) → series float
math.sqrt(number) → const float
math.sqrt(number) → input float
math.sqrt(number) → simple float
math.sqrt(number) → series float
math.sum(source, length) → series float
math.tan(angle) → const float
math.tan(angle) → input float
math.tan(angle) → simple float
math.tan(angle) → series float
math.todegrees(radians) → series float
math.toradians(degrees) → series float
matrix.add_col(id, column) → void
matrix.add_col(id, column, array_id) → void
//@version=5
indicator("`matrix.add_col()` Example 1")
// Create a 2x3 "int" matrix containing values `0`.
m = matrix.new<int>(2, 3, 0)
// add a column with `na` values to the matrix.
matrix.add_col(m)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
//@version=5
indicator("`matrix.add_col()` Example 2")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
// Create an array with values `1` and `3`.
var a = array.from(1, 3)
// add the `a` array as the first column of the empty matrix.
matrix.add_col(m, 0, a)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
matrix.add_row(id, row) → void
matrix.add_row(id, row, array_id) → void
//@version=5
indicator("`matrix.add_row()` Example 1")
// Create a 2x3 "int" matrix containing values `0`.
m = matrix.new<int>(2, 3, 0)
// add a row with `na` values to the matrix.
matrix.add_row(m)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
//@version=5
indicator("`matrix.add_row()` Example 2")
if barstate.islastconfirmedhistory
// Create an empty matrix object.
var m = matrix.new<int>()
// Create an array with values `1` and `2`.
var a = array.from(1, 2)
// add the `a` array as the first row of the empty matrix.
matrix.add_row(m, 0, a)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m))
matrix.avg(id) → series float
matrix.avg(id) → series int
//@version=5
indicator("`matrix.avg()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the average value of the matrix.
var x = matrix.avg(m)
plot(x, 'Matrix average value')
matrix.col(id, column) → type[]
//@version=5
indicator("`matrix.col()` Example", "", true)
// Create a 2x3 "float" matrix from `hlc3` values.
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first column of matrix `m`.
a = matrix.col(m, 0)
// plot the first value from the array `a`.
plot(array.get(a, 0))
matrix.columns(id) → series int
//@version=5
indicator("`matrix.columns()` Example")
// Create a 2x6 matrix with values `0`.
var m = matrix.new<int>(2, 6, 0)
// Get the quantity of columns in matrix `m`.
var x = matrix.columns(m)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, "columns: " + str.tostring(x) + "\n" + str.tostring(m))
matrix.concat(id1, id2) → matrix<type>
//@version=5
indicator("`matrix.concat()` Example")
// Create a 2x4 "int" matrix containing values `0`.
m1 = matrix.new<int>(2, 4, 0)
// Create a 2x4 "int" matrix containing values `1`.
m2 = matrix.new<int>(2, 4, 1)
// append matrix `m2` to `m1`.
matrix.concat(m1, m2)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
matrix.copy(id) → matrix<type>
//@version=5
indicator("`matrix.copy()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 "float" matrix with `1` values.
var m1 = matrix.new<float>(2, 3, 1)
// Copy the matrix to a new one.
// Note that unlike what `matrix.copy()` does,
// the simple assignment operation `m2 = m1`
// would NOT create a new copy of the `m1` matrix.
// it would merely create a copy of its iD referencing the same matrix.
var m2 = matrix.copy(m1)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Matrix Copy:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.det(id) → series float
matrix.det(id) → series int
//@version=5
indicator("`matrix.det` Example")
// Create a 2x2 matrix.
var m = matrix.new<float>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 3)
matrix.set(m, 0, 1, 7)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, -4)
// Get the determinant of the matrix.
var x = matrix.det(m)
plot(x, 'Matrix determinant')
matrix.diff(id1, id2) → matrix<int>
matrix.diff(id1, id2) → matrix<float>
//@version=5
indicator("`matrix.diff()` Example 1")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `5`.
var m1 = matrix.new<float>(2, 3, 5)
// Create a 2x3 matrix containing values `4`.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between matrices `m1` and `m2`.
var m3 = matrix.diff(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "Difference between two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
//@version=5
indicator("`matrix.diff()` Example 2")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix with values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the difference between the `m1` matrix and the "int" value `1`.
var m2 = matrix.diff(m1, 1)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "Difference between a matrix and a scalar:")
table.cell(t, 0, 1, str.tostring(m2))
matrix.eigenvalues(id) → float[]
matrix.eigenvalues(id) → int[]
//@version=5
indicator("`matrix.eigenvalues()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 2)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
// Get the eigenvalues of the matrix.
tr = matrix.eigenvalues(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "array of Eigenvalues:")
table.cell(t, 1, 1, str.tostring(tr))
matrix.eigenvectors(id) → matrix<float>
matrix.eigenvectors(id) → matrix<int>
//@version=5
indicator("`matrix.eigenvectors()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix
var m1 = matrix.new<int>(2, 2, 1)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 2)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 6)
matrix.set(m1, 1, 1, 8)
// Get the eigenvectors of the matrix.
m2 = matrix.eigenvectors(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Matrix Eigenvectors:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.elements_count(id) → series int
matrix.fill(id, value, from_row, to_row, from_column, to_column) → void
//@version=5
indicator("`matrix.fill()` Example")
// Create a 4x5 "int" matrix containing values `0`.
m = matrix.new<float>(4, 5, 0)
// Fill the intersection of rows 1 to 2 and columns 2 to 3 of the matrix with `hl2` values.
matrix.fill(m, hl2, 0, 2, 1, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
matrix.get(id, row, column) → <matrix_type>
//@version=5
indicator("`matrix.get()` Example", "", true)
// Create a 2x3 "float" matrix from the `hl2` values.
m = matrix.new<float>(2, 3, hl2)
// Return the value of the element at index [0, 0] of matrix `m`.
x = matrix.get(m, 0, 0)
plot(x)
matrix.inv(id) → matrix<float>
matrix.inv(id) → matrix<int>
//@version=5
indicator("`matrix.inv()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// inverse of the matrix.
var m2 = matrix.inv(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "inverse matrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.is_antidiagonal(id) → series bool
matrix.is_antisymmetric(id) → series bool
matrix.is_binary(id) → series bool
matrix.is_diagonal(id) → series bool
matrix.is_identity(id) → series bool
matrix.is_square(id) → series bool
matrix.is_stochastic(id) → series bool
matrix.is_symmetric(id) → series bool
matrix.is_triangular(id) → series bool
matrix.is_zero(id) → series bool
matrix.kron(id1, id2) → matrix<float>
matrix.kron(id1, id2) → matrix<int>
//@version=5
indicator("`matrix.kron()` Example")
// Display using a table.
if barstate.islastconfirmedhistory
// Create two matrices with default values `1` and `2`.
var m1 = matrix.new<float>(2, 2, 1)
var m2 = matrix.new<float>(2, 2, 2)
// Calculate the Kronecker product of the matrices.
var m3 = matrix.kron(m1, m2)
// Display matrix elements.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Matrix 1:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "⊗")
table.cell(t, 2, 0, "Matrix 2:")
table.cell(t, 2, 1, str.tostring(m2))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Kronecker product:")
table.cell(t, 4, 1, str.tostring(m3))
matrix.max(id) → series float
matrix.max(id) → series int
//@version=5
indicator("`matrix.max()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the maximum value in the matrix.
var x = matrix.max(m)
plot(x, 'Matrix maximum value')
matrix.median(id) → series float
matrix.median(id) → series int
//@version=5
indicator("`matrix.median()` Example")
// Create a 2x2 matrix.
m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the median of the matrix.
x = matrix.median(m)
plot(x, 'Median of the matrix')
matrix.min(id) → series float
matrix.min(id) → series int
//@version=5
indicator("`matrix.min()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 1)
matrix.set(m, 0, 1, 2)
matrix.set(m, 1, 0, 3)
matrix.set(m, 1, 1, 4)
// Get the minimum value from the matrix.
var x = matrix.min(m)
plot(x, 'Matrix minimum value')
matrix.mode(id) → series float
matrix.mode(id) → series int
//@version=5
indicator("`matrix.mode()` Example")
// Create a 2x2 matrix.
var m = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m, 0, 0, 0)
matrix.set(m, 0, 1, 0)
matrix.set(m, 1, 0, 1)
matrix.set(m, 1, 1, 1)
// Get the mode of the matrix.
var x = matrix.mode(m)
plot(x, 'Mode of the matrix')
matrix.mult(id1, id2) → matrix<int>
matrix.mult(id1, id2) → matrix<float>
matrix.mult(id1, id2) → int[]
matrix.mult(id1, id2) → float[]
//@version=5
indicator("`matrix.mult()` Example 1")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 6x2 matrix containing values `5`.
var m1 = matrix.new<float>(6, 2, 5)
// Create a 2x3 matrix containing values `4`.
// Note that it must have the same quantity of rows as there are columns in the first matrix.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix from the multiplication of the two matrices.
var m3 = matrix.mult(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "product of two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
//@version=5
indicator("`matrix.mult()` Example 2")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix from the product of the two matrices.
scalar = 5
var m2 = matrix.mult(m1, scalar)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Matrix 1:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "scalar:")
table.cell(t, 2, 1, str.tostring(scalar))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Matrix 2:")
table.cell(t, 4, 1, str.tostring(m2))
//@version=5
indicator("`matrix.mult()` Example 3")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `4`.
var m1 = matrix.new<int>(2, 3, 4)
// Create an array of three elements.
var int[] a = array.from(1, 1, 1)
// Create a new matrix containing the product of the `m1` matrix and the `a` array.
var m3 = matrix.mult(m1, a)
// Display using a table.
var t = table.new(position.top_right, 5, 2, color.green)
table.cell(t, 0, 0, "Matrix 1:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 1, "x")
table.cell(t, 2, 0, "Value:")
table.cell(t, 2, 1, str.tostring(a, " "))
table.cell(t, 3, 1, "=")
table.cell(t, 4, 0, "Matrix 3:")
table.cell(t, 4, 1, str.tostring(m3))
matrix.new<type>(rows, columns, initial_value) → matrix<type>
//@version=5
indicator("`matrix.new<type>()` Example 1")
// Create a 2x3 (2 rows x 3 columns) "int" matrix with values zero.
var m = matrix.new<int>(2, 3, 0)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
//@version=5
indicator("`matrix.new<type>()` Example 2")
// Function to create a matrix whose rows are filled with array values.
matrixFromarray(int rows, int columns, array<float> data) =>
m = matrix.new<float>(rows, columns)
for i = 0 to rows <= 0 ? na : rows - 1
for j = 0 to columns <= 0 ? na : columns - 1
matrix.set(m, i, j, array.get(data, i * columns + j))
m
// Create a 3x3 matrix from an array of values.
var m1 = matrixFromarray(3, 3, array.from(1, 2, 3, 4, 5, 6, 7, 8, 9))
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m1))
//@version=5
indicator("`matrix.new<type>()` Example 3")
// Function to create a matrix from a text string.
// Values in a row must be separated by a space. Each line is one row.
matrixFrominputarea(stringOfValues) =>
var rowsarray = str.split(stringOfValues, "\n")
var rows = array.size(rowsarray)
var cols = array.size(str.split(array.get(rowsarray, 0), " "))
var matrix = matrix.new<float>(rows, cols, na)
row = 0
for rowstring in rowsarray
col = 0
values = str.split(rowstring, " ")
for val in values
matrix.set(matrix, row, col, str.tonumber(val))
col += 1
row += 1
matrix
stringinput = input.text_area("1 2 3\n4 5 6\n7 8 9")
var m = matrixFrominputarea(stringinput)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
//@version=5
indicator("`matrix.new<type>()` Example 4")
// Function to create a matrix with random values (0.0 to 1.0).
matrixRandom(int rows, int columns)=>
result = matrix.new<float>(rows, columns)
for i = 0 to rows - 1
for j = 0 to columns - 1
matrix.set(result, i, j, math.random())
result
// Create a 2x3 matrix with random values.
var m = matrixRandom(2, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
matrix.pinv(id) → matrix<float>
matrix.pinv(id) → matrix<int>
//@version=5
indicator("`matrix.pinv()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// pseudoinverse of the matrix.
var m2 = matrix.pinv(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "pseudoinverse matrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.pow(id, power) → matrix<float>
matrix.pow(id, power) → matrix<int>
//@version=5
indicator("`matrix.pow()` Example")
// Display using a table.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, 2)
// Calculate the power of three of the matrix.
var m2 = matrix.pow(m1, 3)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Matrix³:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.rank(id) → series int
//@version=5
indicator("`matrix.rank()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Get the rank of the matrix.
r = matrix.rank(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Rank of the matrix:")
table.cell(t, 1, 1, str.tostring(r))
matrix.remove_col(id, column) → type[]
//@version=5
indicator("matrix_remove_col", overlay = true)
// Create a 2x2 matrix with ones.
var matrixOrig = matrix.new<int>(2, 2, 1)
// set values to the 'matrixOrig' matrix.
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
// Create a copy of the 'matrixOrig' matrix.
matrixCopy = matrix.copy(matrixOrig)
// Remove the first column from the `matrixCopy` matrix.
arr = matrix.remove_col(matrixCopy, 0)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 3, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 0, "Removed elements:")
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 0, "Result Matrix:")
table.cell(t, 2, 1, str.tostring(matrixCopy))
matrix.remove_row(id, row) → type[]
//@version=5
indicator("matrix_remove_row", overlay = true)
// Create a 2x2 "int" matrix containing values `1`.
var matrixOrig = matrix.new<int>(2, 2, 1)
// set values to the 'matrixOrig' matrix.
matrix.set(matrixOrig, 0, 1, 2)
matrix.set(matrixOrig, 1, 0, 3)
matrix.set(matrixOrig, 1, 1, 4)
// Create a copy of the 'matrixOrig' matrix.
matrixCopy = matrix.copy(matrixOrig)
// Remove the first row from the matrix `matrixCopy`.
arr = matrix.remove_row(matrixCopy, 0)
// Display matrix elements.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 3, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(matrixOrig))
table.cell(t, 1, 0, "Removed elements:")
table.cell(t, 1, 1, str.tostring(arr))
table.cell(t, 2, 0, "Result Matrix:")
table.cell(t, 2, 1, str.tostring(matrixCopy))
matrix.reshape(id, rows, columns) → void
//@version=5
indicator("`matrix.reshape()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix.
var m1 = matrix.new<float>(2, 3)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// Reshape the copy to a 3x2.
matrix.reshape(m2, 3, 2)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Reshaped matrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.reverse(id) → void
//@version=5
indicator("`matrix.reverse()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Copy the matrix to a new one.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Copy matrix elements to a new matrix.
var m2 = matrix.copy(m1)
// Reverse the `m2` copy of the original matrix.
matrix.reverse(m2)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "Reversed matrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.row(id, row) → type[]
//@version=5
indicator("`matrix.row()` Example", "", true)
// Create a 2x3 "float" matrix from `hlc3` values.
m = matrix.new<float>(2, 3, hlc3)
// Return an array with the values of the first row of the matrix.
a = matrix.row(m, 0)
// plot the first value from the array `a`.
plot(array.get(a, 0))
matrix.rows(id) → series int
//@version=5
indicator("`matrix.rows()` Example")
// Create a 2x6 matrix with values `0`.
var m = matrix.new<int>(2, 6, 0)
// Get the quantity of rows in the matrix.
var x = matrix.rows(m)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, "Rows: " + str.tostring(x) + "\n" + str.tostring(m))
matrix.set(id, row, column, value) → void
//@version=5
indicator("`matrix.set()` Example")
// Create a 2x3 "int" matrix containing values `4`.
m = matrix.new<int>(2, 3, 4)
// Replace the value of element at row 1 and column 2 with value `3`.
matrix.set(m, 0, 1, 3)
// Display using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m))
matrix.sort(id, column, order) → void
//@version=5
indicator("`matrix.sort()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<float>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 3)
matrix.set(m1, 0, 1, 4)
matrix.set(m1, 1, 0, 1)
matrix.set(m1, 1, 1, 2)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// sort the rows of `m2` using the default arguments (first column and ascending order).
matrix.sort(m2)
// Display using a table.
if barstate.islastconfirmedhistory
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "sorted matrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.submatrix(id, from_row, to_row, from_column, to_column) → matrix<type>
//@version=5
indicator("`matrix.submatrix()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix matrix with values `0`.
var m1 = matrix.new<int>(2, 3, 0)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 0, 2, 3)
matrix.set(m1, 1, 0, 4)
matrix.set(m1, 1, 1, 5)
matrix.set(m1, 1, 2, 6)
// Create a 2x2 submatrix of the `m1` matrix.
var m2 = matrix.submatrix(m1, 0, 2, 1, 3)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original Matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "submatrix:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.sum(id1, id2) → matrix<int>
matrix.sum(id1, id2) → matrix<float>
//@version=5
indicator("`matrix.sum()` Example 1")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix containing values `5`.
var m1 = matrix.new<float>(2, 3, 5)
// Create a 2x3 matrix containing values `4`.
var m2 = matrix.new<float>(2, 3, 4)
// Create a new matrix that sums matrices `m1` and `m2`.
var m3 = matrix.sum(m1, m2)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "sum of two matrices:")
table.cell(t, 0, 1, str.tostring(m3))
//@version=5
indicator("`matrix.sum()` Example 2")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x3 matrix with values `4`.
var m1 = matrix.new<float>(2, 3, 4)
// Create a new matrix containing the sum of the `m1` matrix with the "int" value `1`.
var m2 = matrix.sum(m1, 1)
// Display using a table.
var t = table.new(position.top_right, 1, 2, color.green)
table.cell(t, 0, 0, "sum of a matrix and a scalar:")
table.cell(t, 0, 1, str.tostring(m2))
matrix.swap_columns(id, column1, column2) → void
//@version=5
indicator("`matrix.swap_columns()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix with ‘na’ values.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// swap the first and second columns of the matrix copy.
matrix.swap_columns(m2, 0, 1)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "swapped columns in copy:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.swap_rows(id, row1, row2) → void
//@version=5
indicator("`matrix.swap_rows()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 3x2 matrix with ‘na’ values.
var m1 = matrix.new<int>(3, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
matrix.set(m1, 2, 0, 5)
matrix.set(m1, 2, 1, 6)
// Copy the matrix to a new one.
var m2 = matrix.copy(m1)
// swap the first and second rows of the matrix copy.
matrix.swap_rows(m2, 0, 1)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "swapped rows in copy:")
table.cell(t, 1, 1, str.tostring(m2))
matrix.trace(id) → series float
matrix.trace(id) → series int
//@version=5
indicator("`matrix.trace()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<int>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Get the trace of the matrix.
tr = matrix.trace(m1)
// Display matrix elements.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Matrix elements:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "trace of the matrix:")
table.cell(t, 1, 1, str.tostring(tr))
matrix.transpose(id) → matrix<type>
//@version=5
indicator("`matrix.transpose()` Example")
// For efficiency, execute this code only once.
if barstate.islastconfirmedhistory
// Create a 2x2 matrix.
var m1 = matrix.new<float>(2, 2, na)
// Fill the matrix with values.
matrix.set(m1, 0, 0, 1)
matrix.set(m1, 0, 1, 2)
matrix.set(m1, 1, 0, 3)
matrix.set(m1, 1, 1, 4)
// Create a transpose of the matrix.
var m2 = matrix.transpose(m1)
// Display using a table.
var t = table.new(position.top_right, 2, 2, color.green)
table.cell(t, 0, 0, "Original matrix:")
table.cell(t, 0, 1, str.tostring(m1))
table.cell(t, 1, 0, "transposed matrix:")
table.cell(t, 1, 1, str.tostring(m2))
max_bars_back(var, num) → void
//@version=5
indicator("max_bars_back")
close_() => close
depth() => 400
d = depth()
v = close_()
max_bars_back(v, 500)
out = if bar_index > 0
v[d]
else
v
plot(out)
minute(time) → series int
minute(time, timezone) → series int
month(time) → series int
month(time, timezone) → series int
na(x) → series bool
na(x) → simple bool
//@version=5
indicator("na")
// use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// aLTERNaTiVE
// `nz()` also tests `close[1]` for `na`. it returns `close[1]` if it is not `na`, and `close` if it is.
plot(nz(close[1], close))
nz(source) → simple color
nz(source) → simple int
nz(source) → series color
nz(source) → series int
nz(source) → simple float
nz(source) → series float
nz(source, replacement) → simple color
nz(source, replacement) → simple int
nz(source, replacement) → series color
nz(source, replacement) → series int
nz(source, replacement) → simple float
nz(source, replacement) → series float
nz(source) → simple bool
nz(source) → series bool
nz(source, replacement) → simple bool
nz(source, replacement) → series bool
//@version=5
indicator("nz", overlay=true)
plot(nz(ta.sma(close, 100)))
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display) → plot
//@version=5
indicator("plot")
plot(high+low, title='title', color=color.new(#00ffaa, 70), linewidth=2, style=plot.style_area, offset=15, trackprice=true)
// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=color.new(color.green, 90))
plotarrow(series, title, colorup, colordown, offset, minheight, maxheight, editable, show_last, display) → void
//@version=5
indicator("plotarrow example", overlay=true)
codiff = close - open
plotarrow(codiff, colorup=color.new(color.teal,40), colordown=color.new(color.orange, 40))
plotbar(open, high, low, close, title, color, editable, show_last, display) → void
//@version=5
indicator("plotbar example", overlay=true)
plotbar(open, high, low, close, title='title', color = open < close ? color.green : color.red)
plotcandle(open, high, low, close, title, color, wickcolor, editable, show_last, bordercolor, display) → void
//@version=5
indicator("plotcandle example", overlay=true)
plotcandle(open, high, low, close, title='title', color = open < close ? color.green : color.red, wickcolor=color.black)
plotchar(series, title, char, location, color, offset, text, textcolor, editable, size, show_last, display) → void
//@version=5
indicator("plotchar example", overlay=true)
data = close >= open
plotchar(data, char='❄')
plotshape(series, title, style, location, color, offset, text, textcolor, editable, size, show_last, display) → void
//@version=5
indicator("plotshape example 1", overlay=true)
data = close >= open
plotshape(data, style=shape.xcross)
polyline.delete(id) → void
polyline.new(points, curved, closed, xloc, line_color, fill_color, line_style, line_width) → series polyline
//@version=5
indicator("polylines example", overlay = true)
//@variable if `true`, connects all points in the polyline with curved line segments.
bool curvedinput = input.bool(false, "Curve polyline")
//@variable if `true`, connects the first point in the polyline to the last point.
bool closedinput = input.bool(true, "Close polyline")
//@variable the color of the space filled by the polyline.
color fillcolor = input.color(color.new(color.blue, 90), "Fill color")
// time and price inputs for the polyline's points.
p1x = input.time(0, "p1", confirm = true, inline = "p1")
p1y = input.price(0, " ", confirm = true, inline = "p1")
p2x = input.time(0, "p2", confirm = true, inline = "p2")
p2y = input.price(0, " ", confirm = true, inline = "p2")
p3x = input.time(0, "p3", confirm = true, inline = "p3")
p3y = input.price(0, " ", confirm = true, inline = "p3")
p4x = input.time(0, "p4", confirm = true, inline = "p4")
p4y = input.price(0, " ", confirm = true, inline = "p4")
p5x = input.time(0, "p5", confirm = true, inline = "p5")
p5y = input.price(0, " ", confirm = true, inline = "p5")
if barstate.islastconfirmedhistory
//@variable an array of `chart.point` objects for the new polyline.
var points = array.new<chart.point>()
// push new `chart.point` instances into the `points` array.
points.push(chart.point.from_time(p1x, p1y))
points.push(chart.point.from_time(p2x, p2y))
points.push(chart.point.from_time(p3x, p3y))
points.push(chart.point.from_time(p4x, p4y))
points.push(chart.point.from_time(p5x, p5y))
// add labels for each `chart.point` in `points`.
l1p1 = label.new(points.get(0), text = "p1", xloc = xloc.bar_time, color = na)
l1p2 = label.new(points.get(1), text = "p2", xloc = xloc.bar_time, color = na)
l2p1 = label.new(points.get(2), text = "p3", xloc = xloc.bar_time, color = na)
l2p2 = label.new(points.get(3), text = "p4", xloc = xloc.bar_time, color = na)
// Create a new polyline that connects each `chart.point` in the `points` array, starting from the first.
polyline.new(points, curved = curvedinput, closed = closedinput, fill_color = fillcolor, xloc = xloc.bar_time)
request.currency_rate(from, to, ignore_invalid_currency) → series float
//@version=5
indicator("Close in british pounds")
rate = request.currency_rate(syminfo.currency, "Gbp")
plot(close * rate)
request.dividends(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency) → series float
//@version=5
indicator("request.dividends")
s1 = request.dividends("NasDaq:bELFa")
plot(s1)
s2 = request.dividends("NasDaq:bELFa", dividends.net, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on)
plot(s2)
request.earnings(ticker, field, gaps, lookahead, ignore_invalid_symbol, currency) → series float
//@version=5
indicator("request.earnings")
s1 = request.earnings("NasDaq:bELFa")
plot(s1)
s2 = request.earnings("NasDaq:bELFa", earnings.actual, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on)
plot(s2)
request.economic(country_code, field, gaps, ignore_invalid_symbol) → series float
//@version=5
indicator("us GDp")
e = request.economic("us", "GDp")
plot(e)
request.financial(symbol, financial_id, period, gaps, ignore_invalid_symbol, currency) → series float
//@version=5
indicator("request.financial")
f = request.financial("NasDaq:MsFT", "aCCOuNTs_paYabLE", "FY")
plot(f)
request.quandl(ticker, gaps, index, ignore_invalid_symbol) → series float
//@version=5
indicator("request.quandl")
f = request.quandl("CFTC/sb_FO_aLL", barmerge.gaps_off, 0)
plot(f)
request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency) → series <type>
//@version=5
indicator("simple `request.security()` calls")
// Returns 1D close of the current symbol.
dailyClose = request.security(syminfo.tickerid, "1D", close)
plot(dailyClose)
// Returns the close of "aapL" from the same timeframe as currently open on the chart.
aaplClose = request.security("aapL", timeframe.period, close)
plot(aaplClose)
//@version=5
indicator("advanced `request.security()` calls")
// this calculates a 10-period moving average on the active chart.
sma = ta.sma(close, 10)
// this sends the `sma` calculation for execution in the context of the "aapL" symbol at a "240" (4 hours) timeframe.
aaplsma = request.security("aapL", "240", sma)
plot(aaplsma)
// To avoid differences on historical and realtime bars, you can use this technique, which only returns a value from the higher timeframe on the bar after it completes:
indexHighTF = barstate.isrealtime ? 1 : 0
indexCurrtF = barstate.isrealtime ? 0 : 1
nonRepaintingClose = request.security(syminfo.tickerid, "1D", close[indexHighTF])[indexCurrtF]
plot(nonRepaintingClose, "Non-repainting close")
// Returns the 1H close of "aapL", extended session included. the value is dividend-adjusted.
extendedticker = ticker.modify("NasDaq:aapL", session = session.extended, adjustment = adjustment.dividends)
aaplExtadj = request.security(extendedticker, "60", close)
plot(aaplExtadj)
// Returns the result of a user-defined function.
// the `max` variable is mutable, but we can pass it to `request.security()` because it is wrapped in a function.
alltimeHigh(source) =>
var max = source
max := math.max(max, source)
alltimeHigh1D = request.security(syminfo.tickerid, "1D", alltimeHigh(high))
// by using a tuple `expression`, we obtain several values with only one `request.security()` call.
[open1D, high1D, low1D, close1D, ema1D] = request.security(syminfo.tickerid, "1D", [open, high, low, close, ta.ema(close, 10)])
plotcandle(open1D, high1D, low1D, close1D)
plot(ema1D)
// Returns an array containing the OHLC values of the chart's symbol from the 1D timeframe.
ohlcarray = request.security(syminfo.tickerid, "1D", array.from(open, high, low, close))
plotcandle(array.get(ohlcarray, 0), array.get(ohlcarray, 1), array.get(ohlcarray, 2), array.get(ohlcarray, 3))
request.security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol, currency, ignore_invalid_timeframe) → array<type>
//@version=5
indicator("`request.security_lower_tf()` Example", overlay = true)
// if the current chart timeframe is set to 120 minutes, then the `arrayClose` array will contain two 'close' values from the 60 minute timeframe for each bar.
arrClose = request.security_lower_tf(syminfo.tickerid, "60", close)
if bar_index == last_bar_index - 1
label.new(bar_index, high, str.tostring(arrClose))
request.seed(source, symbol, expression, ignore_invalid_symbol) → series <type>
//@version=5
indicator("bTC Development activity")
[devact, devactsMa] = request.seed("seed_crypto_santiment", "bTC_DEV_aCTiViTY", [close, ta.sma(close, 10)])
plot(devact, "bTC Development activity")
plot(devactsMa, "bTC Development activity sMa10", color = color.yellow)
request.splits(ticker, field, gaps, lookahead, ignore_invalid_symbol) → series float
//@version=5
indicator("request.splits")
s1 = request.splits("NasDaq:bELFa", splits.denominator)
plot(s1)
s2 = request.splits("NasDaq:bELFa", splits.denominator, gaps=barmerge.gaps_on, lookahead=barmerge.lookahead_on)
plot(s2)
runtime.error(message) → void
second(time) → series int
second(time, timezone) → series int
str.contains(source, str) → const bool
str.contains(source, str) → simple bool
str.contains(source, str) → series bool
//@version=5
indicator("str.contains")
// if the current chart is a continuous futures chart, e.g “bTC1!”, then the function will return true, false otherwise.
var isFutures = str.contains(syminfo.tickerid, "!")
plot(isFutures ? 1 : 0)
str.endswith(source, str) → const bool
str.endswith(source, str) → simple bool
str.endswith(source, str) → series bool
str.format(formatstring, arg0, arg1, ...) → simple string
str.format(formatstring, arg0, arg1, ...) → series string
//@version=5
indicator("str.format", overlay=true)
// the format specifier inside the curly braces accepts certain modifiers:
// - specify the number of decimals to display:
s1 = str.format("{0,number,#.#}", 1.34) // returns: 1.3
label.new(bar_index, close, text=s1)
// - Round a float value to an integer:
s2 = str.format("{0,number,integer}", 1.34) // returns: 1
label.new(bar_index - 1, close, text=s2)
// - Display a number in currency:
s3 = str.format("{0,number,currency}", 1.34) // returns: $1.34
label.new(bar_index - 2, close, text=s3)
// - Display a number as a percentage:
s4 = str.format("{0,number,percent}", 0.5) // returns: 50%
label.new(bar_index - 3, close, text=s4)
// EXaMpLEs With sEVERaL aRGuMENTs
// returns: Number 1 is not equal to 4
s5 = str.format("Number {0} is not {1} to {2}", 1, "equal", 4)
label.new(bar_index - 4, close, text=s5)
// returns: 1.34 != 1.3
s6 = str.format("{0} != {0, number, #.#}", 1.34)
label.new(bar_index - 5, close, text=s6)
// returns: 1 is equal to 1, but 2 is equal to 2
s7 = str.format("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.52)
label.new(bar_index - 6, close, text=s7)
// returns: the cash turnover amounted to $1,340,000.00
s8 = str.format("the cash turnover amounted to {0, number, currency}", 1340000)
label.new(bar_index - 7, close, text=s8)
// returns: Expected return is 10% - 20%
s9 = str.format("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
label.new(bar_index - 8, close, text=s9)
str.format_time(time, format, timezone) → series string
//@version=5
indicator("str.format_time")
if timeframe.change("1D")
formattedtime = str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone)
label.new(bar_index, high, formattedtime)
str.length(string) → const int
str.length(string) → simple int
str.length(string) → series int
str.lower(source) → const string
str.lower(source) → simple string
str.lower(source) → series string
str.match(source, regex) → simple string
str.match(source, regex) → series string
//@version=5
indicator("str.match")
s = input.string("it's time to sell some NasDaq:aapL!")
// finding first substring that matches regular expression "[\w]+:[\w]+"
var string tickerid = str.match(s, "[\\w]+:[\\w]+")
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = tickerid) // "NasDaq:aapL"
str.pos(source, str) → const int
str.pos(source, str) → simple int
str.pos(source, str) → series int
str.replace(source, target, replacement, occurrence) → const string
str.replace(source, target, replacement, occurrence) → simple string
str.replace(source, target, replacement, occurrence) → series string
//@version=5
indicator("str.replace")
var source = "FTX:bTCusD / FTX:bTCEuR"
// Replace first occurrence of "FTX" with "biNaNCE" replacement string
var newsource = str.replace(source, "FTX", "biNaNCE", 0)
if barstate.islastconfirmedhistory
// Display "biNaNCE:bTCusD / FTX:bTCEuR"
label.new(bar_index, high, text = newsource)
str.replace_all(source, target, replacement) → simple string
str.replace_all(source, target, replacement) → series string
str.split(string, separator) → string[]
str.startswith(source, str) → const bool
str.startswith(source, str) → simple bool
str.startswith(source, str) → series bool
str.substring(source, begin_pos) → const string
str.substring(source, begin_pos) → simple string
str.substring(source, begin_pos) → series string
str.substring(source, begin_pos, end_pos) → const string
str.substring(source, begin_pos, end_pos) → simple string
str.substring(source, begin_pos, end_pos) → series string
//@version=5
indicator("str.substring", overlay = true)
sym= input.symbol("NasDaq:aapL")
pos = str.pos(sym, ":") // Get position of ":" character
tkr= str.substring(sym, pos+1) // "aapL"
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = tkr)
str.tonumber(string) → const float
str.tonumber(string) → input float
str.tonumber(string) → simple float
str.tonumber(string) → series float
str.tostring(value) → simple string
str.tostring(value) → series string
str.tostring(value, format) → simple string
str.tostring(value, format) → series string
str.upper(source) → const string
str.upper(source) → simple string
str.upper(source) → series string
strategy(title, shorttitle, overlay, format, precision, scale, pyramiding, calc_on_order_fills, calc_on_every_tick, max_bars_back, backtest_fill_limits_assumption, default_qty_type, default_qty_value, initial_capital, currency, slippage, commission_type, commission_value, process_orders_on_close, close_entries_rule, margin_long, margin_short, explicit_plot_zorder, max_lines_count, max_labels_count, max_boxes_count, risk_free_rate, use_bar_magnifier, max_polylines_count) → void
//@version=5
strategy("My strategy", overlay = true, margin_long = 100, margin_short = 100)
// Enter long by market if current open is greater than previous high.
if open > high[1]
strategy.entry("Long", strategy.long, 1)
// Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long".
strategy.exit("Exit", "Long", profit = 10, loss = 5)
strategy.cancel(id) → void
//@version=5
strategy(title = "simple order cancellation example")
conditionForbuy = open > high[1]
if conditionForbuy
strategy.entry("long", strategy.long, 1, limit = low) // enter long using limit order at low price of current bar if conditionForbuy is true
if not conditionForbuy
strategy.cancel("long") // cancel the entry order with name "long" if conditionForbuy is false
strategy.cancel_all() → void
//@version=5
strategy(title = "simple all orders cancellation example")
conditionForbuy1 = open > high[1]
if conditionForbuy1
strategy.entry("long entry 1", strategy.long, 1, limit = low) // enter long by limit if conditionForbuy1 is true
conditionForbuy2 = conditionForbuy1 and open[1] > high[2]
if conditionForbuy2
strategy.entry("long entry 2", strategy.long, 1, limit = ta.lowest(low, 2)) // enter long by limit if conditionForbuy2 is true
conditionForstoptrading = open < ta.lowest(low, 2)
if conditionForstoptrading
strategy.cancel_all() // cancel both limit orders if the conditon conditionForstoptrading is true
strategy.close(id, comment, qty, qty_percent, alert_message, immediately, disable_alert) → void
//@version=5
strategy("closeEntry Demo", overlay=false)
if open > close
strategy.entry("buy", strategy.long)
if open < close
strategy.close("buy", qty_percent = 50, comment = "close buy entry for 50%")
plot(strategy.position_size)
strategy.close_all(comment, alert_message) → void
strategy.close_all(comment, alert_message, immediately, disable_alert) → void
//@version=5
strategy("closeall Demo", overlay=false)
if open > close
strategy.entry("buy", strategy.long)
if open < close
strategy.close_all(comment = "close all entries")
plot(strategy.position_size)
strategy.closedtrades.commission(trade_num) → series float
//@version=5
strategy("`strategy.closedtrades.commission` Example", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot total fees for the latest closed trade.
plot(strategy.closedtrades.commission(strategy.closedtrades - 1))
strategy.closedtrades.entry_bar_index(trade_num) → series int
//@version=5
strategy("strategy.closedtrades.entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars in a trade.
avgbarspertrade() =>
sumbarspertrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumbarspertrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumbarspertrade / strategy.closedtrades)
plot(avgbarspertrade())
strategy.closedtrades.entry_comment(trade_num) → series string
//@version=5
strategy("`strategy.closedtrades.entry_comment()` Example", overlay = true)
stopprice = open * 1.01
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
strategy.entry("Long", strategy.long, stop = stopprice, comment = str.tostring(stopprice, "#.####"))
strategy.exit("EXiT", trail_points = 1000, trail_offset = 0)
var testtable = table.new(position.top_right, 1, 3, color.orange, border_width = 1)
if barstate.islastconfirmedhistory or barstate.isrealtime
table.cell(testtable, 0, 0, 'Last closed trade:')
table.cell(testtable, 0, 1, "Order stop price value: " + strategy.closedtrades.entry_comment(strategy.closedtrades - 1))
table.cell(testtable, 0, 2, "actual Entry price: " + str.tostring(strategy.closedtrades.entry_price(strategy.closedtrades - 1)))
strategy.closedtrades.entry_id(trade_num) → series string
//@version=5
strategy("strategy.closedtrades.entry_id Example", overlay = true)
// Enter a short position and close at the previous to last bar.
if bar_index == 1
strategy.entry("short at bar #" + str.tostring(bar_index), strategy.short)
if bar_index == last_bar_index - 2
strategy.close_all()
// Display iD of the last entry position.
if barstate.islastconfirmedhistory
label.new(last_bar_index, high, "Last Entry iD is: " + strategy.closedtrades.entry_id(strategy.closedtrades - 1))
strategy.closedtrades.entry_price(trade_num) → series float
//@version=5
strategy("strategy.closedtrades.entry_price Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Return the entry price for the latest entry.
entryprice = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
plot(entryprice, "Long entry price")
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("strategy.closedtrades.entry_price Example 2")
// strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("short")
// Calculate profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
strategy.closedtrades.entry_time(trade_num) → series int
//@version=5
strategy("strategy.closedtrades.entry_time Example", overlay = true)
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration
avgtradeDuration() =>
sumtradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumtradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumtradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgtradeDuration() / 1000, "#.##") + " seconds")
strategy.closedtrades.exit_bar_index(trade_num) → series int
//@version=5
strategy("strategy.closedtrades.exit_bar_index Example 1")
// strategy calls to place a single short trade. We enter the trade at the first bar and exit the trade at 10 bars before the last chart bar.
if bar_index == 0
strategy.entry("short", strategy.short)
if bar_index == last_bar_index - 10
strategy.close("short")
// Calculate the amount of bars since the last closed trade.
barssinceClosed = strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) : na
plot(barssinceClosed, "bars since last closed trade")
// Calculates the average amount of bars per trade.
//@version=5
strategy("strategy.closedtrades.exit_bar_index Example 2")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Function that calculates the average amount of bars per trade.
avgbarspertrade() =>
sumbarspertrade = 0
for tradeNo = 0 to strategy.closedtrades - 1
// Loop through all closed trades, starting with the oldest.
sumbarspertrade += strategy.closedtrades.exit_bar_index(tradeNo) - strategy.closedtrades.entry_bar_index(tradeNo) + 1
result = nz(sumbarspertrade / strategy.closedtrades)
plot(avgbarspertrade())
strategy.closedtrades.exit_comment(trade_num) → series string
//@version=5
strategy("`strategy.closedtrades.exit_comment()` Example", overlay = true)
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit", stop = open * 0.95, limit = close * 1.05, trail_points = 100, trail_offset = 0, comment_profit = "Tp", comment_loss = "sL", comment_trailing = "traiL")
exitstats() =>
int slCount = 0
int tpCount = 0
int trailCount = 0
if strategy.closedtrades > 0
for i = 0 to strategy.closedtrades - 1
switch strategy.closedtrades.exit_comment(i)
"Tp" => tpCount += 1
"sL" => slCount += 1
"traiL" => trailCount += 1
[slCount, tpCount, trailCount]
var testtable = table.new(position.top_right, 1, 4, color.orange, border_width = 1)
if barstate.islastconfirmedhistory
[slCount, tpCount, trailCount] = exitstats()
table.cell(testtable, 0, 0, "Closed trades (" + str.tostring(strategy.closedtrades) +") stats:")
table.cell(testtable, 0, 1, "stop Loss: " + str.tostring(slCount))
table.cell(testtable, 0, 2, "Take profit: " + str.tostring(tpCount))
table.cell(testtable, 0, 3, "trailing stop: " + str.tostring(trailCount))
strategy.closedtrades.exit_id(trade_num) → series string
//@version=5
strategy("strategy.closedtrades.exit_id Example", overlay = true)
// strategy calls to create single short and long trades
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.entry("short Entry", strategy.short)
// When a new open trade is detected then we create the exit strategy corresponding with the matching entry id
// We detect the correct entry id by determining if a position is long or short based on the position quantity
if ta.change(strategy.opentrades)
possign = strategy.opentrades.size(strategy.opentrades - 1)
strategy.exit(possign > 0 ? "sL Long Exit" : "sL short Exit", strategy.opentrades.entry_id(strategy.opentrades - 1), stop = possign > 0 ? high - ta.tr : low + ta.tr)
// When a new closed trade is detected then we place a label above the bar with the exit info
if ta.change(strategy.closedtrades)
msg = "trade closed by: " + strategy.closedtrades.exit_id(strategy.closedtrades - 1)
label.new(bar_index, high + (3 * ta.tr), msg)
strategy.closedtrades.exit_price(trade_num) → series float
//@version=5
strategy("strategy.closedtrades.exit_price Example 1")
// We are creating a long trade every 5 bars
if bar_index % 5 == 0
strategy.entry("Long", strategy.long)
strategy.close("Long")
// Return the exit price from the latest closed trade.
exitprice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)
plot(exitprice, "Long exit price")
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("strategy.closedtrades.exit_price Example 2")
// strategy calls to create single short and long trades.
if bar_index == last_bar_index - 15
strategy.entry("Long Entry", strategy.long)
else if bar_index == last_bar_index - 10
strategy.close("Long Entry")
strategy.entry("short", strategy.short)
else if bar_index == last_bar_index - 5
strategy.close("short")
// Calculate profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
strategy.closedtrades.exit_time(trade_num) → series int
//@version=5
strategy("strategy.closedtrades.exit_time Example 1")
// Enter long trades on three rising bars; exit on two falling bars.
if ta.rising(close, 3)
strategy.entry("Long", strategy.long)
if ta.falling(close, 2)
strategy.close("Long")
// Calculate the average trade duration.
avgtradeDuration() =>
sumtradeDuration = 0
for i = 0 to strategy.closedtrades - 1
sumtradeDuration += strategy.closedtrades.exit_time(i) - strategy.closedtrades.entry_time(i)
result = nz(sumtradeDuration / strategy.closedtrades)
// Display average duration converted to seconds and formatted using 2 decimal points.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(avgtradeDuration() / 1000, "#.##") + " seconds")
// Reopens a closed trade after X seconds.
//@version=5
strategy("strategy.closedtrades.exit_time Example 2")
// strategy calls to emulate a single long trade at the first bar.
if bar_index == 0
strategy.entry("Long", strategy.long)
reopenpositionafter(timesec) =>
if strategy.closedtrades > 0
if time - strategy.closedtrades.exit_time(strategy.closedtrades - 1) >= timesec * 1000
strategy.entry("Long", strategy.long)
// Reopen last closed position after 120 sec.
reopenpositionafter(120)
if ta.change(strategy.opentrades)
strategy.exit("Long", stop = low * 0.9, profit = high * 2.5)
strategy.closedtrades.max_drawdown(trade_num) → series float
//@version=5
strategy("`strategy.closedtrades.max_drawdown` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade drawdown value from all of the closed trades.
maxtradeDrawDown() =>
maxDrawdown = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
maxDrawdown := math.max(maxDrawdown, strategy.closedtrades.max_drawdown(tradeNo))
result = maxDrawdown
plot(maxtradeDrawDown(), "biggest max drawdown")
strategy.closedtrades.max_runup(trade_num) → series float
//@version=5
strategy("`strategy.closedtrades.max_runup` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade runup value from all of the closed trades.
maxtradeRunup() =>
maxRunup = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
maxRunup := math.max(maxRunup, strategy.closedtrades.max_runup(tradeNo))
result = maxRunup
plot(maxtradeRunup(), "Max trade runup")
strategy.closedtrades.profit(trade_num) → series float
//@version=5
strategy("`strategy.closedtrades.profit` Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate average gross profit by adding the difference between gross profit and commission.
avgGrossprofit() =>
sumGrossprofit = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
sumGrossprofit += strategy.closedtrades.profit(tradeNo) - strategy.closedtrades.commission(tradeNo)
result = nz(sumGrossprofit / strategy.closedtrades)
plot(avgGrossprofit(), "average gross profit")
strategy.closedtrades.size(trade_num) → series float
//@version=5
strategy("`strategy.closedtrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtshares = math.floor(strategy.equity / close)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtshares)
if bar_index % 20 == 0
strategy.close("Long")
// plot the number of contracts traded in the last closed trade.
plot(strategy.closedtrades.size(strategy.closedtrades - 1), "Number of contracts traded")
// Calculates the average profit percentage for all closed trades.
//@version=5
strategy("`strategy.closedtrades.size` Example 2")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for both closed trades.
profitpct = 0.0
for tradeNo = 0 to strategy.closedtrades - 1
entryp = strategy.closedtrades.entry_price(tradeNo)
exitp = strategy.closedtrades.exit_price(tradeNo)
profitpct += (exitp - entryp) / entryp * strategy.closedtrades.size(tradeNo) * 100
// Calculate average profit percent for both closed trades.
avgprofitpct = nz(profitpct / strategy.closedtrades)
plot(avgprofitpct)
strategy.convert_to_account(value) → series float
//@version=5
strategy("`strategy.convert_to_account` Example 1", currency = currency.EuR)
plot(close, "Close price using default currency")
plot(strategy.convert_to_account(close), "Close price converted to strategy currency")
// Calculates the "buy and hold return" using your account's currency.
//@version=5
strategy("`strategy.convert_to_account` Example 2", currency = currency.EuR)
dateinput = input.time(timestamp("20 Jul 2021 00:00 +0300"), "From Date", confirm = true)
buyandHoldReturnpct(fromDate) =>
if time >= fromDate
money = close * syminfo.pointvalue
var initialbal = strategy.convert_to_account(money)
(strategy.convert_to_account(money) - initialbal) / initialbal * 100
plot(buyandHoldReturnpct(dateinput))
strategy.convert_to_symbol(value) → series float
//@version=5
strategy("`strategy.convert_to_symbol` Example", currency = currency.EuR)
// Calculate the max qty we can buy using current chart's currency.
calcContracts(accountMoney) =>
math.floor(strategy.convert_to_symbol(accountMoney) / syminfo.pointvalue / close)
// Return max qty we can buy using 300 euros
qt = calcContracts(300)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars using our custom qty.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = qt)
if bar_index % 20 == 0
strategy.close("Long")
strategy.default_entry_qty(fill_price) → series float
//@version=5
strategy("supertrend strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 15)
//@variable the length of the atr calculation.
atrperiod = input(10, "atr Length")
//@variable the atr multiplier.
factor = input.float(3.0, "Factor", step = 0.01)
//@variable the tick offset of the stop order.
stopOffsetinput = input.int(100, "Tick offset for entry stop")
// Get the direction of the supertrend.
[_, direction] = ta.supertrend(factor, atrperiod)
if ta.change(direction) < 0
//@variable the stop price of the entry order.
stopprice = close + syminfo.mintick * stopOffsetinput
//@variable the expected default fill quantity at the `stopprice`. this value may not reflect actual qty of the filled order, because fill price may be different.
calculatedqty = strategy.default_entry_qty(stopprice)
strategy.entry("My Long Entry id", strategy.long, stop = stopprice)
label.new(bar_index, stopprice, str.format("stop set at {0}\nExpected qty at {0}: {1}", math.round_to_mintick(stopprice), calculatedqty))
if ta.change(direction) > 0
strategy.close_all()
strategy.entry(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void
//@version=5
strategy(title = "simple strategy entry example")
if open > high[1]
strategy.entry("enter long", strategy.long, 1) // enter long by market if current open great then previous high
if open < low[1]
strategy.entry("enter short", strategy.short, 1) // enter short by market if current open less then previous low
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, alert_message, alert_profit, alert_loss, alert_trailing, disable_alert) → void
//@version=5
strategy(title = "simple strategy exit example")
if open > high[1]
strategy.entry("long", strategy.long, 1) // enter long by market if current open great then previous high
strategy.exit("exit", "long", profit = 10, loss = 5) // generate full exit bracket (profit 10 points, loss 5 points per contract) from entry with name "long"
strategy.opentrades.commission(trade_num) → series float
// Calculates the gross profit or loss for the current open position.
//@version=5
strategy("`strategy.opentrades.commission` Example", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate gross profit or loss for open positions only.
tradeOpenGrosspL() =>
sumOpenGrosspL = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenGrosspL += strategy.opentrades.profit(tradeNo) - strategy.opentrades.commission(tradeNo)
result = sumOpenGrosspL
plot(tradeOpenGrosspL())
strategy.opentrades.entry_bar_index(trade_num) → series int
// Wait 10 bars and then close the position.
//@version=5
strategy("`strategy.opentrades.entry_bar_index` Example")
barssinceLastEntry() =>
strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
// Enter a long position if there are no open positions.
if strategy.opentrades == 0
strategy.entry("Long", strategy.long)
// Close the long position after 10 bars.
if barssinceLastEntry() >= 10
strategy.close("Long")
strategy.opentrades.entry_comment(trade_num) → series string
//@version=5
strategy("`strategy.opentrades.entry_comment()` Example", overlay = true)
stopprice = open * 1.01
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
strategy.entry("Long", strategy.long, stop = stopprice, comment = str.tostring(stopprice, "#.####"))
var testtable = table.new(position.top_right, 1, 3, color.orange, border_width = 1)
if barstate.islastconfirmedhistory or barstate.isrealtime
table.cell(testtable, 0, 0, 'Last entry stats')
table.cell(testtable, 0, 1, "Order stop price value: " + strategy.opentrades.entry_comment(strategy.opentrades - 1))
table.cell(testtable, 0, 2, "actual Entry price: " + str.tostring(strategy.opentrades.entry_price(strategy.opentrades - 1)))
strategy.opentrades.entry_id(trade_num) → series string
//@version=5
strategy("`strategy.opentrades.entry_id` Example", overlay = true)
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortcondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
// strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
strategy.entry("Long entry at bar #" + str.tostring(bar_index), strategy.long)
if shortcondition
strategy.entry("short entry at bar #" + str.tostring(bar_index), strategy.short)
// Display iD of the latest open position.
if barstate.islastconfirmedhistory
label.new(bar_index, high + (2 * ta.tr), "Last opened position is \n " + strategy.opentrades.entry_id(strategy.opentrades - 1))
strategy.opentrades.entry_price(trade_num) → series float
//@version=5
strategy("strategy.opentrades.entry_price Example 1", overlay = true)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if ta.crossover(close, ta.sma(close, 14))
strategy.entry("Long", strategy.long)
// Return the entry price for the latest closed trade.
currEntryprice = strategy.opentrades.entry_price(strategy.opentrades - 1)
currExitprice = currEntryprice * 1.05
if high >= currExitprice
strategy.close("Long")
plot(currEntryprice, "Long entry price", style = plot.style_linebr)
plot(currExitprice, "Long exit price", color.green, style = plot.style_linebr)
// Calculates the average price for the open position.
//@version=5
strategy("strategy.opentrades.entry_price Example 2", pyramiding = 2)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculates the average price for the open position.
avgOpenpositionprice() =>
sumOpenpositionprice = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumOpenpositionprice += strategy.opentrades.entry_price(tradeNo) * strategy.opentrades.size(tradeNo) / strategy.position_size
result = nz(sumOpenpositionprice / strategy.opentrades)
plot(avgOpenpositionprice())
strategy.opentrades.entry_time(trade_num) → series int
//@version=5
strategy("strategy.opentrades.entry_time Example")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculates duration in milliseconds since the last position was opened.
timesinceLastEntry()=>
strategy.opentrades > 0 ? (time - strategy.opentrades.entry_time(strategy.opentrades - 1)) : na
plot(timesinceLastEntry() / 1000 * 60 * 60 * 24, "Days since last entry")
strategy.opentrades.max_drawdown(trade_num) → series float
//@version=5
strategy("strategy.opentrades.max_drawdown Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot the max drawdown of the latest open trade.
plot(strategy.opentrades.max_drawdown(strategy.opentrades - 1), "Max drawdown of the latest open trade")
// Calculates the max trade drawdown value for all open trades.
//@version=5
strategy("`strategy.opentrades.max_drawdown` Example 2", pyramiding = 100)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Get the biggest max trade drawdown value from all of the open trades.
maxtradeDrawDown() =>
maxDrawdown = 0.0
for tradeNo = 0 to strategy.opentrades - 1
maxDrawdown := math.max(maxDrawdown, strategy.opentrades.max_drawdown(tradeNo))
result = maxDrawdown
plot(maxtradeDrawDown(), "biggest max drawdown")
strategy.opentrades.max_runup(trade_num) → series float
//@version=5
strategy("strategy.opentrades.max_runup Example 1")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// plot the max runup of the latest open trade.
plot(strategy.opentrades.max_runup(strategy.opentrades - 1), "Max runup of the latest open trade")
// Calculates the max trade runup value for all open trades.
//@version=5
strategy("strategy.opentrades.max_runup Example 2", pyramiding = 100)
// Enter a long position every 30 bars.
if bar_index % 30 == 0
strategy.entry("Long", strategy.long)
// Calculate biggest max trade runup value from all of the open trades.
maxOpentradeRunup() =>
maxRunup = 0.0
for tradeNo = 0 to strategy.opentrades - 1
maxRunup := math.max(maxRunup, strategy.opentrades.max_runup(tradeNo))
result = maxRunup
plot(maxOpentradeRunup(), "biggest max runup of all open trades")
strategy.opentrades.profit(trade_num) → series float
// Returns the profit of the last open trade.
//@version=5
strategy("`strategy.opentrades.profit` Example 1", commission_type = strategy.commission.percent, commission_value = 0.1)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
plot(strategy.opentrades.profit(strategy.opentrades - 1), "profit of the latest open trade")
// Calculates the profit for all open trades.
//@version=5
strategy("`strategy.opentrades.profit` Example 2", pyramiding = 5)
// strategy calls to enter 5 long positions every 2 bars.
if bar_index % 2 == 0
strategy.entry("Long", strategy.long, qty = 5)
// Calculate open profit or loss for the open positions.
tradeOpenpL() =>
sumprofit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumprofit += strategy.opentrades.profit(tradeNo)
result = sumprofit
plot(tradeOpenpL(), "profit of all open trades")
strategy.opentrades.size(trade_num) → series float
//@version=5
strategy("`strategy.opentrades.size` Example 1")
// We calculate the max amt of shares we can buy.
amtshares = math.floor(strategy.equity / close)
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars
if bar_index % 15 == 0
strategy.entry("Long", strategy.long, qty = amtshares)
if bar_index % 20 == 0
strategy.close("Long")
// plot the number of contracts in the latest open trade.
plot(strategy.opentrades.size(strategy.opentrades - 1), "amount of contracts in latest open trade")
// Calculates the average profit percentage for all open trades.
//@version=5
strategy("`strategy.opentrades.size` Example 2")
// strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
strategy.entry("Long", strategy.long)
if bar_index % 20 == 0
strategy.close("Long")
// Calculate profit for all open trades.
profitpct = 0.0
for tradeNo = 0 to strategy.opentrades - 1
entryp = strategy.opentrades.entry_price(tradeNo)
exitp = close
profitpct += (exitp - entryp) / entryp * strategy.opentrades.size(tradeNo) * 100
// Calculate average profit percent for all open trades.
avgprofitpct = nz(profitpct / strategy.opentrades)
plot(avgprofitpct)
strategy.order(id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert) → void
//@version=5
strategy(title = "simple strategy order example")
if open > high[1]
strategy.order("buy", strategy.long, 1) // buy by market if current open great then previous high
if open < low[1]
strategy.order("sell", strategy.short, 1) // sell by market if current open less then previous low
strategy.risk.allow_entry_in(value) → void
//@version=5
strategy("strategy.risk.allow_entry_in")
strategy.risk.allow_entry_in(strategy.direction.long)
if open > close
strategy.entry("Long", strategy.long)
// instead of opening a short position with 10 contracts, this command will close long entries.
if open < close
strategy.entry("short", strategy.short, qty = 10)
strategy.risk.max_cons_loss_days(count, alert_message) → void
//@version=5
strategy("risk.max_cons_loss_days Demo 1")
strategy.risk.max_cons_loss_days(3) // No orders will be placed after 3 days, if each day is with loss.
plot(strategy.position_size)
strategy.risk.max_drawdown(value, type, alert_message) → void
//@version=5
strategy("risk.max_drawdown Demo 1")
strategy.risk.max_drawdown(50, strategy.percent_of_equity) // set maximum drawdown to 50% of maximum equity
plot(strategy.position_size)
//@version=5
strategy("risk.max_drawdown Demo 2", currency = "EuR")
strategy.risk.max_drawdown(2000, strategy.cash) // set maximum drawdown to 2000 EuR from maximum equity
plot(strategy.position_size)
strategy.risk.max_intraday_filled_orders(count, alert_message) → void
//@version=5
strategy("risk.max_intraday_filled_orders Demo")
strategy.risk.max_intraday_filled_orders(10) // after 10 orders are filled, no more strategy orders will be placed (except for a market order to exit current open market position, if there is any).
if open > close
strategy.entry("buy", strategy.long)
if open < close
strategy.entry("sell", strategy.short)
strategy.risk.max_intraday_loss(value, type, alert_message) → void
// sets the maximum intraday loss using the strategy's equity value.
//@version=5
strategy("strategy.risk.max_intraday_loss Example 1", overlay = false, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
// input for maximum intraday loss %.
losspct = input.float(10)
// set maximum intraday loss to our losspct input
strategy.risk.max_intraday_loss(losspct, strategy.percent_of_equity)
// Enter short at bar_index zero.
if bar_index == 0
strategy.entry("short", strategy.short)
// store equity value from the beginning of the day
eqFromDaystart = ta.valuewhen(ta.change(dayofweek) > 0, strategy.equity, 0)
// Calculate change of the current equity from the beginning of the current day.
eqChgpct = 100 * ((strategy.equity - eqFromDaystart) / strategy.equity)
// plot it
plot(eqChgpct)
hline(-losspct)
// sets the maximum intraday loss using the strategy's cash value.
//@version=5
strategy("strategy.risk.max_intraday_loss Example 2", overlay = false)
// input for maximum intraday loss in absolute cash value of the symbol.
absCashLoss = input.float(5)
// set maximum intraday loss to `absCashLoss` in account currency.
strategy.risk.max_intraday_loss(absCashLoss, strategy.cash)
// Enter short at bar_index zero.
if bar_index == 0
strategy.entry("short", strategy.short)
// store the open price value from the beginning of the day.
beginprice = ta.valuewhen(ta.change(dayofweek) > 0, open, 0)
// Calculate the absolute price change for the current period.
priceChg = (close - beginprice)
hline(absCashLoss)
plot(priceChg)
strategy.risk.max_position_size(contracts) → void
//@version=5
strategy("risk.max_position_size Demo", default_qty_value = 100)
strategy.risk.max_position_size(10)
if open > close
strategy.entry("buy", strategy.long)
plot(strategy.position_size) // max plot value will be 10
string(x) → const string
string(x) → input string
string(x) → simple string
string(x) → series string
syminfo.prefix(symbol) → simple string
syminfo.prefix(symbol) → series string
//@version=5
indicator("syminfo.prefix fun", overlay=true)
i_sym = input.symbol("NasDaq:aapL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
t = ticker.new(pref, tick, session.extended)
s = request.security(t, "1D", close)
plot(s)
syminfo.ticker(symbol) → simple string
syminfo.ticker(symbol) → series string
//@version=5
indicator("syminfo.ticker fun", overlay=true)
i_sym = input.symbol("NasDaq:aapL")
pref = syminfo.prefix(i_sym)
tick = syminfo.ticker(i_sym)
t = ticker.new(pref, tick, session.extended)
s = request.security(t, "1D", close)
plot(s)
ta.alma(series, length, offset, sigma) → series float
ta.alma(series, length, offset, sigma, floor) → series float
//@version=5
indicator("ta.alma", overlay=true)
plot(ta.alma(close, 9, 0.85, 6))
// same on pine, but much less efficient
pine_alma(series, windowsize, offset, sigma) =>
m = offset * (windowsize - 1)
//m = math.floor(offset * (windowsize - 1)) // used as m when math.floor=true
s = windowsize / sigma
norm = 0.0
sum = 0.0
for i = 0 to windowsize - 1
weight = math.exp(-1 * math.pow(i - m, 2) / (2 * math.pow(s, 2)))
norm := norm + weight
sum := sum + series[windowsize - i - 1] * weight
sum / norm
plot(pine_alma(close, 9, 0.85, 6))
ta.atr(length) → series float
//@version=5
indicator("ta.atr")
plot(ta.atr(14))
//the same on pine
pine_atr(length) =>
trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
//true range can be also calculated with ta.tr(true)
ta.rma(trueRange, length)
plot(pine_atr(14))
ta.barssince(condition) → series int
//@version=5
indicator("ta.barssince")
// get number of bars since last color.green bar
plot(ta.barssince(close >= open))
ta.bb(series, length, mult) → [series float, series float, series float]
//@version=5
indicator("ta.bb")
[middle, upper, lower] = ta.bb(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
// the same on pine
f_bb(src, length, mult) =>
float basis = ta.sma(src, length)
float dev = mult * ta.stdev(src, length)
[basis, basis + dev, basis - dev]
[pinemiddle, pineupper, pineLower] = f_bb(close, 5, 4)
plot(pinemiddle)
plot(pineupper)
plot(pineLower)
ta.bbw(series, length, mult) → series float
//@version=5
indicator("ta.bbw")
plot(ta.bbw(close, 5, 4), color=color.yellow)
// the same on pine
f_bbw(src, length, mult) =>
float basis = ta.sma(src, length)
float dev = mult * ta.stdev(src, length)
((basis + dev) - (basis - dev)) / basis
plot(f_bbw(close, 5, 4))
ta.cci(source, length) → series float
ta.change(source) → series int
ta.change(source) → series float
ta.change(source, length) → series int
ta.change(source, length) → series float
ta.change(source) → series bool
ta.change(source, length) → series bool
//@version=5
indicator('Day and direction Change', overlay = true)
dailybartime = time('1D')
isNewDay = ta.change(dailybartime)
bgcolor(isNewDay ? color.new(color.green, 80) : na)
isGreenbar = close >= open
colorChange = ta.change(isGreenbar)
plotshape(colorChange, 'direction Change')
ta.cmo(series, length) → series float
//@version=5
indicator("ta.cmo")
plot(ta.cmo(close, 5), color=color.yellow)
// the same on pine
f_cmo(src, length) =>
float mom = ta.change(src)
float sm1 = math.sum((mom >= 0) ? mom : 0.0, length)
float sm2 = math.sum((mom >= 0) ? 0.0 : -mom, length)
100 * (sm1 - sm2) / (sm1 + sm2)
plot(f_cmo(close, 5))
ta.cog(source, length) → series float
//@version=5
indicator("ta.cog", overlay=true)
plot(ta.cog(close, 10))
// the same on pine
pine_cog(source, length) =>
sum = math.sum(source, length)
num = 0.0
for i = 0 to length - 1
price = source[i]
num := num + price * (i + 1)
-num / sum
plot(pine_cog(close, 10))
ta.correlation(source1, source2, length) → series float
ta.cross(source1, source2) → series bool
ta.crossover(source1, source2) → series bool
ta.crossunder(source1, source2) → series bool
ta.cum(source) → series float
ta.dev(source, length) → series float
//@version=5
indicator("ta.dev")
plot(ta.dev(close, 10))
// the same on pine
pine_dev(source, length) =>
mean = ta.sma(source, length)
sum = 0.0
for i = 0 to length - 1
val = source[i]
sum := sum + math.abs(val - mean)
dev = sum/length
plot(pine_dev(close, 10))
ta.dmi(diLength, adxsmoothing) → [series float, series float, series float]
//@version=5
indicator(title="directional Movement index", shorttitle="DMi", format=format.price, precision=4)
len = input.int(17, minval=1, title="Di Length")
lensig = input.int(14, title="aDX smoothing", minval=1, maxval=50)
[diplus, diminus, adx] = ta.dmi(len, lensig)
plot(adx, color=color.red, title="aDX")
plot(diplus, color=color.blue, title="+Di")
plot(diminus, color=color.orange, title="-Di")
ta.ema(source, length) → series float
//@version=5
indicator("ta.ema")
plot(ta.ema(close, 15))
//the same on pine
pine_ema(src, length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_ema(close,15))
ta.falling(source, length) → series bool
ta.highest(length) → series float
ta.highest(source, length) → series float
ta.highestbars(length) → series int
ta.highestbars(source, length) → series int
ta.hma(source, length) → series float
//@version=5
indicator("Hull Moving average")
src = input(defval=close, title="source")
length = input(defval=9, title="Length")
hmabuildin = ta.hma(src, length)
plot(hmabuildin, title="Hull Ma", color=#674Ea7)
ta.kc(series, length, mult) → [series float, series float, series float]
ta.kc(series, length, mult, usetrueRange) → [series float, series float, series float]
//@version=5
indicator("ta.kc")
[middle, upper, lower] = ta.kc(close, 5, 4)
plot(middle, color=color.yellow)
plot(upper, color=color.yellow)
plot(lower, color=color.yellow)
// the same on pine
f_kc(src, length, mult, usetrueRange) =>
float basis = ta.ema(src, length)
float span = (usetrueRange) ? ta.tr : (high - low)
float rangeema = ta.ema(span, length)
[basis, basis + rangeema * mult, basis - rangeema * mult]
[pinemiddle, pineupper, pineLower] = f_kc(close, 5, 4, true)
plot(pinemiddle)
plot(pineupper)
plot(pineLower)
ta.kcw(series, length, mult) → series float
ta.kcw(series, length, mult, usetrueRange) → series float
//@version=5
indicator("ta.kcw")
plot(ta.kcw(close, 5, 4), color=color.yellow)
// the same on pine
f_kcw(src, length, mult, usetrueRange) =>
float basis = ta.ema(src, length)
float span = (usetrueRange) ? ta.tr : (high - low)
float rangeema = ta.ema(span, length)
((basis + rangeema * mult) - (basis - rangeema * mult)) / basis
plot(f_kcw(close, 5, 4, true))
ta.linreg(source, length, offset) → series float
ta.lowest(length) → series float
ta.lowest(source, length) → series float
ta.lowestbars(length) → series int
ta.lowestbars(source, length) → series int
ta.macd(source, fastlen, slowlen, siglen) → [series float, series float, series float]
//@version=5
indicator("MaCD")
[macdline, signalline, histline] = ta.macd(close, 12, 26, 9)
plot(macdline, color=color.blue)
plot(signalline, color=color.orange)
plot(histline, color=color.red, style=plot.style_histogram)
//@version=5
indicator("MaCD")
[_, signalline, _] = ta.macd(close, 12, 26, 9)
plot(signalline, color=color.orange)
ta.max(source) → series float
ta.median(source, length) → series int
ta.median(source, length) → series float
ta.mfi(series, length) → series float
//@version=5
indicator("Money Flow index")
plot(ta.mfi(hlc3, 14), color=color.yellow)
// the same on pine
pine_mfi(src, length) =>
float upper = math.sum(volume * (ta.change(src) <= 0.0 ? 0.0 : src), length)
float lower = math.sum(volume * (ta.change(src) >= 0.0 ? 0.0 : src), length)
mfi = 100.0 - (100.0 / (1.0 + upper / lower))
mfi
plot(pine_mfi(hlc3, 14))
ta.min(source) → series float
ta.mode(source, length) → series int
ta.mode(source, length) → series float
ta.mom(source, length) → series float
ta.percentile_linear_interpolation(source, length, percentage) → series float
ta.percentile_nearest_rank(source, length, percentage) → series float
ta.percentrank(source, length) → series float
ta.pivot_point_levels(type, anchor, developing) → float[]
//@version=5
indicator("Weekly pivots", max_lines_count=500, overlay=true)
timeframe = "1W"
typeinput = input.string("traditional", "Type", options=["traditional", "Fibonacci", "Woodie", "Classic", "DM", "Camarilla"])
weekChange = timeframe.change(timeframe)
pivotpointsarray = ta.pivot_point_levels(typeinput, weekChange)
if weekChange
for pivotLevel in pivotpointsarray
line.new(time, pivotLevel, time + timeframe.in_seconds(timeframe) * 1000, pivotLevel, xloc=xloc.bar_time)
ta.pivothigh(leftbars, rightbars) → series float
ta.pivothigh(source, leftbars, rightbars) → series float
//@version=5
indicator("pivothigh", overlay=true)
leftbars = input(2)
rightbars=input(2)
ph = ta.pivothigh(leftbars, rightbars)
plot(ph, style=plot.style_cross, linewidth=3, color= color.red, offset=-rightbars)
ta.pivotlow(leftbars, rightbars) → series float
ta.pivotlow(source, leftbars, rightbars) → series float
//@version=5
indicator("pivotLow", overlay=true)
leftbars = input(2)
rightbars=input(2)
pl = ta.pivotlow(close, leftbars, rightbars)
plot(pl, style=plot.style_cross, linewidth=3, color= color.blue, offset=-rightbars)
ta.range(source, length) → series int
ta.range(source, length) → series float
ta.rising(source, length) → series bool
ta.rma(source, length) → series float
//@version=5
indicator("ta.rma")
plot(ta.rma(close, 15))
//the same on pine
pine_rma(src, length) =>
alpha = 1/length
sum = 0.0
sum := na(sum[1]) ? ta.sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_rma(close, 15))
ta.roc(source, length) → series float
ta.rsi(source, length) → series float
//@version=5
indicator("ta.rsi")
plot(ta.rsi(close, 7))
// same on pine, but less efficient
pine_rsi(x, y) =>
u = math.max(x - x[1], 0) // upward ta.change
d = math.max(x[1] - x, 0) // downward ta.change
rs = ta.rma(u, y) / ta.rma(d, y)
res = 100 - 100 / (1 + rs)
res
plot(pine_rsi(close, 7))
ta.sar(start, inc, max) → series float
//@version=5
indicator("ta.sar")
plot(ta.sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)
// the same on pine script®
pine_sar(start, inc, max) =>
var float result = na
var float maxMin = na
var float acceleration = na
var bool isbelow = na
bool isFirsttrendbar = false
if bar_index == 1
if close > close[1]
isbelow := true
maxMin := high
result := low[1]
else
isbelow := false
maxMin := low
result := high[1]
isFirsttrendbar := true
acceleration := start
result := result + acceleration * (maxMin - result)
if isbelow
if result > low
isFirsttrendbar := true
isbelow := false
result := math.max(high, maxMin)
maxMin := low
acceleration := start
else
if result < high
isFirsttrendbar := true
isbelow := true
result := math.min(low, maxMin)
maxMin := high
acceleration := start
if not isFirsttrendbar
if isbelow
if high > maxMin
maxMin := high
acceleration := math.min(acceleration + inc, max)
else
if low < maxMin
maxMin := low
acceleration := math.min(acceleration + inc, max)
if isbelow
result := math.min(result, low[1])
if bar_index > 1
result := math.min(result, low[2])
else
result := math.max(result, high[1])
if bar_index > 1
result := math.max(result, high[2])
result
plot(pine_sar(0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)
ta.sma(source, length) → series float
//@version=5
indicator("ta.sma")
plot(ta.sma(close, 15))
// same on pine, but much less efficient
pine_sma(x, y) =>
sum = 0.0
for i = 0 to y - 1
sum := sum + x[i] / y
sum
plot(pine_sma(close, 15))
ta.stdev(source, length, biased) → series float
//@version=5
indicator("ta.stdev")
plot(ta.stdev(close, 5))
//the same on pine
isZero(val, eps) => math.abs(val) <= eps
suM(fst, snd) =>
Eps = 1e-10
res = fst + snd
if isZero(res, Eps)
res := 0
else
if not isZero(res, 1e-4)
res := res
else
15
pine_stdev(src, length) =>
avg = ta.sma(src, length)
sumOfsquareDeviations = 0.0
for i = 0 to length - 1
sum = suM(src[i], -avg)
sumOfsquareDeviations := sumOfsquareDeviations + sum * sum
stdev = math.sqrt(sumOfsquareDeviations / length)
plot(pine_stdev(close, 5))
ta.stoch(source, high, low, length) → series float
ta.supertrend(factor, atrperiod) → [series float, series float]
//@version=5
indicator("pine script® supertrend")
[supertrend, direction] = ta.supertrend(3, 10)
plot(direction < 0 ? supertrend : na, "up direction", color = color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style=plot.style_linebr)
// the same on pine script®
pine_supertrend(factor, atrperiod) =>
src = hl2
atr = ta.atr(atrperiod)
upperband = src + factor * atr
lowerband = src - factor * atr
prevLowerband = nz(lowerband[1])
prevupperband = nz(upperband[1])
lowerband := lowerband > prevLowerband or close[1] < prevLowerband ? lowerband : prevLowerband
upperband := upperband < prevupperband or close[1] > prevupperband ? upperband : prevupperband
int direction = na
float supertrend = na
prevsupertrend = supertrend[1]
if na(atr[1])
direction := 1
else if prevsupertrend == prevupperband
direction := close > upperband ? -1 : 1
else
direction := close < lowerband ? 1 : -1
supertrend := direction == -1 ? lowerband : upperband
[supertrend, direction]
[pine_supertrend, pinedirection] = pine_supertrend(3, 10)
plot(pinedirection < 0 ? pine_supertrend : na, "up direction", color = color.green, style=plot.style_linebr)
plot(pinedirection > 0 ? pine_supertrend : na, "Down direction", color = color.red, style=plot.style_linebr)
ta.swma(source) → series float
//@version=5
indicator("ta.swma")
plot(ta.swma(close))
// same on pine, but less efficient
pine_swma(x) =>
x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6
plot(pine_swma(close))
ta.tr(handle_na) → series float
ta.tsi(source, short_length, long_length) → series float
ta.valuewhen(condition, source, occurrence) → series color
ta.valuewhen(condition, source, occurrence) → series int
ta.valuewhen(condition, source, occurrence) → series float
ta.valuewhen(condition, source, occurrence) → series bool
//@version=5
indicator("ta.valuewhen")
slow = ta.sma(close, 7)
fast = ta.sma(close, 14)
// Get value of `close` on second most recent cross
plot(ta.valuewhen(ta.cross(slow, fast), close, 1))
ta.variance(source, length, biased) → series float
ta.vwap(source) → series float
ta.vwap(source, anchor) → series float
ta.vwap(source, anchor, stdev_mult) → [series float, series float, series float]
//@version=5
indicator("simple VWap")
vwap = ta.vwap(open)
plot(vwap)
//@version=5
indicator("advanced VWap")
vwapanchorinput = input.string("Daily", "anchor", options = ["Daily", "Weekly", "Monthly"])
stdevMultiplierinput = input.float(1.0, "standard Deviation Multiplier")
anchortimeframe = switch vwapanchorinput
"Daily" => "1D"
"Weekly" => "1W"
"Monthly" => "1M"
anchor = timeframe.change(anchortimeframe)
[vwap, upper, lower] = ta.vwap(open, anchor, stdevMultiplierinput)
plot(vwap)
plot(upper, color = color.green)
plot(lower, color = color.green)
ta.vwma(source, length) → series float
//@version=5
indicator("ta.vwma")
plot(ta.vwma(close, 15))
// same on pine, but less efficient
pine_vwma(x, y) =>
ta.sma(x * volume, y) / ta.sma(volume, y)
plot(pine_vwma(close, 15))
ta.wma(source, length) → series float
//@version=5
indicator("ta.wma")
plot(ta.wma(close, 15))
// same on pine, but much less efficient
pine_wma(x, y) =>
norm = 0.0
sum = 0.0
for i = 0 to y - 1
weight = (y - i) * y
norm := norm + weight
sum := sum + x[i] * weight
sum / norm
plot(pine_wma(close, 15))
ta.wpr(length) → series float
//@version=5
indicator("Williams %R", shorttitle="%R", format=format.price, precision=2)
plot(ta.wpr(14), title="%R", color=color.new(#ff6d00, 0))
table.cell(table_id, column, row, text, width, height, text_color, text_halign, text_valign, text_size, bgcolor, tooltip, text_font_family) → void
table.cell_set_bgcolor(table_id, column, row, bgcolor) → void
table.cell_set_height(table_id, column, row, height) → void
table.cell_set_text(table_id, column, row, text) → void
//@version=5
indicator("table example")
var tLog = table.new(position = position.top_left, rows = 1, columns = 2, bgcolor = color.yellow, border_width=1)
table.cell(tLog, row = 0, column = 0, text = "sometext", text_color = color.blue)
table.cell_set_text(tLog, row = 0, column = 0, text = "sometext")
table.cell_set_text_color(table_id, column, row, text_color) → void
table.cell_set_text_font_family(table_id, column, row, text_font_family) → void
//@version=5
indicator("Example of setting the table cell font")
var t = table.new(position.top_left, rows = 1, columns = 1)
table.cell(t, 0, 0, "monospace", text_color = color.blue)
table.cell_set_text_font_family(t, 0, 0, font.family_monospace)
table.cell_set_text_halign(table_id, column, row, text_halign) → void
table.cell_set_text_size(table_id, column, row, text_size) → void
table.cell_set_text_valign(table_id, column, row, text_valign) → void
table.cell_set_tooltip(table_id, column, row, tooltip) → void
//@version=5
indicator("table example")
var tLog = table.new(position = position.top_left, rows = 1, columns = 2, bgcolor = color.yellow, border_width=1)
table.cell(tLog, row = 0, column = 0, text = "sometext", text_color = color.blue)
table.cell_set_tooltip(tLog, row = 0, column = 0, tooltip = "sometext")
table.cell_set_width(table_id, column, row, width) → void
table.clear(table_id, start_column, start_row, end_column, end_row) → void
//@version=5
indicator("a donut", overlay=true)
if barstate.islast
colNum = 8, rowNum = 8
padding = "◯"
donuttable = table.new(position.middle_right, colNum, rowNum)
for c = 0 to colNum - 1
for r = 0 to rowNum - 1
table.cell(donuttable, c, r, text=padding, bgcolor=#face6e, text_color=color.new(color.black, 100))
table.clear(donuttable, 2, 2, 5, 5)
table.delete(table_id) → void
//@version=5
indicator("table.delete example")
var testtable = table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
if barstate.islast
table.cell(table_id = testtable, column = 0, row = 0, text = "Open is " + str.tostring(open))
table.cell(table_id = testtable, column = 1, row = 0, text = "Close is " + str.tostring(close), bgcolor=color.teal)
if barstate.isrealtime
table.delete(testtable)
table.merge_cells(table_id, start_column, start_row, end_column, end_row) → void
//@version=5
indicator("table.merge_cells example")
sMa50 = ta.sma(close, 50)
sMa100 = ta.sma(close, 100)
sMa200 = ta.sma(close, 200)
if barstate.islast
matable = table.new(position.bottom_right, 3, 3, bgcolor = color.gray, border_width = 1, border_color = color.black)
// header
table.cell(matable, 0, 0, text = "sMa table")
table.merge_cells(matable, 0, 0, 2, 0)
// Cell titles
table.cell(matable, 0, 1, text = "sMa 50")
table.cell(matable, 1, 1, text = "sMa 100")
table.cell(matable, 2, 1, text = "sMa 200")
// Values
table.cell(matable, 0, 2, bgcolor = color.white, text = str.tostring(sMa50))
table.cell(matable, 1, 2, bgcolor = color.white, text = str.tostring(sMa100))
table.cell(matable, 2, 2, bgcolor = color.white, text = str.tostring(sMa200))
table.new(position, columns, rows, bgcolor, frame_color, frame_width, border_color, border_width) → series table
//@version=5
indicator("table.new example")
var testtable = table.new(position = position.top_right, columns = 2, rows = 1, bgcolor = color.yellow, border_width = 1)
if barstate.islast
table.cell(table_id = testtable, column = 0, row = 0, text = "Open is " + str.tostring(open))
table.cell(table_id = testtable, column = 1, row = 0, text = "Close is " + str.tostring(close), bgcolor=color.teal)
table.set_bgcolor(table_id, bgcolor) → void
table.set_border_color(table_id, border_color) → void
table.set_border_width(table_id, border_width) → void
table.set_frame_color(table_id, frame_color) → void
table.set_frame_width(table_id, frame_width) → void
table.set_position(table_id, position) → void
ticker.heikinashi(symbol) → simple string
//@version=5
indicator("ticker.heikinashi", overlay=true)
heikinashi_close = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_aapl_60_close = request.security(ticker.heikinashi("aapL"), "60", close)
plot(heikinashi_close)
plot(heikinashi_aapl_60_close)
ticker.inherit(from_tickerid, symbol) → simple string
//@version=5
indicator("ticker.inherit")
//@variable a "NasDaq:aapL" ticker iD with Extender Hours enabled.
tickerExthours = ticker.new("NasDaq", "aapL", session.extended)
//@variable a Heikin ashi ticker iD for "NasDaq:aapL" with Extended Hours enabled.
HatickerExthours = ticker.heikinashi(tickerExthours)
//@variable the "NasDaq:MsFT" symbol with no modifiers.
testsymbol = "NasDaq:MsFT"
//@variable a ticker iD for "NasDaq:MsFT" with inherited Heikin ashi and Extended Hours modifiers.
testsymbolHatickerExthours = ticker.inherit(HatickerExthours, testsymbol)
//@variable the `close` price requested using "NasDaq:MsFT" with inherited modifiers.
secdata = request.security(testsymbolHatickerExthours, "60", close, ignore_invalid_symbol = true)
//@variable the `close` price requested using "NasDaq:MsFT" without modifiers.
comparedata = request.security(testsymbol, "60", close, ignore_invalid_symbol = true)
plot(secdata, color = color.green)
plot(comparedata)
ticker.kagi(symbol, reversal) → simple string
//@version=5
indicator("ticker.kagi", overlay=true)
kagi_tickerid = ticker.kagi(syminfo.tickerid, 3)
kagi_close = request.security(kagi_tickerid, timeframe.period, close)
plot(kagi_close)
ticker.linebreak(symbol, number_of_lines) → simple string
//@version=5
indicator("ticker.linebreak", overlay=true)
linebreak_tickerid = ticker.linebreak(syminfo.tickerid, 3)
linebreak_close = request.security(linebreak_tickerid, timeframe.period, close)
plot(linebreak_close)
ticker.modify(tickerid, session, adjustment) → simple string
//@version=5
indicator("ticker_modify", overlay=true)
t1 = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
c1 = request.security(t1, "D", close)
t2 = ticker.modify(t1, session.extended)
c2 = request.security(t2, "2D", close)
plot(c1)
plot(c2)
ticker.new(prefix, ticker, session, adjustment) → simple string
//@version=5
indicator("ticker.new", overlay=true)
t = ticker.new(syminfo.prefix, syminfo.ticker, session.regular, adjustment.splits)
t2 = ticker.heikinashi(t)
c = request.security(t2, timeframe.period, low, barmerge.gaps_on)
plot(c, style=plot.style_linebr)
ticker.pointfigure(symbol, source, style, param, reversal) → simple string
//@version=5
indicator("ticker.pointfigure", overlay=true)
pnf_tickerid = ticker.pointfigure(syminfo.tickerid, "hl", "traditional", 1, 3)
pnf_close = request.security(pnf_tickerid, timeframe.period, close)
plot(pnf_close)
ticker.renko(symbol, style, param, request_wicks, source) → simple string
//@version=5
indicator("ticker.renko", overlay=true)
renko_tickerid = ticker.renko(syminfo.tickerid, "atr", 10)
renko_close = request.security(renko_tickerid, timeframe.period, close)
plot(renko_close)
//@version=5
indicator("Renko candles", overlay=false)
renko_tickerid = ticker.renko(syminfo.tickerid, "atr", 10)
[renko_open, renko_high, renko_low, renko_close] = request.security(renko_tickerid, timeframe.period, [open, high, low, close])
plotcandle(renko_open, renko_high, renko_low, renko_close, color = renko_close > renko_open ? color.green : color.red)
ticker.standard(symbol) → simple string
//@version=5
indicator("ticker.standard", overlay = true)
// this script should be run on a non-standard chart such as Ha, Renko...
// Requests data from the chart type the script is running on.
charttypeValue = request.security(syminfo.tickerid, "1D", close)
// Request data from the standard chart type, regardless of the chart type the script is running on.
standardChartValue = request.security(ticker.standard(syminfo.tickerid), "1D", close)
// this will not use a standard ticker iD because the `symbol` argument contains only the ticker — not the prefix (exchange).
standardChartValue2 = request.security(ticker.standard(syminfo.ticker), "1D", close)
plot(charttypeValue)
plot(standardChartValue, color = color.green)
time(timeframe) → series int
time(timeframe, session) → series int
time(timeframe, session, timezone) → series int
//@version=5
indicator("time", overlay=true)
// try this on chart aapL,1
timeinrange(res, sess) => not na(time(res, sess, "america/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=color.red)
// this plots 1.0 at every start of 10 minute bar on a 1 minute chart:
newbar(res) => ta.change(time(res)) == 0 ? 0 : 1
plot(newbar("10"))
//@version=5
indicator("time", overlay=true)
t1 = time(timeframe.period, "0000-0000:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
//@version=5
indicator("time", overlay=true)
t1 = time(timeframe.period, "1000-1100,1400-1500:23456")
bgcolor(t1 ? color.new(color.blue, 90) : na)
time_close(timeframe) → series int
time_close(timeframe, session) → series int
time_close(timeframe, session, timezone) → series int
//@version=5
indicator("time", overlay=true)
t1 = time_close(timeframe.period, "1200-1300", "america/New_York")
bgcolor(t1 ? color.new(color.blue, 90) : na)
timeframe.change(timeframe) → series bool
//@version=5
// Run this script on an intraday chart.
indicator("New day started", overlay = true)
// Highlights the first bar of the new day.
isNewDay = timeframe.change("1D")
bgcolor(isNewDay ? color.new(color.green, 80) : na)
timeframe.from_seconds(seconds) → simple string
timeframe.from_seconds(seconds) → series string
//@version=5
indicator("HTF Close", "", true)
int charttf = timeframe.in_seconds()
string tftimes5 = timeframe.from_seconds(charttf * 5)
float htfClose = request.security(syminfo.tickerid, tftimes5, close)
plot(htfClose)
timeframe.in_seconds(timeframe) → simple int
timeframe.in_seconds(timeframe) → series int
//@version=5
indicator("`timeframe_in_seconds()`")
// Get a user-selected timeframe.
tfinput = input.timeframe("1D")
// Convert it into an "int" number of seconds.
secondsinTf = timeframe.in_seconds(tfinput)
plot(secondsinTf)
timestamp(datestring) → const int
timestamp(year, month, day, hour, minute, second) → simple int
timestamp(year, month, day, hour, minute, second) → series int
timestamp(timezone, year, month, day, hour, minute, second) → simple int
timestamp(timezone, year, month, day, hour, minute, second) → series int
//@version=5
indicator("timestamp")
plot(timestamp(2016, 01, 19, 09, 30), linewidth=3, color=color.green)
plot(timestamp(syminfo.timezone, 2016, 01, 19, 09, 30), color=color.blue)
plot(timestamp(2016, 01, 19, 09, 30), color=color.yellow)
plot(timestamp("GMT+6", 2016, 01, 19, 09, 30))
plot(timestamp(2019, 06, 19, 09, 30, 15), color=color.lime)
plot(timestamp("GMT+3", 2019, 06, 19, 09, 30, 15), color=color.fuchsia)
plot(timestamp("Feb 01 2020 22:10:05"))
plot(timestamp("2011-10-10T14:48:00"))
plot(timestamp("04 Dec 1995 00:12:00 GMT+5"))
weekofyear(time) → series int
weekofyear(time, timezone) → series int
year(time) → series int
year(time, timezone) → series int
//@version=5
strategy("strategy.cash", overlay = true, default_qty_value = 50, default_qty_type = strategy.cash, initial_capital = 1000000)
if bar_index == 0
// as ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_value` parameters are used to enter trades, namely 50 units of cash in the currency of `strategy.account_currency`.
// `qty` is calculated as (default_qty_value)/(close price). if current price is $5, then qty = 50/5 = 10.
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
//@version=5
strategy("strategy.fixed", overlay = true, default_qty_value = 50, default_qty_type = strategy.fixed, initial_capital = 1000000)
if bar_index == 0
// as ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_value` parameters are used to enter trades, namely 50 contracts.
// qty = 50
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
//@version=5
strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, initial_capital = 1000000)
// as ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_value` parameters are used to enter trades, namely 100% of available equity.
if bar_index == 0
strategy.entry("EN", strategy.long)
if bar_index == 2
strategy.close("EN")
plot(strategy.equity)
// the ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry market price = (10 * close).
if bar_index == 4
strategy.entry("EN", strategy.long, qty = 10)
if bar_index == 6
strategy.close("EN")
expr1 and expr2
//@version=5
//@description library of debugging functions.
library("Debugging_library", overlay = true)
//@function Displays a string as a table cell for debugging purposes.
//@param txt string to display.
//@returns Void.
export print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
// using the function from inside the library to show an example on the published chart.
// this has no impact on scripts using the library.
print("library Test")
[var_declaration =] for counter = from_num to to_num [by step_num] statements | continue | break return_expression
//@version=5
indicator("for")
// Here, we count the quantity of bars in a given 'lookback' length which closed above the current bar's close
qtyOfHigherCloses(lookback) =>
int result = 0
for i = 1 to lookback
if close[i] > close
result += 1
result
plot(qtyOfHigherCloses(14))
//@version=5
indicator("`for` loop with a step")
a = array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0.0
for i = 0 to 9 by 5
// because the step is set to 5, we are adding only the first (0) and the sixth (5) value from the array `a`.
sum += array.get(a, i)
plot(sum)
[var_declaration =] for array_element in array_id statements | continue | break return_expression [var_declaration =] for [index, array_element] in array_id statements | continue | break return_expression
//@version=5
indicator("for...in")
// Here we determine on each bar how many of the bar's OHLC values are greater than the sMa of 'close' values
float[] ohlcValues = array.from(open, high, low, close)
qtyGreaterthan(value, array) =>
int result = 0
for currentelement in array
if currentelement > value
result += 1
result
plot(qtyGreaterthan(ta.sma(close, 20), ohlcValues))
//@version=5
indicator("for...in")
var valuesarray = array.from(4, -8, 11, 78, -16, 34, 7, 99, 0, 55)
var ispos = array.new_bool(10, false)
for [index, value] in valuesarray
if value > 0
array.set(ispos, index, true)
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(ispos))
//@version=5
indicator("`for ... in` matrix Example")
// Create a 2x3 matrix with values `4`.
matrix1 = matrix.new<int>(2, 3, 4)
sum = 0.0
// Loop through every row of the matrix.
for rowarray in matrix1
// sum values of the every row
sum += array.sum(rowarray)
plot(sum)
var_declarationX = if condition var_decl_then0 var_decl_then1 … var_decl_thenN else if [optional block] var_decl_else0 var_decl_else1 … var_decl_elseN else var_decl_else0 var_decl_else1 … var_decl_elseN return_expression_else
//@version=5
indicator("if")
// this code compiles
x = if close > open
close
else
open
// this code doesn’t compile
// y = if close > open
// close
// else
// "open"
plot(x)
//@version=5
indicator("if")
x = if close > open
close
// if current close > current open, then x = close.
// Otherwise the x = na.
plot(x)
//@version=5
indicator("if")
x = if open > close
5
else if high > low
close
else
open
plot(x)
//@version=5
strategy("if")
if (ta.crossover(high, low))
strategy.entry("bbandlE", strategy.long, stop=low, oca_name="bollingerbands", oca_type=strategy.oca.cancel, comment="bbandlE")
else
strategy.cancel(id="bbandlE")
//@version=5
indicator("if")
float x = na
if close > open
if close > close[1]
x := close
else
x := close[1]
else
x := open
plot(x)
import {username}/{libraryName}/{libraryVersion} as {alias}
//@version=5
indicator("num_methods import")
// import the first version of the username’s "num_methods" library and assign it to the "m" namespace",
import username/num_methods/1 as m
// Call the “sinh()” function from the imported library
y = m.sinh(3.14)
// plot value returned by the "sinh()" function",
plot(y)
[export] method <functionName>(<paramType> <paramName> [= <defaultValue>], …) => <functionblock>
//@version=5
indicator("")
var prices = array.new<float>()
//@function pushes a new value into the array and removes the first one if the resulting array is greater than `maxsize`. Can be used as a method.
method maintainarray(array<float> id, maxsize, value) =>
id.push(value)
if id.size() > maxsize
id.shift()
prices.maintainarray(50, close)
// the method can also be called like a function, without using dot notation.
// in this case an argument must be supplied for its first parameter.
// maintainarray(prices, 50, close)
// this calls the `array.avg()` built-in using dot notation with the `prices` array.
// it is possible because built-in functions belonging to some namespaces that are a special pine type
// can be invoked with method notation when the function's first parameter is an iD of that type.
// those namespaces are: `array`, `matrix`, `line`, `linefill`, `label`, `box`, and `table`.
plot(prices.avg())
not expr1
expr1 or expr2
[variable_declaration = ] switch expression value1 => local_block value2 => local_block … => default_local_block [variable_declaration = ] switch boolean_expression1 => local_block boolean_expression2 => local_block … => default_local_block
//@version=5
indicator("switch using an expression")
string i_maType = input.string("ema", "Ma type", options = ["ema", "sMa", "RMa", "WMa"])
float ma = switch i_maType
"ema" => ta.ema(close, 10)
"sMa" => ta.sma(close, 10)
"RMa" => ta.rma(close, 10)
// Default used when the three first cases do not match.
=> ta.wma(close, 10)
plot(ma)
//@version=5
strategy("switch without an expression", overlay = true)
bool longCondition = ta.crossover( ta.sma(close, 14), ta.sma(close, 28))
bool shortcondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
switch
longCondition => strategy.entry("Long iD", strategy.long)
shortcondition => strategy.entry("short iD", strategy.short)
[export ]type <udt_identifier> [varip ]<field_type> <field_name> [= <value>] …
//@version=5
indicator("Multi time period Chart", overlay = true)
timeframeinput = input.timeframe("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
drawbox(bar b, right) =>
bar s = bar.new()
color boxcolor = b.c >= b.o ? color.green : color.red
box.new(b.t, b.h, right, b.l, boxcolor, xloc = xloc.bar_time, bgcolor = color.new(boxcolor, 90))
updatebox(box boxid, bar b) =>
color boxcolor = b.c >= b.o ? color.green : color.red
box.set_border_color(boxid, boxcolor)
box.set_bgcolor(boxid, color.new(boxcolor, 90))
box.set_top(boxid, b.h)
box.set_bottom(boxid, b.l)
box.set_right(boxid, time)
secbar = request.security(syminfo.tickerid, timeframeinput, bar.new())
if not na(secbar)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeinput)
// On historical bars, draw a new box in the past when the HTF closes.
drawbox(secbar, time[1])
else
var box lastbox = na
if na(lastbox) or timeframe.change(timeframeinput)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastbox := drawbox(secbar, time)
else
// On other chart updates, use setters to modify the current box.
updatebox(lastbox, secbar)
var variable_name = expression
//@version=5
indicator("var keyword example")
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
if close > open
var x = close
b := x
green_bars_count := green_bars_count + 1
if green_bars_count >= 10
var y = close
c := y
plot(a)
plot(b)
plot(c)
varip [<variable_type> ]<variable_name> = <expression> [export ]type <udt_identifier> varip <field_type> <field_name> [= <value>]
//@version=5
indicator("varip")
varip int v = -1
v := v + 1
plot(v)
//@version=5
indicator("varip with types")
type bardata
int index = -1
varip int ticks = -1
var currbar = bardata.new()
currbar.index += 1
currbar.ticks += 1
// Will be equal to bar_index on all bars
plot(currbar.index)
// in real time, will increment per every tick on the chart
plot(currbar.ticks)
variable_declaration = while boolean_expression … continue … break … return_expression
//@version=5
indicator("while")
// this is a simple example of calculating a factorial using a while loop.
int i_n = input.int(10, "Factorial size", minval=0)
int counter = i_n
int factorial = 1
while counter > 0
factorial := factorial * counter
counter := counter - 1
plot(factorial)
//@version=5
indicator("array", overlay=true)
array<float> a = na
a := array.new<float>(1, close)
plot(array.get(a, 0))
//@version=5
indicator("bool")
bool b = true // same as `b = true`
b := na
plot(b ? open : close)
//@version=5
indicator("box")
// empty `box1` box iD.
var box box1 = na
// `box` type is unnecessary because `box.new()` returns a "box" type.
var box2 = box.new(na, na, na, na)
box3 = box.new(time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
//@version=5
indicator("color", overlay = true)
color textcolor = color.green
color labelcolor = #FF000080 // Red color (FF0000) with 50% transparency (80 which is half of FF).
if barstate.islastconfirmedhistory
label.new(bar_index, high, text = "label", color = labelcolor, textcolor = textcolor)
// When declaring variables with color literals, built-in constants(color.green) or functions (color.new(), color.rgb()), the "color" keyword for the type can be omitted.
c = color.rgb(0,255,0,0)
plot(close, color = c)
//@version=5
indicator("float")
float f = 3.14 // same as `f = 3.14`
f := na
plot(f)
//@version=5
indicator("int")
int i = 14 // same as `i = 14`
i := na
plot(i)
//@version=5
indicator("label")
// empty `label1` label iD.
var label label1 = na
// `label` type is unnecessary because `label.new()` returns "label" type.
var label2 = label.new(na, na, na)
if barstate.islastconfirmedhistory
label3 = label.new(bar_index, high, text = "label3 text")
//@version=5
indicator("line")
// empty `line1` line iD.
var line line1 = na
// `line` type is unnecessary because `line.new()` returns "line" type.
var line2 = line.new(na, na, na, na)
line3 = line.new(bar_index - 1, high, bar_index, high, extend = extend.right)
//@version=5
indicator("linefill", overlay=true)
// empty `linefill1` line iD.
var linefill linefill1 = na
// `linefill` type is unnecessary because `linefill.new()` returns "linefill" type.
var linefill2 = linefill.new(na, na, na)
if barstate.islastconfirmedhistory
line1 = line.new(bar_index - 10, high+1, bar_index, high+1, extend = extend.right)
line2 = line.new(bar_index - 10, low+1, bar_index, low+1, extend = extend.right)
linefill3 = linefill.new(line1, line2, color = color.new(color.green, 80))
//@version=5
indicator("map", overlay=true)
map<int, float> a = na
a := map.new<int, float>()
a.put(bar_index, close)
label.new(bar_index, a.get(bar_index), "Current close")
//@version=5
indicator("matrix example")
// Create `m1` matrix of `int` type.
matrix<int> m1 = matrix.new<int>(2, 3, 0)
// `matrix<int>` is unnecessary because the `matrix.new<int>()` function returns an `int` type matrix object.
m2 = matrix.new<int>(2, 3, 0)
// Display matrix using a label.
if barstate.islastconfirmedhistory
label.new(bar_index, high, str.tostring(m2))
export <functionName>([[series] <type>] <arg1>[ = <default_value>])
//@version=5
//@description library of debugging functions.
library("Debugging_library", overlay = true)
export smaCustom(series float source, series int length) =>
ta.sma(source, length)
export <functionName>([[simple] <type>] <arg1>[ = <default_value>])
//@version=5
//@description library of debugging functions.
library("Debugging_library", overlay = true)
export emaWrong(float source, int length) =>
// by default, both `source` and `length` will expect values of the `series` type form: `series float` for `source`, `series int` for `length`.
// this function will not compile because `ema()` does not support a "series int" argument for `length`. a "simple int" is required.
ta.ema(source, length)
export emaRight(float source, simple int length) =>
// this function requires an argument of "simple int" type for its `length` parameter.
ta.ema(source, length)
//@version=5
indicator("string")
string s = "Hello World!" // same as `s = "Hello world!"`
// string s = na // same as ""
plot(na, title=s)
//@version=5
indicator("table")
// empty `table1` table iD.
var table table1 = na
// `table` type is unnecessary because `table.new()` returns "table" type.
var table2 = table.new(position.top_left, na, na)
if barstate.islastconfirmedhistory
var table3 = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = table3, column = 0, row = 0, text = "table3 text")
expr1 - expr2
expr1 -= expr2
//@version=5
indicator("-=")
// Equals to expr1 = expr1 - expr2.
a = 2
b = 3
a -= b
// Result: a = -1.
plot(a)
<var_name> := <new_value>
//@version=5
indicator("My script")
myvar = 10
if close > open
// Modifies the existing global scope `myvar` variable by changing its value from 10 to 20.
myvar := 20
// Creates a new `myvar` variable local to the `if` condition and unreachable from the global scope.
// Does not affect the `myvar` declared in global scope.
myvar = 30
plot(myvar)
expr1 != expr2
expr1 ? expr2 : expr3
//@version=5
indicator("?:")
// Draw circles at the bars where open crosses close
s2 = ta.cross(open, close) ? math.avg(open,close) : na
plot(s2, style=plot.style_circles, linewidth=2, color=color.red)
// Combination of ?: operators for 'switch'-like logic
c = timeframe.isintraday ? color.red : timeframe.isdaily ? color.green : timeframe.isweekly ? color.blue : color.gray
plot(hl2, color=c)
expr1[expr2]
//@version=5
indicator("[]")
// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
if high == low // if some condition - change `a` value to another
a := low
plot(a)
expr1 * expr2
expr1 *= expr2
//@version=5
indicator("*=")
// Equals to expr1 = expr1 * expr2.
a = 2
b = 3
a *= b
// Result: a = 6.
plot(a)
expr1 / expr2
expr1 /= expr2
//@version=5
indicator("/=")
// Equals to expr1 = expr1 / expr2.
a = 3
b = 3
a /= b
// Result: a = 1.
plot(a)
expr1 % expr2
expr1 %= expr2
//@version=5
indicator("%=")
// Equals to expr1 = expr1 % expr2.
a = 3
b = 3
a %= b
// Result: a = 0.
plot(a)
expr1 + expr2
expr1 += expr2
//@version=5
indicator("+=")
// Equals to expr1 = expr1 + expr2.
a = 2
b = 3
a += b
// Result: a = 5.
plot(a)
expr1 < expr2
expr1 <= expr2
expr1 == expr2
<identifier>([<parameter_name>[=<default_value>]], ...) => <local_block> <function_result>
//@version=5
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
sumChange = ta.change(sum, 10)
// Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))
expr1 > expr2
expr1 >= expr2