0% found this document useful (0 votes)
69 views4 pages

Pine Script: History-Referencing & Functions

The document explains the use of the history-referencing operator in Pine Script to fetch previous bar values, along with examples of calculating simple moving averages using both a for loop and history-referencing. It also covers the creation of single-line and multi-line functions, returning multiple values from functions, and user inputs for creating indicators and strategies. Additionally, it includes details on customizing plot attributes and managing bar gaps in visualizations.

Uploaded by

Khin Yee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views4 pages

Pine Script: History-Referencing & Functions

The document explains the use of the history-referencing operator in Pine Script to fetch previous bar values, along with examples of calculating simple moving averages using both a for loop and history-referencing. It also covers the creation of single-line and multi-line functions, returning multiple values from functions, and user inputs for creating indicators and strategies. Additionally, it includes details on customizing plot attributes and managing bar gaps in visualizations.

Uploaded by

Khin Yee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

History-referencing operator ([])

The history-referencing operator allows you to fetch


previous bar values. The history-referencing is used after
a variable or function call. Inside square brackets, you
have to pass an integer value, which refers to the offset
in the past. For example, if you want to fetch closing price
value two bars in the past, you would use close[2].

The following script calculates a simple moving average


of length three using the history-referencing operator.

//@version=5
indicator("My script")

past_close1 = close[0]
past_close2 = close[1]
past_close3 = close[2]

sma_3 = (past_close1 + past_close2 + past_close3)/3

plot(sma_3)

Switch Statements
color plot_color = switch
high > 176 => [Link]
close > open => [Link]
close < open => [Link]

plot(close, color = plot_color)


For Loop
You should use the for loop when you know the number
of iterations in advance for which you want to execute a
piece of code.

The following script shows how to calculate a simple


moving average of length 10 using a for loop.

//@version=5
indicator("My script")
num_past_bars = 10
sum_10 = 0.0
for i = 0 to num_past_bars - 1
sum_10 := sum_10 + close[i]

sma_10 = sum_10/10

plot(sma_10)
Built-in Variables
[Link]

Single-line Functions
//@version=5
indicator("My script")

close_open_ratio(close_val, open_val, vol_val) => (close_val/open_val) * vol_val

ratio = close_open_ratio(close, open, volume)

plot(ratio)

Multi-line Functions
You can define a function in multiple lines, hence the
multi-line function.

//@version=5
indicator("My script")

close_open_ratio(close_val, open_val, vol_val) =>


ratio = (close_val/open_val) * vol_val
sqrt_ratio = [Link](ratio)
random = [Link]() * sqrt_ratio

ratio = close_open_ratio(close, open, volume)

plot(ratio)
Functions Returning Multiple Values
You can return multiple values from a Pine Script
function. To do so, pass the values to return inside square
brackets and separate them by commas.
Likewise, to receive multiple values from a function, pass
receiving variables inside square brackets and separate
them by commas.

//@version=5
indicator("My script")

close_open_ratio(close_val, open_val, vol_val) =>


ratio = (close_val/open_val) * vol_val
sqrt_ratio = [Link](ratio)
random = [Link]() * sqrt_ratio

[sqrt_ratio, random]

[ratio, random] = close_open_ratio(close, open, volume)

plot(ratio, title = "ratio", color = [Link])


plot(random, title = "random", color = [Link])
Getting User Inputs
Creating Indicators
shorttitle attribute specifies the short title of the plot.
format attribute set format of your plot.
[Link], you will see volume values in K (for
thousands) and M (for millions).
linewidth - width of the line plot
style – change plot style
show_last attribute displays the last N bars for a plot
offset attribute shifts a plot to the right or left. In the
following script, we offset the green close plot by -10,
moving it 10 bars to the left.
//@version=5
indicator("My script", shorttitle = "SPSC")

plot(close, color = [Link], linewidth = 3)


plot(open, color = [Link], style = plot.style_circles, show_last = 20)
plot(close, color = [Link], offset = -10)
[Link]()

barmerge.gaps_off means no gaps are displayed


between bars

Creating Strategies

Common questions

Powered by AI

Single-line functions in Pine Script allow for concise expression but are limited in complexity and number of operations, generally returning a single value efficiently. In contrast, multi-line functions afford greater flexibility in implementing complex calculations, such as those involving multiple operations over several lines, and can handle returning multiple values using square brackets. For example, a multi-line function can calculate a ratio and its square root, as well as a random number derived from that square root, and return these values through [sqrt_ratio, random]. This complexity would be cumbersome or impossible in single-line functions, highlighting the trade-off between simplicity and capability .

