Skip to content

prelude

TIP

The prelude is loaded automatically into every script. Its types and functions are referenced directly by name — do not use a namespace prefix (e.g. write close, not prelude.close).

Types

NameDescription
AlertFreqAlert frequency constant for alert.
Array<T>An ordered, indexable collection of elements of type T.
BarmergeGapsGap-filling mode for request.*() functions.
BarmergeLookaheadLookahead mode for request.*() functions.
BoxHandle for a box drawing.
CommissionTypeCommission calculation mode for strategy.
CurrencyCurrency code (ISO 4217).
DayOfWeekDay of the week constant.
DefaultQtyTypeDefault quantity mode for strategy.
DirectionDirection for strategy orders.
DividendsFieldField selector for request.dividends.
EarningsFieldField selector for request.earnings.
ExtendLine extension direction.
FontFamilyFont family for text drawing.
FormatNumber format for plots and labels.
HlineHandle for a horizontal line created by hline.
HlineStyleStyle of a horizontal line drawing.
LabelHandle for a label drawing.
LabelStyleStyle of a label drawing.
LineHandle for a line drawing.
LineStyleStyle of a line drawing.
LinefillHandle for a linefill between two lines.
LocationVertical location for plot_shape and plot_char.
Map<K, V>A key-value store mapping keys of type K to values of type V.
Matrix<T>A two-dimensional table of elements of type T, stored in row-major order.
OcaTypeOCA (One-Cancels-All) behavior for strategy orders.
PlotHandle for a plot created by plot.
PlotDisplayDisplay options for plots (e.g.
PlotSimpleDisplayControls which price scale and chart the plot is displayed on.
PlotStyleStyle of a plot series.
PolylineHandle for a polyline drawing.
PositionTable and label position on the chart pane.
ScaleTypePrice scale attachment mode for indicator and strategy.
SessionTrading session type.
ShapeShape drawn by plot_shape.
SizeSize constant for drawings and labels.
SortOrderSort order for array and matrix operations.
SplitsFieldField selector for request.splits.
TableHandle for a table drawing.
TextFormatText formatting flags (bold, italic).
TextHAlignHorizontal text alignment.
TextVAlignVertical text alignment.
TextWrapText wrapping mode.
XlocX-axis coordinate mode for drawings.
YlocY-axis coordinate mode for labels.

Properties

ask

Type: series float

Best ask price of the current bar.

The ask price is the lowest price at which a seller is willing to sell. Only available on 1T (tick) timeframes; returns na on all other timeframes.


bar_index

Type: series int

Index of the current bar.

Numbering is zero-based, so the first (oldest) bar on the chart has index 0. The value increases by 1 for each subsequent bar. Use bar_index[1] to reference the previous bar's index.


bid

Type: series float

Best bid price of the current bar.

The bid price is the highest price a buyer is willing to pay. Only available on 1T (tick) timeframes; returns na on all other timeframes.


close

Type: series float

Closing price of the current bar.

On historical bars, this is the last traded price when the bar closed. On real-time bars, this is the current last traded price and will change until the bar closes.


day_of_month

Type: int

Returns the day of month (1-31) of the current bar's opening time in the symbol's timezone.


day_of_week

Type: DayOfWeek

Returns the day of week of the current bar's opening time.


high

Type: series float

Highest price reached during the current bar.

On historical bars, this is the maximum traded price. On real-time bars, this value can increase as new highs are made.


hl2

Type: series float

The midpoint of high and low prices: (high + low) / 2.

Also known as the median price. Useful as a simple estimate of the bar's central price.


hlc3

Type: series float

The typical price: (high + low + close) / 3.

A common price proxy that weights the close equally with the high-low range. Often used in volume weighted calculations.


hlcc4

Type: series float

Weighted close price: (high + low + close + close) / 4.

Places extra weight on the closing price, giving it 50% of the total weight.


hour

Type: int

Returns the hour (0-23) of the current bar's opening time in the symbol's timezone.


last_bar_index

Type: series int

Index of the last (newest) bar on the chart.

Combined with bar_index, this can be used to determine the distance from the current bar to the chart's end, e.g., last_bar_index - bar_index gives bars remaining.


last_bar_time

Type: series int

Timestamp of the last bar on the chart, in UNIX format (milliseconds since 1970-01-01 00:00:00 UTC).

Useful for determining the chart's time range or for time-based calculations relative to the chart end.


low

Type: series float

Lowest price reached during the current bar.

On historical bars, this is the minimum traded price. On real-time bars, this value can decrease as new lows are made.


minute

Type: int

Returns the minute (0-59) of the current bar's opening time in the symbol's timezone.


month

Type: int

Returns the month (1-12) of the current bar's opening time in the symbol's timezone.


ohlc4

Type: series float

Average price: (open + high + low + close) / 4.

The arithmetic mean of all four OHLC prices, representing the bar's overall price activity.


open

Type: series float

Opening price of the current bar.

This is the first traded price when the bar opened. On real-time bars, this value is fixed once the bar opens.


second

Type: int

Returns the second (0-59) of the current bar's opening time in the symbol's timezone.


time

Type: series int

UNIX timestamp for the bar's left edge.

The value is expressed in milliseconds from the Unix epoch and does not drift while the current realtime bar is still forming.


time_close

Type: series int

UNIX timestamp for the bar's right edge.

On time-based charts this is the scheduled close of the active bar.


time_now

Type: series int

Current real-world time in UNIX format (milliseconds since 1970-01-01 00:00:00 UTC).

Unlike time, which returns the bar's time, timenow returns the actual current time and updates continuously on real-time bars.


time_tradingday

Type: series int

Returns a UTC-midnight marker for the exchange session the current bar belongs to.

The result stays identical for all bars that share the same trading session, which is handy when sessions bleed across calendar boundaries.


volume

Type: series float

Trading volume of the current bar.

Represents the total number of shares or contracts traded. May be na if volume data is unavailable for the symbol.


week_of_year

Type: int

Returns the week of year (1-53) of the current bar's opening time in the symbol's timezone.


year

Type: int

Returns the year of the current bar's opening time in the symbol's timezone.

Functions

alert

navi
alert(message: series string, freq: input AlertFreq = AlertFreq.OncePerBar)

Creates an alert with the given message and frequency.

Parameters

NameTypeDefaultDescription
messageseries string
freqinput AlertFreqAlertFreq.OncePerBar

alert_condition

navi
alert_condition(
    condition: series bool,
    title: const string,
    message: const string
  )

Creates an alert condition that can be used to trigger alerts based on a boolean condition.

Parameters

NameTypeDefaultDescription
conditionseries bool
titleconst string
messageconst string

bar_color

navi
bar_color(
    color: series color,
    offset: simple int = 0,
    editable: input bool = true,
    show_last: input int = na,
    title: const string = na,
    display: input PlotSimpleDisplay
  )

Sets the color of price bars on the chart.

Each bar can have its own color, allowing for dynamic coloring based on indicator conditions.

Parameters

NameTypeDefaultDescription
colorseries colorThe color to apply to the bar. Use na to keep the default color.
offsetsimple int0Shifts the coloring left (negative) or right (positive) by the specified number of bars.
editableinput booltrueIf true, the setting can be edited in the style dialog.
show_lastinput intnaIf set, only colors the last N bars.
titleconst stringnaTitle shown in the style dialog.
displayinput PlotSimpleDisplayControls where the coloring is visible.

bg_color

navi
bg_color(
    color: series color,
    offset: simple int = 0,
    editable: input bool = true,
    show_last: input int = na,
    title: const string = na,
    display: input PlotSimpleDisplay = display.ALL,
    force_overlay: const bool = na
  )

Fills the background of chart bars with a specified color.

Useful for highlighting specific conditions or time periods on the chart.

Parameters

NameTypeDefaultDescription
colorseries colorThe background color. Use na for transparent.
offsetsimple int0Shifts the background coloring left (negative) or right (positive) by the specified number of bars.
editableinput booltrueIf true, the setting can be edited in the style dialog.
show_lastinput intnaIf set, only fills the last N bars.
titleconst stringnaTitle shown in the style dialog.
displayinput PlotSimpleDisplaydisplay.ALLControls where the background is visible.
force_overlayconst boolnaIf true, forces display on the main chart pane.

bool

Converts the x value to a bool value.

Parameters

NameTypeDefaultDescription
xint

Returns: boolfalse if x is na, false, or an int/float value equal to 0. true for all other values.

Converts a float to bool; returns false if na or zero, true otherwise.

Parameters

NameTypeDefaultDescription
xfloat

Returns: bool

Converts a bool to bool; returns false if na, otherwise the value.

Parameters

NameTypeDefaultDescription
xbool

Returns: bool

Converts a value of any type to bool; returns false if na, true otherwise.

Parameters

NameTypeDefaultDescription
xT

Returns: bool


box

navi
box(x: Box): Box

Casts na to box type.

Useful for initializing box variables that will be assigned later.

Parameters

NameTypeDefaultDescription
xBox

Returns: Box


color

navi
color(x: color): color

Casts na to color

Parameters

NameTypeDefaultDescription
xcolor

Returns: color


day_of_month

navi
day_of_month(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the day of month (1-31) from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


day_of_week

navi
day_of_week(timestamp: int, timezone: string = syminfo.timezone): DayOfWeek

Extracts the day of week from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: DayOfWeek — 1 (Sunday) through 7 (Saturday).


fill

Fills the area between two horizontal lines with a solid color.

Useful for creating visual zones (e.g., overbought/oversold regions).

Parameters

NameTypeDefaultDescription
hline1HlineThe first horizontal line handle (from hline).
hline2HlineThe second horizontal line handle (from hline).
colorseries colorcolor.BLUEThe fill color.
titleconst stringnaTitle shown in the style dialog.
editableinput booltrueIf true, the fill can be edited in the style dialog.
fill_gapsconst boolfalseIf true, fills gaps in the data.
displayinput PlotSimpleDisplaydisplay.ALLControls where the fill is visible.

Fills the area between two plots with a solid color.

Useful for visualizing the difference or spread between two series.

Parameters

NameTypeDefaultDescription
plot1PlotThe first plot handle (from plot).
plot2PlotThe second plot handle (from plot).
colorseries colorcolor.BLUEThe fill color.
titleconst stringnaTitle shown in the style dialog.
editableinput booltrueIf true, the fill can be edited in the style dialog.
show_lastinput intnaIf set, only fills the last N bars.
fill_gapsconst boolfalseIf true, fills gaps in the data.
displayinput PlotSimpleDisplaydisplay.ALLControls where the fill is visible.

Fills the area between two plots with a vertical gradient.

The gradient transitions from top_color at top_value to bottom_color at bottom_value, creating a smooth color transition based on price levels.

Parameters

NameTypeDefaultDescription
plot1PlotThe first plot handle (from plot).
plot2PlotThe second plot handle (from plot).
top_valueseries floatThe price level where the top color is applied.
bottom_valueseries floatThe price level where the bottom color is applied.
top_colorseries colorcolor.BLUEThe color at the top of the gradient.
bottom_colorseries color#3a3c42The color at the bottom of the gradient.
titleconst stringnaTitle shown in the style dialog.
displayinput PlotSimpleDisplaydisplay.ALLControls where the fill is visible.
fill_gapsconst boolfalseIf true, fills gaps in the data.
editableinput booltrueIf true, the fill can be edited in the style dialog.

fixnan

navi
fixnan(value: series T): series T

Replaces na values with the last non-na value in the series.

Carries forward the most recent valid value, effectively "filling" gaps in the data. If no valid value has been seen yet, returns na. Useful for maintaining continuity in series that have occasional missing values.

Parameters

NameTypeDefaultDescription
valueseries TThe series value to process.

Returns: series T — The current value if it is not na, otherwise the most recent non-na value, or na if no valid value has been seen yet.


float

Casts na to float

Parameters

NameTypeDefaultDescription
xfloat

Returns: float

Converts an int to float.

Parameters

NameTypeDefaultDescription
xint

Returns: float


hline

navi
hline(
    price: input float,
    title: const string = na,
    color: input color = color.BLUE,
    linestyle: input HlineStyle = HlineStyle.Dashed,
    linewidth: input int = 1,
    editable: input bool = true,
    display: input PlotSimpleDisplay = display.ALL
  ): Hline

Draws a horizontal line at a fixed price level across the entire chart.

Unlike plot, the price must be a constant or input value, not a series.

Parameters

NameTypeDefaultDescription
priceinput floatThe price level where the line is drawn.
titleconst stringnaTitle shown in the style dialog.
colorinput colorcolor.BLUELine color.
linestyleinput HlineStyleHlineStyle.DashedLine style: HlineStyle.Solid, HlineStyle.Dashed, HlineStyle.Dotted.
linewidthinput int1Width of the line in pixels (1-4).
editableinput booltrueIf true, the line can be edited in the style dialog.
displayinput PlotSimpleDisplaydisplay.ALLControls where the line is visible.

Returns: Hline — An hline handle that can be used with fill.


hour

navi
hour(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the hour (0-23) from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


indicator

navi
indicator(
    title: const string,
    shorttitle: const string = na,
    overlay: const bool = false,
    format: const Format = Format.Inherit,
    precision: const int = na,
    scale: const ScaleType = na,
    max_bars_back: const int = na,
    timeframe: const string = na,
    timeframe_gaps: const bool = true,
    explicit_plot_zorder: const bool = false,
    max_lines_count: const int = 50,
    max_labels_count: const int = 50,
    max_boxes_count: const int = 50,
    calc_bars_count: const int = na,
    max_polylines_count: const int = 50,
    dynamic_requests: const bool = true,
    behind_chart: const bool = true
  )

Designates the script as an indicator and sets indicator-related properties.

Parameters

NameTypeDefaultDescription
titleconst stringThe title of the script. It is displayed on the chart when no shorttitle argument is used, and becomes the publication's default title when publishing the script.
shorttitleconst stringnaThe script's display name on charts. If specified, it will replace the title argument in most chart-related windows.
overlayconst boolfalseIf true, the script's visuals appear on the main chart pane if the user adds it to the chart directly, or in another script's pane if the user applies it to that script. If false, the script's visuals appear in a separate pane.
formatconst FormatFormat.InheritSpecifies the formatting of the script's displayed values. Possible values: Format.Inherit, Format.Price, Format.Volume, Format.Percent. Optional.
precisionconst intnaSpecifies the number of digits after the floating point of the script's displayed values. Must be a non-negative integer no greater than 16. If format is set to Format.Inherit and precision is specified, the format will instead be set to Format.Price. When the function's format parameter uses Format.Volume, the precision parameter will not affect the result, as the decimal precision rules defined by Format.Volume supersede other precision settings. Optional. The default is inherited from the precision of the chart's symbol.
scaleconst ScaleTypenaThe price scale used. Possible values: ScaleType.Right, ScaleType.Left, ScaleType.None. The ScaleType.None value can only be applied in combination with overlay = true. Optional. By default, the script uses the same scale as the chart. Uses the ScaleType type.
max_bars_backconst intnaThe length of the historical buffer the script keeps for every variable and function, which determines how many past values can be referenced using the [] history-referencing operator.
timeframeconst stringnaAdds multi-timeframe functionality to simple scripts.
timeframe_gapsconst booltrueSpecifies how the indicator's values are displayed on chart bars when the timeframe is higher than the chart's. If true, a value only appears on a chart bar when the higher timeframe value becomes available, otherwise na is returned (thus a "gap" occurs). With false, what would otherwise be gaps are filled with the latest known value returned, avoiding na values. Optional. The default is true.
explicit_plot_zorderconst boolfalseSpecifies the order in which the script's plots, fills, and hlines are rendered. If true, plots are drawn in the order in which they appear in the script's code, each newer plot being drawn above the previous ones. This only applies to plot*() functions, fill, and hline.
max_lines_countconst int50The number of last Line drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed.
max_labels_countconst int50The number of last Label drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed.
max_boxes_countconst int50The number of last Box drawings displayed. Possible values: 1-500. The count is approximate; more drawings than the specified count may be displayed.
calc_bars_countconst intnaLimits the initial calculation of a script to the last number of bars specified. The default is na, in which case the script executes on all available bars.
max_polylines_countconst int50The number of last Polyline drawings displayed. Possible values: 1-100. The count is approximate; more drawings than the specified count may be displayed.
dynamic_requestsconst booltrueSpecifies whether the script can dynamically call functions from the request.*() namespace. Dynamic request.*() calls are allowed within the local scopes of conditional structures (e.g., if), loops (e.g., for), and exported functions. Additionally, such calls allow "series" arguments for many of their parameters.
behind_chartconst booltrueControls whether all plots and drawings appear behind the chart display (if true) or in front of it (if false). This parameter only takes effect when the overlay parameter is true.

Examples

navi
// RSI indicator in a separate pane
indicator("My RSI", shorttitle: "RSI", overlay: false);
plot(ta.rsi(close, 14), title: "RSI");
navi
// Overlay indicator on the price chart
indicator("EMA Cross", overlay: true);
plot(ta.ema(close, 9),  color: color.GREEN);
plot(ta.ema(close, 21), color: color.RED);

input

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst int
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input int

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst float
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input float

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst bool
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input bool

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst color
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input color

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst string
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input string

Creates an input value exposed in the script settings UI.

Parameters

NameTypeDefaultDescription
defvalconst expression
titleconst stringna
tooltipconst stringna
inlineconst stringna
groupconst stringna
displayconst PlotDisplaydisplay.ALL
activeinput booltrue

Returns: input float


int

Casts na to int

Parameters

NameTypeDefaultDescription
xint

Returns: int

Converts a float to int (truncates toward zero via math.floor).

Parameters

NameTypeDefaultDescription
xfloat

Returns: int


label

navi
label(x: Label): Label

Casts na to label type.

Useful for initializing label variables that will be assigned later.

Parameters

NameTypeDefaultDescription
xLabel

Returns: Label


library

navi
library(
    title: const string,
    overlay: const bool = false,
    dynamic_requests: const bool = true
  )

Declaration statement identifying a script as a library.

Parameters

NameTypeDefaultDescription
titleconst stringThe title of the library and its identifier. It cannot contain spaces, special characters or begin with a digit. It is used as the publication's default title, and to uniquely identify the library in the import statement, when another script uses it. It is also used as the script's name on the chart.
overlayconst boolfalseIf true, any visuals produced by the library's exported functions are drawn on the main chart pane. If false, they appear in a separate pane. Optional. The default is false.
dynamic_requestsconst booltrueSpecifies whether the library's exported functions may contain dynamic request.*() calls — i.e., calls placed inside conditional structures or loops, or calls that accept "series" arguments for parameters that normally require a simpler qualifier. Optional. The default is true.

line

navi
line(x: Line): Line

Casts na to line type.

Useful for initializing line variables that will be assigned later.

Parameters

NameTypeDefaultDescription
xLine

Returns: Line


linefill

navi
linefill(x: Linefill): Linefill

Casts na to linefill type.

Useful for initializing linefill variables that will be assigned later.

Parameters

NameTypeDefaultDescription
xLinefill

Returns: Linefill


max_bars_back

navi
max_bars_back(variable: variableref, num: const int)

Sets the maximum number of historical bars available for a specific variable or built-in series via the [] history-referencing operator. If the actual number of bars exceeds the maximum, only the most recent bars will be available.

Parameters

NameTypeDefaultDescription
variablevariableref
numconst intMaximum number of historical bars.

minute

navi
minute(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the minute (0-59) from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


month

navi
month(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the month (1-12) from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


na

navi
na(value: any): bool

Tests if value is na (not available).

Essential for handling gaps in data, missing values in series, or uninitialized variables.

Parameters

NameTypeDefaultDescription
valueanyThe value to test. Can be any type.

Returns: booltrue if the value is undefined or missing, false otherwise.


nz

Replaces na values with a specified replacement.

If source is not na, returns source unchanged. If source is na, returns replacement. Essential for ensuring calculations don't propagate na values.

Parameters

NameTypeDefaultDescription
sourceTThe value to check.
replacementTThe value to return if source is na.

Returns: T

Replaces na integer values with a replacement (default 0).

Useful when you need a numeric fallback for missing integer data.

Parameters

NameTypeDefaultDescription
sourceintThe integer value to check.
replacementint0The value to return if source is na. Defaults to 0.

Returns: int

Replaces na float values with a replacement (default 0.0).

Useful when you need a numeric fallback for missing price or calculation data.

Parameters

NameTypeDefaultDescription
sourcefloatThe float value to check.
replacementfloat0The value to return if source is na. Defaults to 0.0.

Returns: float

Replaces na color values with a replacement (default black).

Useful when you need a visible fallback color for conditional coloring.

Parameters

NameTypeDefaultDescription
sourcecolorThe color value to check.
replacementcolor#000000The value to return if source is na. Defaults to #000000.

Returns: color


plot

navi
plot(
    series: series float,
    title: const string = na,
    color: series color = color.BLUE,
    linewidth: input int = 1,
    style: input PlotStyle = PlotStyle.Line,
    track_price: input bool = false,
    hist_base: input float = 0,
    offset: simple int = 0,
    join: input bool = false,
    editable: input bool = true,
    show_last: input int = na,
    display: input PlotDisplay = display.ALL,
    format: input Format = na,
    precision: input int = na,
    force_overlay: const bool = na,
    linestyle: input PlotStyle = PlotStyle.Line
  ): Plot

Plots a series of data on the chart as a visual representation.

Supports various styles including line, histogram, area, columns, and more.

Parameters

NameTypeDefaultDescription
seriesseries floatThe series of values to plot.
titleconst stringnaTitle of the plot, shown in the style dialog and as a data window tooltip.
colorseries colorcolor.BLUEColor of the plotted element.
linewidthinput int1Width of the plotted line, in pixels (1-4).
styleinput PlotStylePlotStyle.LinePlot style: PlotStyle.Line, PlotStyle.Histogram, PlotStyle.Area, PlotStyle.Columns, etc.
track_priceinput boolfalseIf true, a horizontal price line is shown at the last value.
hist_baseinput float0The base value for histogram/columns style. Bars extend from this level to the series value.
offsetsimple int0Shifts the plot left (negative) or right (positive) by the specified number of bars.
joininput boolfalseIf true, connects gaps in the series with a line.
editableinput booltrueIf true, the plot style can be edited in the style dialog.
show_lastinput intnaIf set, only the last N bars are displayed.
displayinput PlotDisplaydisplay.ALLControls where the plot is displayed. Use display.ALL, display.NONE, display.PANE, display.PRICE_SCALE, etc.
formatinput FormatnaOverrides the default number format for this plot in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces the plot to display on the main chart pane.
linestyleinput PlotStylePlotStyle.LineLine style: PlotStyle.Line, PlotStyle.Stepline, PlotStyle.LineBr.

Returns: Plot — A plot handle that can be used with fill to fill areas between plots.

Examples

navi
// Plot a simple moving average
let smaLine = plot(ta.sma(close, 20), title: "SMA 20", color: color.BLUE);
navi
// Plot two EMAs and fill between them
let p1 = plot(ta.ema(close, 9), title: "EMA 9", color: color.GREEN); let p2 =
plot(ta.ema(close, 21), title: "EMA 21", color: color.RED); fill(p1, p2,
color: color.new(color.GRAY, 80));

plot_arrow

navi
plot_arrow(
    series: series float,
    title: const string = na,
    color_up: series color = color.BLUE,
    color_down: series color = color.BLACK,
    offset: simple int = 0,
    min_height: input int = 5,
    max_height: input int = 100,
    editable: input bool = true,
    show_last: input int = na,
    display: input PlotDisplay = display.ALL,
    format: input Format = na,
    precision: input int = na,
    force_overlay: const bool = na
  )

Plots up and down arrows on the chart based on the sign of the series.

An up arrow is drawn when the value is positive, a down arrow when negative. The arrow height is proportional to the absolute value, scaled between minheight and maxheight. Useful for visualizing momentum or direction changes.

Parameters

NameTypeDefaultDescription
seriesseries floatThe data series. Positive values draw up arrows, negative draw down arrows. na or zero values draw nothing.
titleconst stringnaTitle shown in the style dialog and data window.
color_upseries colorcolor.BLUEColor of up arrows.
color_downseries colorcolor.BLACKColor of down arrows.
offsetsimple int0Shifts arrows left (negative) or right (positive) by the specified bars.
min_heightinput int5Minimum arrow height in pixels.
max_heightinput int100Maximum arrow height in pixels.
editableinput booltrueIf true, the plot can be edited in the style dialog.
show_lastinput intnaIf set, only shows arrows on the last N bars.
displayinput PlotDisplaydisplay.ALLControls where arrows are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

plot_bar

navi
plot_bar(
    open: series float,
    high: series float,
    low: series float,
    close: series float,
    title: const string = na,
    color: series color = color.BLUE,
    editable: input bool = true,
    show_last: input int = na,
    display: input PlotDisplay = display.ALL,
    format: input Format = na,
    precision: input int = na,
    force_overlay: const bool = na
  )

Plots OHLC bars on the chart.

Each bar shows open, high, low, and close prices as a traditional bar chart element. Useful for overlaying custom OHLC data or displaying transformed price data.

Parameters

NameTypeDefaultDescription
openseries floatThe open price for each bar.
highseries floatThe high price for each bar.
lowseries floatThe low price for each bar.
closeseries floatThe close price for each bar.
titleconst stringnaTitle shown in the style dialog and data window.
colorseries colorcolor.BLUEBar color.
editableinput booltrueIf true, the plot can be edited in the style dialog.
show_lastinput intnaIf set, only shows the last N bars.
displayinput PlotDisplaydisplay.ALLControls where bars are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

plot_candle

navi
plot_candle(
    open: series float,
    high: series float,
    low: series float,
    close: series float,
    title: const string = na,
    color: series color = color.BLUE,
    wick_color: series color = color.BLUE,
    editable: input bool = true,
    show_last: input int = na,
    border_color: series color = color.BLACK,
    display: input PlotDisplay = display.ALL,
    format: input Format = na,
    precision: input int = na,
    force_overlay: const bool = na
  )

Plots candlesticks on the chart.

Each candle shows open, high, low, and close prices with a body and wicks. Useful for overlaying custom candlestick data (e.g., Heikin-Ashi) or displaying transformed price series.

Parameters

NameTypeDefaultDescription
openseries floatThe open price for each candle.
highseries floatThe high price for each candle.
lowseries floatThe low price for each candle.
closeseries floatThe close price for each candle.
titleconst stringnaTitle shown in the style dialog and data window.
colorseries colorcolor.BLUECandle body color.
wick_colorseries colorcolor.BLUECandle wick color.
editableinput booltrueIf true, the plot can be edited in the style dialog.
show_lastinput intnaIf set, only shows the last N candles.
border_colorseries colorcolor.BLACKCandle body border color.
displayinput PlotDisplaydisplay.ALLControls where candles are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

plot_char

Plots a character at each bar where the series has a non-na value.

The character is positioned relative to the bar based on location. Useful for marking specific events or conditions on the chart.

Parameters

NameTypeDefaultDescription
seriesseries floatThe data series. A character is drawn when the value is not na.
titleconst stringnaTitle shown in the style dialog and data window.
charinput string"⭐"The character to display (Unicode supported).
locationinput LocationLocation.AboveBarVertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute.
colorseries colorcolor.BLUECharacter color.
offsetsimple int0Shifts the character left (negative) or right (positive) by bars.
textconst stringnaOptional text displayed near the character.
text_colorseries colorcolor.BLUEColor of the optional text.
editableinput booltrueIf true, the plot can be edited in the style dialog.
sizeconst SizeSize.AutoCharacter size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge.
show_lastinput intnaIf set, only shows characters on the last N bars.
displayinput PlotDisplaydisplay.ALLControls where characters are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

Plots a character at each bar where the bool series is true.

A character is drawn when the value is true.

Parameters

NameTypeDefaultDescription
seriesseries boolThe boolean series. A character is drawn when true.
titleconst stringnaTitle shown in the style dialog and data window.
charinput string"⭐"The character to display (Unicode supported).
locationinput LocationLocation.AboveBarVertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute.
colorseries colorcolor.BLUECharacter color.
offsetsimple int0Shifts the character left (negative) or right (positive) by bars.
textconst stringnaOptional text displayed near the character.
text_colorseries colorcolor.BLUEColor of the optional text.
editableinput booltrueIf true, the plot can be edited in the style dialog.
sizeconst SizeSize.AutoCharacter size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge.
show_lastinput intnaIf set, only shows characters on the last N bars.
displayinput PlotDisplaydisplay.ALLControls where characters are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

plot_shape

Plots a shape at each bar where the series has a non-na value.

Various shape styles are available (arrows, circles, crosses, etc.). The shape is positioned relative to the bar based on location.

Parameters

NameTypeDefaultDescription
seriesseries floatThe data series. A shape is drawn when the value is not na.
titleconst stringnaTitle shown in the style dialog and data window.
styleinput ShapeShape.XCrossShape style: Shape.XCross, Shape.Cross, Shape.TriangleUp, Shape.TriangleDown, Shape.Flag, Shape.Circle, Shape.ArrowUp, Shape.ArrowDown, Shape.LabelUp, Shape.LabelDown, Shape.Square, Shape.Diamond.
locationinput LocationLocation.AboveBarVertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute.
colorseries colorcolor.BLUEShape color.
offsetsimple int0Shifts the shape left (negative) or right (positive) by bars.
textconst stringnaOptional text displayed near the shape.
text_colorseries colorcolor.BLUEColor of the optional text.
editableinput booltrueIf true, the plot can be edited in the style dialog.
sizeconst SizeSize.AutoShape size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge.
show_lastinput intnaIf set, only shows shapes on the last N bars.
displayinput PlotDisplaydisplay.ALLControls where shapes are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

Plots a shape at each bar where the bool series is true.

A shape is drawn when the value is true.

Parameters

NameTypeDefaultDescription
seriesseries boolThe boolean series. A shape is drawn when true.
titleconst stringnaTitle shown in the style dialog and data window.
styleinput ShapeShape.XCrossShape style: Shape.XCross, Shape.Cross, Shape.TriangleUp, Shape.TriangleDown, Shape.Flag, Shape.Circle, Shape.ArrowUp, Shape.ArrowDown, Shape.LabelUp, Shape.LabelDown, Shape.Square, Shape.Diamond.
locationinput LocationLocation.AboveBarVertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute.
colorseries colorcolor.BLUEShape color.
offsetsimple int0Shifts the shape left (negative) or right (positive) by bars.
textconst stringnaOptional text displayed near the shape.
text_colorseries colorcolor.BLUEColor of the optional text.
editableinput booltrueIf true, the plot can be edited in the style dialog.
sizeconst SizeSize.AutoShape size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge.
show_lastinput intnaIf set, only shows shapes on the last N bars.
displayinput PlotDisplaydisplay.ALLControls where shapes are displayed.
formatinput FormatnaOverrides the default number format in the data window.
precisioninput intnaNumber of decimal places for display.
force_overlayconst boolnaIf true, forces display on the main chart pane.

second

navi
second(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the second (0-59) from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


strategy

navi
strategy(
    title: const string,
    shorttitle: const string = na,
    overlay: const bool = false,
    format: const Format = Format.Inherit,
    precision: const int = na,
    scale: const ScaleType = na,
    pyramiding: const int = 0,
    calc_on_order_fills: const bool = false,
    calc_on_every_tick: const bool = false,
    max_bars_back: const int = na,
    backtest_fill_limits_assumption: const int = 0,
    default_qty_type: const DefaultQtyType = DefaultQtyType.Fixed,
    default_qty_value: const float = 1,
    initial_capital: const float = 1000000,
    currency: simple string = syminfo.currency,
    slippage: const int = 0,
    commission_type: const CommissionType = CommissionType.Percent,
    commission_value: const float = 0,
    process_orders_on_close: const bool = false,
    close_entries_rule: const string = "FIFO",
    margin_long: const float = 100,
    margin_short: const float = 100,
    explicit_plot_zorder: const bool = false,
    max_lines_count: const int = 50,
    max_labels_count: const int = 50,
    max_boxes_count: const int = 50,
    calc_bars_count: const int = na,
    risk_free_rate: const float = 2,
    use_bar_magnifier: const bool = false,
    fill_orders_on_standard_ohlc: const bool = false,
    max_polylines_count: const int = 50,
    dynamic_requests: const bool = true,
    behind_chart: const bool = true
  )

Designates the script as a strategy and sets strategy-related properties.

Parameters

NameTypeDefaultDescription
titleconst stringThe title of the script. Displayed on the chart when shorttitle is not set, and becomes the publication's default title when publishing.
shorttitleconst stringnaAn abbreviated display name for the script shown on the chart and in most chart-related windows. Optional.
overlayconst boolfalseIf true, the strategy's visuals are drawn on the main chart pane. If false, they appear in a separate pane. Optional. The default is false.
formatconst FormatFormat.InheritSpecifies how the strategy's displayed values are formatted. Possible values: Format.Inherit, Format.Price, Format.Volume, Format.Percent. Optional.
precisionconst intnaNumber of decimal digits shown for the strategy's displayed values. Must be a non-negative integer no greater than 16. When Format.Volume is used, this setting has no effect. Optional. The default is inherited from the chart symbol's precision.
scaleconst ScaleTypenaThe price scale to use. Possible values: ScaleType.Right, ScaleType.Left, ScaleType.None. ScaleType.None is only allowed when overlay = true. Optional.
pyramidingconst int0The maximum number of entries allowed in the same direction at the same time. Optional. The default is 0, meaning only one entry per direction is permitted.
calc_on_order_fillsconst boolfalseIf true, the strategy recalculates its logic whenever an order is filled during a bar, rather than only at bar close. Optional. The default is false.
calc_on_every_tickconst boolfalseIf true, the strategy recalculates on every incoming real-time price update (tick). If false, calculations only occur at bar close. Optional. The default is false.
max_bars_backconst intnaThe depth of the history buffer kept for all variables and functions, controlling how many past values can be read with the [] operator. Optional.
backtest_fill_limits_assumptionconst int0The number of ticks beyond the limit price a market must move before a limit order is assumed to be filled. Optional. The default is 0.
default_qty_typeconst DefaultQtyTypeDefaultQtyType.FixedDetermines how default_qty_value is interpreted. Possible values: DefaultQtyType.Fixed, DefaultQtyType.PercentOfEquity, DefaultQtyType.Cash. Optional. The default is DefaultQtyType.Fixed.
default_qty_valueconst float1The default order size used when no quantity is specified in an entry call. Its meaning depends on default_qty_type. Optional. The default is 1.0.
initial_capitalconst float1000000The starting capital available to the strategy at the beginning of the backtest, expressed in currency. Optional. The default is 1000000.0.
currencysimple stringsyminfo.currencyThe base currency in which the strategy tracks capital, profit, and loss. Optional. Defaults to the chart symbol's currency.
slippageconst int0The number of ticks added to each order fill price to simulate execution slippage. Optional. The default is 0.
commission_typeconst CommissionTypeCommissionType.PercentSpecifies how trading commission is calculated. Possible values: strategy.commission.percent, strategy.commission.cash_per_contract, strategy.commission.cash_per_order. Optional. The default is strategy.commission.percent.
commission_valueconst float0The commission amount, interpreted according to commission_type. Optional. The default is 0.0.
process_orders_on_closeconst boolfalseIf true, orders generated during a bar are processed at that bar's closing price rather than on the opening of the next bar. Optional. The default is false.
close_entries_ruleconst string"FIFO"The sequencing rule applied when closing multiple open entries. "FIFO" closes the oldest entry first; "ANY" allows the close call to target a specific entry by ID. Optional. The default is "FIFO".
margin_longconst float100The margin requirement for long positions, expressed as a percentage of position value. A value of 100 means no leverage. Optional. The default is 100.0.
margin_shortconst float100The margin requirement for short positions, expressed as a percentage of position value. A value of 100 means no leverage. Optional. The default is 100.0.
explicit_plot_zorderconst boolfalseIf true, plots, fills, and hlines are rendered in the order they appear in the script code, with later declarations drawn on top of earlier ones. Optional. The default is false.
max_lines_countconst int50The maximum number of recent line drawings kept on the chart. Possible values: 1–500. Optional. The default is 50.
max_labels_countconst int50The maximum number of recent label drawings kept on the chart. Possible values: 1–500. Optional. The default is 50.
max_boxes_countconst int50The maximum number of recent box drawings kept on the chart. Possible values: 1–500. Optional. The default is 50.
calc_bars_countconst intnaLimits the backtest to the most recent number of bars specified. When na, the strategy runs on all available history. Optional. The default is na.
risk_free_rateconst float2The annual risk-free rate (as a percentage) used when computing the Sharpe and Sortino ratios. Optional. The default is 2.0.
use_bar_magnifierconst boolfalseIf true, the engine uses intrabar data at a finer resolution to determine more accurate order fill prices within each bar. Optional. The default is false.
fill_orders_on_standard_ohlcconst boolfalseIf true, limit and stop orders are filled against the bar's standard OHLC prices, ignoring any intrabar price path. Optional. The default is false.
max_polylines_countconst int50The maximum number of recent polyline drawings kept on the chart. Possible values: 1–100. Optional. The default is 50.
dynamic_requestsconst booltrueSpecifies whether the strategy may contain dynamic request.*() calls inside conditional structures or loops, or calls that accept "series" arguments for normally non-series parameters. Optional. The default is true.
behind_chartconst booltrueIf true, all plots and drawings are rendered behind the chart's candlesticks or bars. Only takes effect when overlay = true. Optional. The default is true.

string

navi
string(x: string): string

Casts na to string

Parameters

NameTypeDefaultDescription
xstring

Returns: string


table

navi
table(x: Table): Table

Casts na to table type.

Useful for initializing table variables that will be assigned later.

Parameters

NameTypeDefaultDescription
xTable

Returns: Table


time

Resolves the opening timestamp of the bar bucket selected by timeframe and session.

This overload is convenient when you want the target session interpreted in a specific time zone.

Parameters

NameTypeDefaultDescription
timeframeseries stringTimeframe code such as "D", "60", or "W".
sessionseries stringnaOptional session window. When omitted, the symbol's regular session rules are used.
timezoneseries stringsyminfo.timezoneTime zone used when evaluating the session string.

Returns: series int — Millisecond timestamp for the matching bar start, or na when the current bar does not belong to the requested session.

Maps the current chart bar to another timeframe and returns that target bar's opening timestamp.

The lookup can be shifted first on the chart timeframe and then again on the target timeframe.

Parameters

NameTypeDefaultDescription
timeframeseries stringDestination timeframe. An empty string falls back to the chart timeframe.
sessionseries stringnaOptional session filter for the destination lookup.
bars_backseries int0Offset applied on the chart timeframe before mapping.
timeframe_bars_backseries int0Extra offset applied after the destination bar is found.

Returns: series int


time_close

Resolves the closing timestamp of the bar bucket selected by timeframe and session.

Parameters

NameTypeDefaultDescription
timeframeseries stringTimeframe code such as "D", "60", or "W".
sessionseries stringnaOptional session window used during the lookup.
timezoneseries stringsyminfo.timezoneTime zone used when interpreting the session string.

Returns: series int — Millisecond timestamp for the matching bar close, or na when the current bar is outside the requested session.

Maps the current chart bar to another timeframe and returns that target bar's closing timestamp.

It uses the same two-stage offset model as time, but reports the bar end instead of the bar start.

Parameters

NameTypeDefaultDescription
timeframeseries stringDestination timeframe. An empty string falls back to the chart timeframe.
sessionseries stringnaOptional session filter for the destination lookup.
bars_backseries int0Offset applied on the chart timeframe before mapping.
timeframe_bars_backseries int0Extra offset applied after the destination bar is found.

Returns: series int


timestamp

Parses a date/time string and returns the corresponding UNIX timestamp in milliseconds.

The string must be in ISO 8601 format (e.g., "2024-01-15" or "2024-01-15T09:30:00Z") or IETF RFC 2822 format.

Parameters

NameTypeDefaultDescription
date_stringstringThe date/time string to parse.

Returns: int

Creates a UNIX timestamp from date/time components using the chart's timezone.

Parameters

NameTypeDefaultDescription
yearintThe year (e.g., 2024).
monthintThe month (1-12).
dayintThe day of month (1-31).
hourint0The hour (0-23). Defaults to 0.
minuteint0The minute (0-59). Defaults to 0.
secondint0The second (0-59). Defaults to 0.

Returns: int — Milliseconds since 1970-01-01 00:00:00 UTC.

Creates a UNIX timestamp from date/time components in a specified timezone.

Parameters

NameTypeDefaultDescription
timezonestringsyminfo.timezoneThe timezone (e.g., "America/New_York", "UTC", "GMT+8").
yearintThe year (e.g., 2024).
monthintThe month (1-12).
dayintThe day of month (1-31).
hourint0The hour (0-23). Defaults to 0.
minuteint0The minute (0-59). Defaults to 0.
secondint0The second (0-59). Defaults to 0.

Returns: int — Milliseconds since 1970-01-01 00:00:00 UTC.


week_of_year

navi
week_of_year(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the week of year (1-53) from a UNIX timestamp in the specified timezone.

Week 1 is the week containing January 4th (ISO 8601).

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int


year

navi
year(timestamp: int, timezone: string = syminfo.timezone): int

Extracts the year from a UNIX timestamp in the specified timezone.

Parameters

NameTypeDefaultDescription
timestampintThe UNIX timestamp in milliseconds.
timezonestringsyminfo.timezoneThe timezone for interpretation. Defaults to symbol's timezone.

Returns: int

Released under the MIT License.