PineScript Coding Tutorial

PineScript Tutorial

Pine can be used for building indicators or fully-automated trading strategies. This tutorial exclusively focuses on coding indicators...PineScript from TradingView is a simple programming language that is specially designed for traders. Pine can be used for building indicators or fully-automated trading strategies. This tutorial exclusively focuses on coding indicators.

 

The Basics of Creating Scripts

 

A script can refer to simple research (Study) or an automated system (Strategy). Both elements (Studies and Strategies) include functions and variables. At the beginning of each script there is a statement declaring the version of PineScript, the name of the script, and whether if it is a Study or a Strategy:

//@version=4

study(title, shorttitle, overlay, format, precision)

This is a short explanation of the above parameters:

  • If used, ‘overlay’ defines where the calculation will be shown on the main chart or below the main chart
  • If used, ‘format’ defines the type of formatting in indicator values. The available values are: format.inherit, format.price and format.volume
  • If used, ‘precision’ states the number of digits after the floating point. It must be a non-negative integer and not greater than 16

At the end of each script there are the instructions to plot the results inside the chart window (overlay=true) or below the chart window:

  • If nothing is stated, scripts are designed to plot calculations below the chart window
  • If you add at the beginning the instruction (overlay=true), calculations will be plotted inside the chart window

 

NAMING VARIABLES

You can create variables anywhere within the script:

  • Can include letters (lower and upper­case), numbers, and underscore ‘_’
  • Variables cannot begin with a number

 

ADDING COMMENTS ON ANY SCRIPT

In order to make the code easier to read, PineScript allows single-line comments. Any text in a line that commences with the symbol ‘//’ is considered to be a comment:

  • // Here is a comment

□ HOTKEY: You can add a comment anytime by pressing ‘Ctr + /’

 

 

Adding Inputs (Changing Variables on Window)

 

Pine allows coders to easily add inputs into their scripts.

  • p = input(50, title="Period")

That means the variable p can be modified, while 50 is the standard setting.

However, you can add other forms of inputs.

choice = input(title="Choice", defval="A", options=["A", "B"])

plot(choice == "A" ? close : choice == "B" ? open : na)

This will offer the option to choose between A (closing price) and B (opening price).

 

INPUT PARAMETERS

You can use the following types of ‘input’:

  • options parameter

choice = input(title="Choice", defval="A", options=["A", "B"])

plot(choice == "A" ? close : choice == "B" ? open : na)

  • bool

b = input(title="On/Off", type=input.bool, defval=true)

plot(b ? open : na)

  • color

c = input(title="Color", type=input.color, defval=color.red)

plot(close, color=c)

  • integer

i = input(title="Offset", type=input.integer, defval=7, minval=-10, maxval=10)

plot(offset(close, i))

  • float

f = input(title="Angle", type=input.float, defval=-0.5, minval=-3.14, maxval=3.14, step=0.2)

plot(sin(f) > 0 ? close : open)

  • string
  • symbol

sym = input(title="Symbol", type=input.symbol, defval="SPY")

res = input(title="Resolution", type=input.resolution, defval="60")

plot(close, color=color.red)

plot(security(sym, res, close), color=color.green)

  • resolution
  • session

s = input(title="Session", type=input.session, defval="24x7")

plot(time(timeframe.period, s))

  • source

src = input(title="Source", type=input.source, defval=close)

ma = sma(src, 9)

plot(ma)

  • time

date = input(title="Date", type=input.time, defval=timestamp("20 Feb 2020 00:00 +0300"))

plot(date)

 

Explaining Operators

 

Logical Operators

You can use the following logical operators:

TRUE & FALSE

PineScript incorporates two built-in constants:

  • true
  • false

END, OR, & NOT

  • not {Negation}
  • and {Logical Conjunction}
  • or {Logical Disjunction}

 

Comparison Operators

There are six comparison operators in PineScript:

  • == Equal
  • != Not Equal
  • <= Less Than or Equal To
  • < Less Than
    • Greater Than
  • >= Greater Than or Equal To

 

Conditional Operators ?, iff & if Statement

You can add a conditional ternary operator by using the function ‘?’.

  • condition ? outcome_1 : outcome_2

If condition is true then the ternary operator will return outcome_1, otherwise it will return outcome_2.

Alternatively, you can use the iff

  • iff(condition, outcome_1, outcome_2)