The history-referencing operator in Pine Script allows retrieval of previous bar values by specifying an integer offset within square brackets. This capability is crucial for calculating moving averages, as it lets the script access past close prices. For example, to calculate a simple moving average (SMA) of length three, the script first retrieves close values from the present and the past two bars (e.g., close[0], close[1], close[2]) and then averages them. The following script demonstrates this: past_close1 = close[0]; past_close2 = close[1]; past_close3 = close[2]; sma_3 = (past_close1 + past_close2 + past_close3)/3; plot(sma_3).

Switch statements provide a structured and readable approach to handling multiple conditional scenarios in Pine Script. When plotting, using switch statements can simplify the code by encapsulating the logic determining colors outside the plot function, thus making the script easier to read and manage. This separation of logic and action allows for cleaner code, especially when dealing with complex conditions that vary plot appearance, such as color changes based on high and close values as depicted: plot_color = switch high > 176 => color.yellow; close > open => color.green; close < open => color.red. In contrast, embedding conditional logic inside the plot function could lead to cluttered and less maintainable scripts .

Line width and style attributes in Pine Script control the visual presentation of plotted data, significantly impacting the indicator's clarity and user interpretation. The linewidth attribute dictates the thickness of plot lines, ensuring visibility for varying data resolutions, while styles (e.g., plot.style_circles) cater to distinctive visualization needs, enhancing interpretability or highlighting specific data points. These attributes affect how easily users can discern trends, signals, or critical values within large datasets, pivotal for actionable insights in trading strategies. Consequently, they influence user experience and decision-making efficiency, underscoring their importance in indicator design .

In Pine Script, the for loop is an iterative construct used to execute code for a specified number of iterations. When computing a moving average, a for loop can iterate over a specified number of past bars to accumulate their close values, as shown: num_past_bars = 10; sum_10 = 0.0; for i = 0 to num_past_bars - 1 sum_10 := sum_10 + close[i]; sma_10 = sum_10/10; plot(sma_10). This differs from using the history-referencing operator, which accesses specific past values directly without iteration (e.g., close[0], close[1], close[2]). While both methods achieve the same outcome, the for loop is advantageous for more extended computations, but the history-referencing operator offers concise syntax for smaller, fixed-average calculations .

User inputs enhance the customization and interactivity of indicators in Pine Script, allowing users to set parameters that affect the indicator's behavior such as short titles, format, line width, plot style, and offsets. For example, attributes like shorttitle, format.volume, linewidth, and offset help tailor the visualization to suit user preferences or specific analysis needs. A developer might choose to include them to create adaptable tools that accommodate varying user requirements, ensuring broader applicability and greater user engagement with the script, as demonstrated in the script segment: indicator('My script', shorttitle = 'SPSC') plot(close, color = color.green, offset = -10).

The offset attribute in Pine Script's plot function manipulates temporal positioning of the visual representation, shifting it left (negative values) or right (positive values) on the chart. This capacity allows for aligning data with relevant timeframes or compensating for delayed data signals, enhancing interpretive accuracy. For example, offsetting a plot by -10 shifts it 10 bars left, preemptively visualizing data in relation to a key event or timeframe. Such temporal adjustments are crucial when indicators operate or provide signals with inherent delays, helping traders anticipate trends more effectively, improving strategic timing and decision-making .

The close_open_ratio function in Pine Script calculates the ratio of the close to open values multiplied by volume, enhancing analysis of market momentum or volume impacts. In a single-line format, it allows quick calculation with minimal coding, suitable for simple applications needing efficiency: close_open_ratio(close_val, open_val, vol_val) => (close_val/open_val) * vol_val. In a multi-line format, this function gains complexity and depth by including additional calculations, like the square root of the ratio and a random factor: close_open_ratio(close_val, open_val, vol_val) => ratio = (close_val/open_val) * vol_val; sqrt_ratio = math.sqrt(ratio); random = math.random() * sqrt_ratio. This expanded scope accommodates more sophisticated analyses, highlighting trade-offs between simplicity and advanced analytical capabilities .

Returning multiple values from a function in Pine Script is facilitated by passing these values inside square brackets and is interpreted by receiving variables similarly, as in [ratio, random] = close_open_ratio(close, open, volume). This paradigm supports clean and efficient code structures by grouping related values, such as calculations or intermediate results, for succinct return and reusability across scripts. Benefits include enhanced script performance, as calculations are conducted within a single function call, reducing operational overhead, and improved readability, as related outputs remain logically linked, simplifying comprehension and maintenance .

In Pine Script, the request.security function is used to fetch data for a symbol at a specified resolution, integral for strategies that rely on data from multiple sources or resolutions. Utilizing the barmerge.gaps_off option within this function ensures that gaps, which may exist in price data due to differing trading sessions or holidays, are not displayed. This results in a continuous appearance of price bars, which can help maintain the visual integrity of trends in strategies and prevent misleading gaps from affecting the analytical interpretation. This approach is preferred in strategies focusing on seamless data presentation and analysis accuracy .

You might also like