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
| Name | Description |
|---|---|
AlertFreq | Alert frequency constant for alert. |
Array<T> | An ordered, indexable collection of elements of type T. |
BarmergeGaps | Gap-filling mode for request.*() functions. |
BarmergeLookahead | Lookahead mode for request.*() functions. |
Box | Handle for a box drawing. |
CommissionType | Commission calculation mode for strategy. |
Currency | Currency code (ISO 4217). |
DayOfWeek | Day of the week constant. |
DefaultQtyType | Default quantity mode for strategy. |
Direction | Direction for strategy orders. |
DividendsField | Field selector for request.dividends. |
EarningsField | Field selector for request.earnings. |
Extend | Line extension direction. |
FontFamily | Font family for text drawing. |
Format | Number format for plots and labels. |
Hline | Handle for a horizontal line created by hline. |
HlineStyle | Style of a horizontal line drawing. |
Label | Handle for a label drawing. |
LabelStyle | Style of a label drawing. |
Line | Handle for a line drawing. |
LineStyle | Style of a line drawing. |
Linefill | Handle for a linefill between two lines. |
Location | Vertical 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. |
OcaType | OCA (One-Cancels-All) behavior for strategy orders. |
Plot | Handle for a plot created by plot. |
PlotDisplay | Display options for plots (e.g. |
PlotSimpleDisplay | Controls which price scale and chart the plot is displayed on. |
PlotStyle | Style of a plot series. |
Polyline | Handle for a polyline drawing. |
Position | Table and label position on the chart pane. |
ScaleType | Price scale attachment mode for indicator and strategy. |
Session | Trading session type. |
Shape | Shape drawn by plot_shape. |
Size | Size constant for drawings and labels. |
SortOrder | Sort order for array and matrix operations. |
SplitsField | Field selector for request.splits. |
Table | Handle for a table drawing. |
TextFormat | Text formatting flags (bold, italic). |
TextHAlign | Horizontal text alignment. |
TextVAlign | Vertical text alignment. |
TextWrap | Text wrapping mode. |
Xloc | X-axis coordinate mode for drawings. |
Yloc | Y-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
alert(message: series string, freq: input AlertFreq = AlertFreq.OncePerBar)Creates an alert with the given message and frequency.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
message | series string | ||
freq | input AlertFreq | AlertFreq.OncePerBar |
alert_condition
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
| Name | Type | Default | Description |
|---|---|---|---|
condition | series bool | ||
title | const string | ||
message | const string |
bar_color
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
| Name | Type | Default | Description |
|---|---|---|---|
color | series color | The color to apply to the bar. Use na to keep the default color. | |
offset | simple int | 0 | Shifts the coloring left (negative) or right (positive) by the specified number of bars. |
editable | input bool | true | If true, the setting can be edited in the style dialog. |
show_last | input int | na | If set, only colors the last N bars. |
title | const string | na | Title shown in the style dialog. |
display | input PlotSimpleDisplay | Controls where the coloring is visible. |
bg_color
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
| Name | Type | Default | Description |
|---|---|---|---|
color | series color | The background color. Use na for transparent. | |
offset | simple int | 0 | Shifts the background coloring left (negative) or right (positive) by the specified number of bars. |
editable | input bool | true | If true, the setting can be edited in the style dialog. |
show_last | input int | na | If set, only fills the last N bars. |
title | const string | na | Title shown in the style dialog. |
display | input PlotSimpleDisplay | display.ALL | Controls where the background is visible. |
force_overlay | const bool | na | If true, forces display on the main chart pane. |
bool
Converts the x value to a bool value.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | int |
Returns: bool — false if x is na, false, or an int/float value equal to 0. true for all other values.
box
box(x: Box): BoxCasts na to box type.
Useful for initializing box variables that will be assigned later.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | Box |
Returns: Box
color
color(x: color): colorCasts na to color
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | color |
Returns: color
day_of_month
day_of_month(timestamp: int, timezone: string = syminfo.timezone): intExtracts the day of month (1-31) from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
day_of_week
day_of_week(timestamp: int, timezone: string = syminfo.timezone): DayOfWeekExtracts the day of week from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The 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
| Name | Type | Default | Description |
|---|---|---|---|
hline1 | Hline | The first horizontal line handle (from hline). | |
hline2 | Hline | The second horizontal line handle (from hline). | |
color | series color | color.BLUE | The fill color. |
title | const string | na | Title shown in the style dialog. |
editable | input bool | true | If true, the fill can be edited in the style dialog. |
fill_gaps | const bool | false | If true, fills gaps in the data. |
display | input PlotSimpleDisplay | display.ALL | Controls where the fill is visible. |
fixnan
fixnan(value: series T): series TReplaces 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
| Name | Type | Default | Description |
|---|---|---|---|
value | series T | The 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
| Name | Type | Default | Description |
|---|---|---|---|
x | float |
Returns: float
hline
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
): HlineDraws 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
| Name | Type | Default | Description |
|---|---|---|---|
price | input float | The price level where the line is drawn. | |
title | const string | na | Title shown in the style dialog. |
color | input color | color.BLUE | Line color. |
linestyle | input HlineStyle | HlineStyle.Dashed | Line style: HlineStyle.Solid, HlineStyle.Dashed, HlineStyle.Dotted. |
linewidth | input int | 1 | Width of the line in pixels (1-4). |
editable | input bool | true | If true, the line can be edited in the style dialog. |
display | input PlotSimpleDisplay | display.ALL | Controls where the line is visible. |
Returns: Hline — An hline handle that can be used with fill.
hour
hour(timestamp: int, timezone: string = syminfo.timezone): intExtracts the hour (0-23) from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
indicator
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
| Name | Type | Default | Description |
|---|---|---|---|
title | const string | The 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. | |
shorttitle | const string | na | The script's display name on charts. If specified, it will replace the title argument in most chart-related windows. |
overlay | const bool | false | If 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. |
format | const Format | Format.Inherit | Specifies the formatting of the script's displayed values. Possible values: Format.Inherit, Format.Price, Format.Volume, Format.Percent. Optional. |
precision | const int | na | Specifies 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. |
scale | const ScaleType | na | The 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_back | const int | na | The 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. |
timeframe | const string | na | Adds multi-timeframe functionality to simple scripts. |
timeframe_gaps | const bool | true | Specifies 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_zorder | const bool | false | Specifies 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_count | const int | 50 | The 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_count | const int | 50 | The 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_count | const int | 50 | The 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_count | const int | na | Limits 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_count | const int | 50 | The number of last Polyline drawings displayed. Possible values: 1-100. The count is approximate; more drawings than the specified count may be displayed. |
dynamic_requests | const bool | true | Specifies 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_chart | const bool | true | Controls 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
// RSI indicator in a separate pane
indicator("My RSI", shorttitle: "RSI", overlay: false);
plot(ta.rsi(close, 14), title: "RSI");// 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
| Name | Type | Default | Description |
|---|---|---|---|
defval | const int | ||
title | const string | na | |
tooltip | const string | na | |
inline | const string | na | |
group | const string | na | |
display | const PlotDisplay | display.ALL | |
active | input bool | true |
Returns: input int
int
Casts na to int
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | int |
Returns: int
label
label(x: Label): LabelCasts na to label type.
Useful for initializing label variables that will be assigned later.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | Label |
Returns: Label
library
library(
title: const string,
overlay: const bool = false,
dynamic_requests: const bool = true
)Declaration statement identifying a script as a library.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
title | const string | The 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. | |
overlay | const bool | false | If 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_requests | const bool | true | Specifies 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
line(x: Line): LineCasts na to line type.
Useful for initializing line variables that will be assigned later.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | Line |
Returns: Line
linefill
linefill(x: Linefill): LinefillCasts na to linefill type.
Useful for initializing linefill variables that will be assigned later.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | Linefill |
Returns: Linefill
max_bars_back
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
| Name | Type | Default | Description |
|---|---|---|---|
variable | variableref | ||
num | const int | Maximum number of historical bars. |
minute
minute(timestamp: int, timezone: string = syminfo.timezone): intExtracts the minute (0-59) from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
month
month(timestamp: int, timezone: string = syminfo.timezone): intExtracts the month (1-12) from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
na
na(value: any): boolTests if value is na (not available).
Essential for handling gaps in data, missing values in series, or uninitialized variables.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
value | any | The value to test. Can be any type. |
Returns: bool — true 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
| Name | Type | Default | Description |
|---|---|---|---|
source | T | The value to check. | |
replacement | T | The value to return if source is na. |
Returns: T
plot
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
): PlotPlots a series of data on the chart as a visual representation.
Supports various styles including line, histogram, area, columns, and more.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
series | series float | The series of values to plot. | |
title | const string | na | Title of the plot, shown in the style dialog and as a data window tooltip. |
color | series color | color.BLUE | Color of the plotted element. |
linewidth | input int | 1 | Width of the plotted line, in pixels (1-4). |
style | input PlotStyle | PlotStyle.Line | Plot style: PlotStyle.Line, PlotStyle.Histogram, PlotStyle.Area, PlotStyle.Columns, etc. |
track_price | input bool | false | If true, a horizontal price line is shown at the last value. |
hist_base | input float | 0 | The base value for histogram/columns style. Bars extend from this level to the series value. |
offset | simple int | 0 | Shifts the plot left (negative) or right (positive) by the specified number of bars. |
join | input bool | false | If true, connects gaps in the series with a line. |
editable | input bool | true | If true, the plot style can be edited in the style dialog. |
show_last | input int | na | If set, only the last N bars are displayed. |
display | input PlotDisplay | display.ALL | Controls where the plot is displayed. Use display.ALL, display.NONE, display.PANE, display.PRICE_SCALE, etc. |
format | input Format | na | Overrides the default number format for this plot in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If true, forces the plot to display on the main chart pane. |
linestyle | input PlotStyle | PlotStyle.Line | Line style: PlotStyle.Line, PlotStyle.Stepline, PlotStyle.LineBr. |
Returns: Plot — A plot handle that can be used with fill to fill areas between plots.
Examples
// Plot a simple moving average
let smaLine = plot(ta.sma(close, 20), title: "SMA 20", color: color.BLUE);// 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
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
| Name | Type | Default | Description |
|---|---|---|---|
series | series float | The data series. Positive values draw up arrows, negative draw down arrows. na or zero values draw nothing. | |
title | const string | na | Title shown in the style dialog and data window. |
color_up | series color | color.BLUE | Color of up arrows. |
color_down | series color | color.BLACK | Color of down arrows. |
offset | simple int | 0 | Shifts arrows left (negative) or right (positive) by the specified bars. |
min_height | input int | 5 | Minimum arrow height in pixels. |
max_height | input int | 100 | Maximum arrow height in pixels. |
editable | input bool | true | If true, the plot can be edited in the style dialog. |
show_last | input int | na | If set, only shows arrows on the last N bars. |
display | input PlotDisplay | display.ALL | Controls where arrows are displayed. |
format | input Format | na | Overrides the default number format in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If true, forces display on the main chart pane. |
plot_bar
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
| Name | Type | Default | Description |
|---|---|---|---|
open | series float | The open price for each bar. | |
high | series float | The high price for each bar. | |
low | series float | The low price for each bar. | |
close | series float | The close price for each bar. | |
title | const string | na | Title shown in the style dialog and data window. |
color | series color | color.BLUE | Bar color. |
editable | input bool | true | If true, the plot can be edited in the style dialog. |
show_last | input int | na | If set, only shows the last N bars. |
display | input PlotDisplay | display.ALL | Controls where bars are displayed. |
format | input Format | na | Overrides the default number format in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If true, forces display on the main chart pane. |
plot_candle
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
| Name | Type | Default | Description |
|---|---|---|---|
open | series float | The open price for each candle. | |
high | series float | The high price for each candle. | |
low | series float | The low price for each candle. | |
close | series float | The close price for each candle. | |
title | const string | na | Title shown in the style dialog and data window. |
color | series color | color.BLUE | Candle body color. |
wick_color | series color | color.BLUE | Candle wick color. |
editable | input bool | true | If true, the plot can be edited in the style dialog. |
show_last | input int | na | If set, only shows the last N candles. |
border_color | series color | color.BLACK | Candle body border color. |
display | input PlotDisplay | display.ALL | Controls where candles are displayed. |
format | input Format | na | Overrides the default number format in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If 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
| Name | Type | Default | Description |
|---|---|---|---|
series | series float | The data series. A character is drawn when the value is not na. | |
title | const string | na | Title shown in the style dialog and data window. |
char | input string | "⭐" | The character to display (Unicode supported). |
location | input Location | Location.AboveBar | Vertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute. |
color | series color | color.BLUE | Character color. |
offset | simple int | 0 | Shifts the character left (negative) or right (positive) by bars. |
text | const string | na | Optional text displayed near the character. |
text_color | series color | color.BLUE | Color of the optional text. |
editable | input bool | true | If true, the plot can be edited in the style dialog. |
size | const Size | Size.Auto | Character size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge. |
show_last | input int | na | If set, only shows characters on the last N bars. |
display | input PlotDisplay | display.ALL | Controls where characters are displayed. |
format | input Format | na | Overrides the default number format in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If 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
| Name | Type | Default | Description |
|---|---|---|---|
series | series float | The data series. A shape is drawn when the value is not na. | |
title | const string | na | Title shown in the style dialog and data window. |
style | input Shape | Shape.XCross | Shape 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. |
location | input Location | Location.AboveBar | Vertical position: Location.AboveBar, Location.BelowBar, Location.Top, Location.Bottom, Location.Absolute. |
color | series color | color.BLUE | Shape color. |
offset | simple int | 0 | Shifts the shape left (negative) or right (positive) by bars. |
text | const string | na | Optional text displayed near the shape. |
text_color | series color | color.BLUE | Color of the optional text. |
editable | input bool | true | If true, the plot can be edited in the style dialog. |
size | const Size | Size.Auto | Shape size: Size.Auto, Size.Tiny, Size.Small, Size.Normal, Size.Large, Size.Huge. |
show_last | input int | na | If set, only shows shapes on the last N bars. |
display | input PlotDisplay | display.ALL | Controls where shapes are displayed. |
format | input Format | na | Overrides the default number format in the data window. |
precision | input int | na | Number of decimal places for display. |
force_overlay | const bool | na | If true, forces display on the main chart pane. |
second
second(timestamp: int, timezone: string = syminfo.timezone): intExtracts the second (0-59) from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
strategy
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
| Name | Type | Default | Description |
|---|---|---|---|
title | const string | The title of the script. Displayed on the chart when shorttitle is not set, and becomes the publication's default title when publishing. | |
shorttitle | const string | na | An abbreviated display name for the script shown on the chart and in most chart-related windows. Optional. |
overlay | const bool | false | If 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. |
format | const Format | Format.Inherit | Specifies how the strategy's displayed values are formatted. Possible values: Format.Inherit, Format.Price, Format.Volume, Format.Percent. Optional. |
precision | const int | na | Number 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. |
scale | const ScaleType | na | The price scale to use. Possible values: ScaleType.Right, ScaleType.Left, ScaleType.None. ScaleType.None is only allowed when overlay = true. Optional. |
pyramiding | const int | 0 | The 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_fills | const bool | false | If 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_tick | const bool | false | If 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_back | const int | na | The 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_assumption | const int | 0 | The 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_type | const DefaultQtyType | DefaultQtyType.Fixed | Determines how default_qty_value is interpreted. Possible values: DefaultQtyType.Fixed, DefaultQtyType.PercentOfEquity, DefaultQtyType.Cash. Optional. The default is DefaultQtyType.Fixed. |
default_qty_value | const float | 1 | The 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_capital | const float | 1000000 | The starting capital available to the strategy at the beginning of the backtest, expressed in currency. Optional. The default is 1000000.0. |
currency | simple string | syminfo.currency | The base currency in which the strategy tracks capital, profit, and loss. Optional. Defaults to the chart symbol's currency. |
slippage | const int | 0 | The number of ticks added to each order fill price to simulate execution slippage. Optional. The default is 0. |
commission_type | const CommissionType | CommissionType.Percent | Specifies 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_value | const float | 0 | The commission amount, interpreted according to commission_type. Optional. The default is 0.0. |
process_orders_on_close | const bool | false | If 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_rule | const 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_long | const float | 100 | The 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_short | const float | 100 | The 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_zorder | const bool | false | If 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_count | const int | 50 | The maximum number of recent line drawings kept on the chart. Possible values: 1–500. Optional. The default is 50. |
max_labels_count | const int | 50 | The maximum number of recent label drawings kept on the chart. Possible values: 1–500. Optional. The default is 50. |
max_boxes_count | const int | 50 | The maximum number of recent box drawings kept on the chart. Possible values: 1–500. Optional. The default is 50. |
calc_bars_count | const int | na | Limits 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_rate | const float | 2 | The annual risk-free rate (as a percentage) used when computing the Sharpe and Sortino ratios. Optional. The default is 2.0. |
use_bar_magnifier | const bool | false | If 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_ohlc | const bool | false | If 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_count | const int | 50 | The maximum number of recent polyline drawings kept on the chart. Possible values: 1–100. Optional. The default is 50. |
dynamic_requests | const bool | true | Specifies 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_chart | const bool | true | If 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
string(x: string): stringCasts na to string
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | string |
Returns: string
table
table(x: Table): TableCasts na to table type.
Useful for initializing table variables that will be assigned later.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | Table |
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
| Name | Type | Default | Description |
|---|---|---|---|
timeframe | series string | Timeframe code such as "D", "60", or "W". | |
session | series string | na | Optional session window. When omitted, the symbol's regular session rules are used. |
timezone | series string | syminfo.timezone | Time 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.
time_close
Resolves the closing timestamp of the bar bucket selected by timeframe and session.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timeframe | series string | Timeframe code such as "D", "60", or "W". | |
session | series string | na | Optional session window used during the lookup. |
timezone | series string | syminfo.timezone | Time 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.
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
| Name | Type | Default | Description |
|---|---|---|---|
date_string | string | The date/time string to parse. |
Returns: int
week_of_year
week_of_year(timestamp: int, timezone: string = syminfo.timezone): intExtracts 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
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int
year
year(timestamp: int, timezone: string = syminfo.timezone): intExtracts the year from a UNIX timestamp in the specified timezone.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
timestamp | int | The UNIX timestamp in milliseconds. | |
timezone | string | syminfo.timezone | The timezone for interpretation. Defaults to symbol's timezone. |
Returns: int