Home » Pinescript Syntax » Understanding the int Type in Pine Script

Understanding the int Type in Pine Script

Photo of author
Published on

In Pine Script version 5, understanding data types is crucial for creating robust and efficient scripts. One of the fundamental data types in Pine Script is the integer type, often referred to as int. This article will delve into the int type, showcasing its utility with a practical example.

What is the int Type?

The int type in Pine Script represents integers, which are whole numbers without any fractional parts. These numbers can be positive, negative, or zero. Integer literals in Pine Script are written using decimal notation, making them straightforward to read and write. Examples of integer literals include:

  • 1
  • -1
  • 750

Using int in Pine Script

Many built-in variables in Pine Script return values of the int type. These include:

  • bar_index: The index of the current bar, starting from 0.
  • time: The opening time of the current bar in milliseconds since Unix epoch.
  • timenow: The current time in milliseconds since Unix epoch.
  • dayofmonth: The day of the month for the current bar.
  • strategy.wintrades: The number of winning trades in the strategy.

These variables are integral to performing various operations in Pine Script, from time-based conditions to indexing and counting.

Example: Utilizing int in a Script

Let’s create a simple script that demonstrates the use of the int type in Pine Script version 5. This script will highlight bars where the dayofmonth is even, showcasing the use of an int type variable in a condition.

indicator("Highlight Even Days", overlay=true)

// Utilizing an int type variable
dayOfMonthEven = dayofmonth % 2 == 0

// Highlighting bars where day of month is even
bgcolor(dayOfMonthEven ? color.new(color.green, 90) : na)

In this script:

  • We declare an indicator using indicator("Highlight Even Days", overlay=true) to ensure our script runs on the chart’s main panel.
  • The variable dayOfMonthEven checks if the day of the month (dayofmonth) is even by using the modulus operator (%). This operation returns an int type value, showcasing the direct application of int types in conditions.
  • The bgcolor function changes the background color of bars where dayOfMonthEven is true, using a green color with transparency set by color.new(color.green, 90).

Key Features and Takeaways

  • Integer Representation: int type variables represent whole numbers in Pine Script, crucial for indexing, time-based operations, and counting.
  • Built-in Variables: Pine Script includes several built-in variables like bar_index, time, timenow, and dayofmonth that return int type values, useful for various scripting needs.
  • Practical Application: The example demonstrates how int types can be used to create conditions and visually modify chart elements based on those conditions.

Leave a Comment