If the condition is true then it returns outcome_1, otherwise outcome_2.

if Statement

An if statement defines a block of actions to be executed if the if’s conditional expression is TRUE, or an alternative block of actions to be executed when the expression is FALSE.

Example:

<var_declarationX> = if <condition>

    <var_decl_then0>

else if [optional block]

    <var_decl_else0>

    <return_expression_else>

where:

  • var_declarationX — this variable is assigned the value of the if statement as a whole.
  • condition — if the condition expression is TRUE, then the block follows the if first line (var_decl_then0), if the condition is FALSE, the block follows the next (var_decl_else0).
  • return_expression_then, return_expression_else — the last expression will determine the final value of the whole if statement

 

Creating a Loop (for Statement)

The ‘for statement’ executes a number of instructions repeatedly:

Example:

<var_declarationX> = for <i> = <from> to <to> by <step>

    <var_decl0>

    <var_decl1>

    ...

    continue

    ...

    break

    ...

    <var_declN>

    <return_expression>

where:

  • i — a loop counter variable
  • from — start value of the counter
  • to — end value of the counter. When the counter becomes greater than to the loop ends
  • step — default is 1
  • var_decl0, …— body of the loop. It must be indented by 4 spaces [1].
  • return_expression — returning value. When a loop is finished or broken, the returning value is assigned to var_declarationX.
  • continue — a keyword. Can only be used in loops. It jumps to the loop’s next iteration.
  • break — a keyword. Can be used only in loops. It exits the loop.

 

Operator Precedence

The operators’ precedence determines the order of calculations. Operators with greater precedence are calculated first. Below is a list of operators sorted by decreasing precedence:

9     []

8     unary +, unary -, not

7     *, %

6     +, -

5     >, <, >=, <=

4     ==, !=

3     and

2     or

1     ?:

 

The Quant Platform for Advanced Automated Forex Trading...

 

Built-in Elements for Trading Analysis

 

There are several built­in elements for trading analysis, for example:

  • open, high, low, close, volume
  • hl2, hlc3, ohlc4
  • built-in indicators (RSI, SMA, etc.)

 

The [ ] Operator

You can store a sequence of historical values associated with bars by using the [ ] operator.

       h = high[1] // Refers to the previous period ``high`` value

 

‘Barssince’ Function (Conditionally Bars-Counting)

The 'barssince' function returns the bars count since the condition between () was met.

Example:

//@version=4

study("Barssince",overlay=false)

b = barssince(close<close[1])

res = close>close[1] ? b : -1

plot(res, style=plot.style_histogram, color=res >= 0 ? color.red : color.green)

 

ASSET INDEX & SYMBOLS

By rule, a script uses the data of the current chart. However, you can add data of other assets in your script, by using the instruction ‘security’. The instruction ‘security’ allows to set the timeframe ‘D’ but also to choose between open, high, low, and close.

  • Asset2 = security("MSFT", "D", close)

 

TIME

The most basic variables:

  • time — UNIX UTC time of the current bar (in milliseconds)
  • year — Current bar year
  • month — Current bar month
  • weekofyear — Week number of current bar
  • dayofmonth — Date of current bar
  • dayofweek — Day of week for current bar
  • hour — Hour of the current bar start time
  • minute — Minute of the current bar start time
  • second — Second of the current bar start time
  • timenow — Current UNIX time
  • timezone — Exchange timezone of the chart main symbol series

 

Plotting, Locations & Shapes

 

The basic plotting instruction is plot(x):

  • plot(X, color=color.green)

Nevertheless, there are additional instructions printing several shapes on the chart window or on any indicator.

  • plotarrow(X, colorup=teal, colordown=orange, transp=50)
  • plotshape(X, color=color.green)
  • plotchar(X, char='a')

The ‘plotarrow’ prints arrows on the chart. You can separate the color of bullish arrows (colorup=) and bearish arrows (colordown=). There is also the option to set the transparency level (transp=).

The main difference between ‘plotshape’ and ‘plotchar’ is that ‘plotchar’ uses shapes as ASCII symbols (i.e. a, b, c, #, *, etc.).

In the following example, there are two SMAs plotted on the chart (9,21). In addition, there is a red cross (+) printed whenever there is a cross between the two SMAs.

Example:

study("PlottingExample", overlay=true)

src = close

a = sma(src, 9)

b = sma(src, 21)

c = cross(a, b)

plot(a, color=color.green)

plot(b, color=color.blue)

plotshape(c, color=color.red)

The instruction ‘plotshape’ includes additional parameters that set the style of the shape, and the position of the shape (abovebar, belowbar):

  • plotshape(X, style=shape.diamond,

                 location=location.abovebar, color=color.green)

ADDING TEXT ON SHAPES

You can also add text on both ‘plotshape’ and ‘plotchar’.

Example:

study('ADDING TEXT', overlay=true)

Shape = open >= close

plotshape(Shape, location=location.abovebar, text="one\ntwo")

plotchar(not Shape, location=location.belowbar, text="three")

SHIFTING PLOTTED LINES

You can use the ‘offset’ to create a shift when a line is plotted (negative values shift to the left while positive values shift to the right):

Example:

//@version=4

study("Shifting Lines", overlay=true)

plot(close, color=color.green, offset=-2)

plot(close, color=color.red, offset=2)

LOCATIONS

These are the available location parameters:

  • abovebar - above a bar
  • belowbar - below a bar
  • top - top of the script’s y space
  • bottom - bottom of the script’s y space
  • absolute - any position in the y space

SHAPES

There are several different shapes available that you can use along with text or without text:

  • xcross
  • cross
  • circle
  • triangleup
  • triangledown
  • flag
  • arrowup
  • arrowdown
  • square
  • diamond
  • labelup
  • labeldown

 

 

 

Pine Drawings

 

Starting with Pine version 4, you can create drawing objects on the Chart Window, based on certain conditions. If too many drawings are created, the Pine automatically deletes the old drawings to limit the resources needed (garbage collection process).

Example:

 //@version=4

study("My Script", overlay=true)

label.new(bar_index, high, style=label.style_none,

          text="x=" + tostring(bar_index) + "\ny=" + tostring(high))

This will draw a label on each high of each bar indicating x and y coordinates.

 

LABEL TYPES

These are the basic drawing labels:

  • style_none
  • style_xcross
  • style_triangleup
  • style_triangledown
  • style_flag
  • style_circle
  • style_arrowup
  • style_arrowdown
  • style_labelup
  • style_labeldown
  • style_square
  • style_diamond

 

LINES

You can draw a line at a given level using the ‘hline’ annotation:

       hline(0, title="Zero", color=color.gray, linestyle=hline.style_dashed)

 

FILL COLOR BETWEEN PLOT OR LINES

You can fill the background between two plots or hlines with a given color. Note that the fill annotation cannot be used with plot and hline arguments simultaneously.

-FILL BETWEEN PLOTS

p1 = plot(open)

p2 = plot(close)

fill(p1, p2, color=color.green)

-FILL BETWEEN LINES

h1 = hline(20)

h2 = hline(10)

fill(h1, h2, color=color.yellow)

Example:

//@version=4

study("FILL BETWEEN INDICATOR & ZERO LINE")

src = close, len = 10

ma = sma(src, len)

osc = 100 * (ma - src) / ma

p = plot(osc)

fill(p, plot(0))

 

LABEL STYLES

These are the styles that can be applied to lines with either the line.new or line.set_style function:

  • style_solid
  • style_dotted
  • style_dashed
  • style_arrow_left
  • style_arrow_right

 

Pine Colors and Background Colors

 

The bgcolor function modifies the background color. If the script is running in overlay=true mode, then the bgcolor function modifies the chart’s background.

  • bgcolor(sessioncolor, transp=65)

The transp parameter (0–100) allows changing the transparency level.

Color Codes

  • aqua #00BCD4
  • black #363A45
  • blue #2196F3
  • fuchsia #E040FB
  • gray #787B86
  • green #4CAF50
  • lime #00E676
  • maroon #880E4F
  • navy #311B92
  • olive #808000
  • orange #FF9800
  • purple #9C27B0
  • red #FF5252
  • silver #B2B5BE
  • teal #00897B
  • white #FFFFFF
  • yellow #FFEB3B

 

» Visit TradingView and open a free account | » Create PineScript Indicators & Strategies

 

 

PineScript Coding Tutorial

Giorgos Protonotarios, financial analyst,

ForexAutomatic.com (c)

Resources:

TradingView: https://www.tradingview.com/pine-script-docs/en/v4/index.html

Pin It