Triple Threat

Share this post

Learn Pinescript

sonnyparlin.substack.com

Learn Pinescript

A quickstart tutorial for learning Pinescript

Sonny Parlin
Mar 14
Share this post

Learn Pinescript

sonnyparlin.substack.com

TradingView is a popular web-based charting application that is used by traders and investors around the world. The application has gained popularity due to its user-friendly interface, a vast selection of technical analysis tools, and an active community of traders who share ideas and strategies. The platform also allows users to access real-time market data from multiple exchanges, including cryptocurrencies, stocks, forex, and commodities. Additionally, TradingView has integrated social media features, allowing users to follow and interact with other traders, share charts and insights, and collaborate on trading strategies. The platform's popularity has grown rapidly in recent years due to its accessibility, ease of use, and its ability to connect traders and investors from around the world.

One of the standout features of TradingView is its proprietary scripting language, PineScript. PineScript is a powerful scripting language that allows users to create custom indicators and trading strategies that can be applied directly to TradingView charts. This language is relatively easy to learn and offers a range of advanced features that enable traders to create complex trading algorithms. Additionally, TradingView has an extensive library of pre-built indicators and strategies that users can customize and apply to their charts. The integration of PineScript has made TradingView a popular choice for traders and investors who want to develop their own custom indicators and trading algorithms without needing to have extensive coding experience.

Thanks for reading Triple Threat! Subscribe for free to receive new posts and support my work.

Getting Started with PineScript

  1. Create a TradingView account and log in to the platform.

  2. Open the Pine Editor by clicking on the "Pine Editor" icon on the toolbar.

  3. In the Pine Editor, you can create a new script by clicking on "New Script".

Basic Syntax

Here's a simple example of PineScript code:

//@version=5 
study("My First Script", overlay=true) 
plot(close)

This code creates a new study with the name "My First Script" and plots the closing price of the security being charted. Here's a breakdown of the code:

  • //@version=5: This is a versioning comment that specifies the version of PineScript being used.

  • study("My First Script", overlay=true): This creates a new study with the name "My First Script".

  • plot(close): This plots the closing price of the security being charted.

Variables

In PineScript, you can declare variables to store values. Here's an example:

//@version=5 
study("My Second Script", overlay=true) 
var x = 10
plot(x)

This code creates a new study with the name "My Second Script" and declares a variable x with the value of 10. The plot(x) function plots the value of x.

Conditional Statements

You can use conditional statements to control the flow of your PineScript code. Here's an example:

//@version=5 
study("My Third Script", overlay=true) 
var x = 10 
if (x > 5) 
    plot(x)

This code creates a new study with the name "My Third Script" and declares a variable x with the value of 10. The if statement checks if x is greater than 5. If it is, the plot(x) function is called.

Loops

You can also use loops to repeat code. Here's an example:

//@version=5 
study("My Fourth Script", overlay=true) 
var x = 1 
while (x <= 10) 
    plot(x) 
    x := x + 1

This code creates a new study with the name "My Fourth Script" and declares a variable x with the value of 1. The while loop repeats the plot(x) function while x is less than or equal to 10. The x := x + 1 statement increments the value of x by 1 in each iteration.

Indicators

PineScript also allows you to create custom indicators. Here's an example:

//@version=5 
study("My Custom Indicator", overlay=true) 
ma = ta.sma(close, 10) 
plot(ma)

This code creates a new study with the name "My Custom Indicator" and calculates a 10-period simple moving average (SMA) of the closing price. The plot(ma) function plots the SMA on the chart.

Tables

Tables are a useful way to organize and display data in Pine Script 5. The process of creating tables in Pine Script 5 is similar to Pine Script 4, but there are some differences in syntax and function names.

To create a table in Pine Script 5, you can use the table.new() function, which takes two arguments: the number of rows and columns in the table, and an optional argument for the initial cell value.

Here's an example of how to create a simple table with three columns and three rows:

//@version=5 indicator("Table Example") 

// Create a new table with 3 columns and 3 rows 
myTable = table.new(3, 3) 

// Set the width of each column 
table.cellWidth(myTable, 0, 100) 
table.cellWidth(myTable, 1, 100) 
table.cellWidth(myTable, 2, 100) 

// Set the header row values 
table.setHeader(myTable, 0, ["Column 1", "Column 2", "Column 3"]) 

// Set the data values 
table.set(myTable, 1, 0, "Row 1 Column 1") 
table.set(myTable, 1, 1, "Row 1 Column 2") 
table.set(myTable, 1, 2, "Row 1 Column 3") 

table.set(myTable, 2, 0, "Row 2 Column 1") 
table.set(myTable, 2, 1, "Row 2 Column 2") 
table.set(myTable, 2, 2, "Row 2 Column 3") 

// Display the table 
table.draw(myTable)

Let's break down this code step by step:

  1. The indicator() function is used to define the script as an indicator in Pine Script 5.

  2. We create a new table using the table.new() function and store it in the myTable variable. We specify that the table should have three columns and three rows.

  3. We use the table.cellWidth() function to set the width of each column in the table. In this case, we set each column to 100 pixels wide.

  4. We use the table.setHeader() function to set the values of the header row. In this case, we set the header row to display "Column 1", "Column 2", and "Column 3".

  5. We use the table.set() function to set the values of the cells in the table. In this case, we set the cells in rows 1 and 2 to display various strings.

  6. Finally, we use the table.draw() function to display the table on the chart.

You can customize this code to create tables of any size and with any data. You can also use conditional formatting and other formatting options to make your tables more visually appealing.

Arrays

