Home » Pinescript Syntax » Understanding Nested If Statements in Pine Script

Understanding Nested If Statements in Pine Script

Photo of author
Published on

This article will explore the concept of nested if statements in Pine Script by examining a practical example that implements a trading strategy. 

Introduction to Nested If Statements

Nested if statements allow you to evaluate multiple conditions within your Pine Script strategies or indicators. They are essentially “if statements within if statements,” enabling more granular control over your trading logic.


Before delving into the example, let’s clarify the syntax of nested if statements in Pine Script:

if (condition1)
    if (condition2)
        // Action when both condition1 and condition2 are true
        // Action when condition1 is true and condition2 is false
    if (condition3)
        // Action when condition1 is false and condition3 is true
        // Action when condition1 is false and condition3 is false

This structure allows for complex decision-making processes by evaluating conditions in a stepwise manner. Now, with an understanding of the syntax, let’s examine how nested if statements can be utilized in a practical trading strategy.

Example: A Trading Strategy Using Nested If Statements

Let’s dive into an example that illustrates how to use nested if statements within a trading strategy. This strategy calculates a simple moving average (SMA), determines a price target based on current price conditions, and then decides whether to enter long or short positions, or exit positions, based on these calculations.

strategy(title="Advanced Nested If Strategy Example", overlay=true)

// Calculate an SMA
averagePrice = ta.sma(close, 75)

// Plot the moving average on the chart
plot(averagePrice, color=color.green, linewidth=2)

// Calculate profit target
peakHigh = ta.highest(high, 20)[1]
valleyLow = ta.lowest(low, 20)[1]

targetPrice = if close > averagePrice
    peakHigh * 1.005
    valleyLow * 0.995

// When the strategy is not in a position, check for trade entry conditions
if strategy.position_size == 0
    if close > close[10]
        strategy.entry("Long Position", strategy.long)

    if close < close[10]
        strategy.entry("Short Position", strategy.short)

// Check for trade exit conditions
if strategy.position_size != 0
    if strategy.position_size > 0
        strategy.exit("Close Long", limit=targetPrice)

    if strategy.position_size < 0
        strategy.exit("Close Short", limit=targetPrice)

Walkthrough of the Example

  1. Calculation of SMA: The averagePrice variable stores the simple moving average (SMA) of the closing prices over the last 75 periods.
  2. Plotting the SMA: The SMA, now stored in averagePrice, is plotted on the chart with a green line.
  3. Determining the Profit Target: Based on the current price, the script calculates a profit target (targetPrice). If the current close is above the SMA (averagePrice), it sets the target to 0.5% above the highest high of the last 20 periods (peakHigh). Otherwise, it sets the target to 0.5% below the lowest low of the last 20 periods (valleyLow).
  4. Entry Conditions: If there’s no current position (strategy.position_size == 0), the strategy evaluates whether the current close is greater or less than the close 10 periods ago to decide on entering a long or short position.
  5. Exit Conditions: If a position is held, the strategy checks the type of position (long or short) and sets an exit order at the targetPrice calculated earlier.

Key Features and Takeaways

  • Nested If Statements: The core of this strategy lies in its use of nested if statements to make trading decisions based on multiple conditions.
  • Dynamic Profit Targets: By calculating profit targets dynamically based on the SMA and price action, the strategy adapts to changing market conditions.
  • Flexibility in Entry and Exit Conditions: The strategy’s logic for entering and exiting trades demonstrates how nested if statements can be used to implement complex trading logic.

This example illustrates the power of nested if statements in Pine Script, enabling traders and developers to create sophisticated trading strategies on the TradingView platform. By understanding and utilizing these concepts, you can enhance your trading scripts to better align with your trading strategy and market conditions.

Leave a Comment