Home » Pinescript Syntax » Mastering Variable Declarations in Pine Script

Mastering Variable Declarations in Pine Script

Photo of author
Published on

Introduction

Variables in Pine Script play a pivotal role in data manipulation and storage. Their declaration is an essential first step in leveraging Pine Script’s capabilities, requiring a specific syntax and understanding.

The Syntax of Declaring Variables

Variable declaration in Pine Script adheres to a distinct structure:

[<declaration_mode>] [<type>] <identifier> = <expression> | <structure>

or

<tuple_declaration> = <function_call> | <structure>

Components Explained

  • | signifies an “or” choice.
  • [ ] denotes optional elements.
  • <declaration_mode> can include var, varip, or none.
  • <type> is optional, with Pine Script often inferring it.
  • <identifier> refers to the variable’s name.
  • <expression> could be a literal, variable, another expression, or function call.
  • <structure> encompasses if, for, while, or switch structures.
  • <tuple_declaration> involves declaring multiple variables simultaneously, e.g., [x, y, z].

Examples

// Sample Pine Script code

// Set script properties
//@version=5
indicator("Custom Indicator", shorttitle="CI")

// Color for bullish conditions
BULLISH_COLOR = color.aqua

// Initialize a counter
counterIndex = 0

// User input for a length parameter
movingAverageLength = input(14, "Moving Average Length")

// Assign a float value to a variable
numValue = 9.7

// Round the closing price to the nearest tick
roundedClosePrice = math.round_to_mintick(close)

// Calculate a simple moving average
simpleMA = ta.sma(close, movingAverageLength)

// Declare a variable with an initial 'na' value, to be set later
var highestVolume = float(na)

// Store the opening price of the first bar
var openingPrice = open

// Declare a variable with variable declaration mode 'varip'
varip bool isCloseHigher = na

// Extract values from the MACD indicator
[macdValue, signalValue, histogram] = ta.macd(close, 10, 22, 7)

// Determine the color for plotting based on the closing price
plottingColor =  close > open ? color.green : color.purple


plot(series = macdValue  ,color = plottingColor )
Variable Declarations

Distinguishing Declarations from Reassignments

Recognizing the difference between a variable’s initial declaration (using =) and subsequent reassignment (using :=) is key. Reassignment changes the value of an already declared variable.

Formal Syntax

The comprehensive syntax for variable declaration in Pine Script is:

<variable_declaration>
[<declaration_mode>] [<type>] <identifier> = <expression> | <structure>
|
<tuple_declaration> = <function_call> | <structure>

<declaration_mode>
var | varip

<type>
int | float | bool | color | string | line | linefill | label | box | table | array<type> | matrix<type> | UDF

Initialization with na

Type is usually inferred at compile time in Pine Script, making explicit type declaration a matter of coding style rather than necessity.

Example:

errorLine = na // leads to a compile-time error
num errorMargin = na // valid declaration
toleranceLevel = num(na) // also valid

The first line results in an error because of the ambiguous type of na. The other two lines correctly declare variables with explicit and inferred types.

Tuple Declarations

When dealing with functions or structures that return multiple values, tuple declarations come into play, allowing for the simultaneous declaration of several variables.

Example:

[smaValue, upperLimit, lowerLimit] = ta.sma(close, 10)

Here, ta.sma() is a hypothetical function that returns three values, assigned using a tuple declaration.

Key Takeaways

  • Variable declarations in Pine Script must adhere to a specific syntax, with options for declaration modes and types.
  • Distinguishing between declaration and reassignment is essential.
  • Pine Script performs type inference, but explicit typing can offer more clarity.
  • Tuple declarations are used for assigning multiple values from a function or structure.

Conclusion

Understanding variable declarations is foundational in Pine Script programming. This overview provides the necessary knowledge to begin effectively scripting, laying the groundwork for more advanced Pine Script functionalities.

Leave a Comment