Arrays are a fundamental data structure in Pine Script 5, and they are used to store and manipulate collections of values. To create an array in Pine Script 5, you can use the square bracket notation to define a list of values, or use the array.new() function to create an empty array of a specified length.

Here's an example of how to create an array with five elements:

//@version=5 indicator("Array Example") 

// Define an array with five elements 
myArray = [1, 2, 3, 4, 5] 

// Display the array values 
for i = 0 to 4 
    label.new(bar_index, high[i], tostring(myArray[i]), yloc = yloc.abovebar)

In this example, we define an array myArray with five elements, which are the integers 1 through 5. We then loop through the array using a for loop and display each array element as a label at the high price of the corresponding bar.

Alternatively, we can create an empty array using the array.new() function and then fill the array with values using the array.set() function. Here's an example:

//@version=5 
indicator("Array Example") 

// Create an empty array with five elements 
myArray = array.new_float(5) 

// Set the values of the array 
array.set(myArray, 0, 1.0) 
array.set(myArray, 1, 2.0) 
array.set(myArray, 2, 3.0) 
array.set(myArray, 3, 4.0) 
array.set(myArray, 4, 5.0) 

// Display the array values 
for i = 0 to 4 
    label.new(bar_index, high[i], tostring(array.get(myArray, i)), yloc = yloc.abovebar)

In this example, we create an empty array myArray with five elements using the array.new_float() function. We then use the array.set() function to set the values of each element to the floating point values 1.0 through 5.0. Finally, we loop through the array using a for loop and display each array element as a label at the high price of the corresponding bar.

You can customize these examples to create arrays of any size and with any data type. You can also use various functions and methods to manipulate and analyze arrays, such as array.max(), array.min(), array.sum(), array.sort(), and many others.

Trading Strategies

You can also use PineScript to create custom trading strategies. Here's an example:

//@version=5
// Sample strategy for trading the S&P 500 E Mini futures with plots
// for the moving averages and the stop loss and profit target.
// Try this on the ES1! ticker.

strategy("My Custom Strategy", overlay=true) 
f = input.int(21, "fast moving average", step=1)
s = input.int(50, "slow moving average", step=1)
mafast = ta.sma(close, f) 
maslow = ta.sma(close, s) 
plot(mafast, color=color.green)
plot(maslow, color=color.red)

longCondition = ta.crossover(mafast, maslow) 
shortCondition = ta.crossunder(mafast, maslow)

ptticks=input.int(25, "Profit target ticks", step=1)
stopticks=input.int(11, "Stop Loss ticks", step=1)
ticksize = input.float(.25, "Tick Size", step=0.01)
qty=input.int(5, "Qty", step=1)

var entry = float(na)
var stopLossPrice = float(na)
var ptmet = float(na)

if (longCondition and strategy.opentrades == 0) 
    entry := close
    stopLossPrice := entry-stopticks*ticksize
    ptmet := entry+ptticks*ticksize
    strategy.entry("Long", strategy.long, qty)
    strategy.exit("Long", stop=entry-stopticks*ticksize, limit=entry+ptticks*ticksize)

if (shortCondition and strategy.opentrades == 0)
    entry := close
    stopLossPrice := entry+stopticks
    ptmet := entry-ptticks*ticksize
    strategy.entry("Short", strategy.short, qty)
    strategy.exit("Short", stop=entry+stopticks*ticksize, limit=entry-ptticks*ticksize)

plot(stopLossPrice, color=color.red)
plot(ptmet, color=color.green)
plot(entry, color=color.gray)

This code creates a new strategy with the name "My Custom Strategy" and calculates a moving average (SMA) cross for longs and shorts. The crossover() and crossunder() functions check for the buy and sell signals respectively, based on the crossing of the moving averages. If a buy signal is generated, the strategy.entry() function is used to enter a long position with the label "Long". Similarly, if a sell signal is generated, the strategy.entry() function is used to enter a short position with the label "Short". The strategy.exit() function is used to calculate the stop loss and profit target.

The results from this strategy running from 1/8/2023 to 3/13/2023 are as follows:

The results aren’t that great given the gross loss, but it illustrates how easy it is to create a simple strategy using Pinescript.

In PineScript, you can also use additional built-in functions and operators to build more complex indicators and strategies. Some of the commonly used functions and operators include:

  • ta.ema(): Calculates the exponential moving average of a given period.

  • ta.rsi(): Calculates the relative strength index of a given period.

  • ta.stoch(): Calculates the stochastic oscillator of a given period.

  • ta.roc(): Calculates the rate of change of a given period.

  • and, or, not: Logical operators for combining and negating conditions.

PineScript also provides a large number of built-in variables and constants that you can use in your code. Some of the commonly used variables and constants include:

  • open, high, low, close, volume: The OHLCV data for the security being charted.

  • time: The timestamp of the current bar.

  • bar_index: The index of the current bar.

  • strategy.position_size, strategy.order_size: The current position or order size of the strategy.

  • strategy.opentrades, strategy.closedtrades: The number of open and closed trades for the strategy.

  • strategy.equity, strategy.profit: The current equity and profit/loss for the strategy.

Conclusion

PineScript is a powerful and flexible language for creating custom indicators and trading strategies in TradingView. By understanding the basic syntax, variables, conditional statements, loops, indicators, and trading strategies of PineScript, you can create your own custom tools to analyze and trade the markets.

Thanks for reading Triple Threat! Subscribe for free to receive new posts and support my work.

Share this post

Learn Pinescript

sonnyparlin.substack.com
TopNew

No posts

Ready for more?

© 2023 Sonny Parlin
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing