Skip to main content

Pine Script If Statements: Write Smarter Conditional Logic

· 8 min read
Pineify Team
Pine Script and AI trading workflow research team

You're looking at your TradingView chart and price has just crossed below the 200-day moving average on SPY. You want your indicator to flip from green to red the moment that happens. That's what an if statement does -- it checks a condition and decides what to display or compute next. I've used if statements in nearly every Pine Script I've written, from a simple EMA crossover back in January to a multi-condition strategy for QQQ options in March.

An if statement in Pine Script is a conditional block that executes code only when a specified condition is true. It's the core decision-making tool in any non-trivial script. Without it, your indicator plots the same thing on every bar regardless of what the market is doing.

The Syntax (Straightforward)

if close > open
color = color.green
else
color = color.red

If today's close is higher than the open, the bar turns green. If not, it turns red. Both branches matter here -- if you only handle the true case, the false case stays whatever color was set before, which might not be what you want.

Returning Values from If Blocks

You can assign the result of an if-else directly to a variable:

var result = if close > open
1
else
0

This is useful when you need to track state across bars, like counting consecutive winning days. One gotcha: both branches must return the same data type. I learned this the hard way when I tried returning a string from one branch and an int from the other -- Pine Script threw a type mismatch and I spent 20 minutes hunting it down.

Common Pitfalls (I've Hit All of These)

Indentation. Pine Script uses indentation to define blocks, similar to Python. Always use 4 spaces or a single tab, but never mix them. I prefer 4 spaces because it's what TradingView's own editor inserts by default. If your script compiles but behaves unexpectedly, check indentation first.

Over-nesting. You can nest if statements inside other if statements, but it gets unreadable fast. I try to keep it at three levels max. Beyond that, a switch statement or breaking the logic into separate functions works better.

Missing else branches. If you don't provide an else, the variable keeps its previous value. That's sometimes intentional (for example, holding a signal until it flips), but it's also an easy source of bugs. I've had scripts that showed phantom signals because I forgot the else branch.

Practical Trading Applications

These are the use cases I come back to most often:

  1. Color-coded bars. Change bar color based on whether price is above or below a moving average. It makes reversal points instantly visible.

  2. Strategy entry signals. In a multi-condition strategy, use if with ta.crossover to trigger entries. For example, my RSI+MACD crypto strategy checks both indicators before opening a position.

  3. Conditional plotting. Hide or show plots based on market regime. I have an indicator that only plots resistance lines during trending markets and turns them off during ranges.

If you are just starting out, I recommend working through the Pine Script tutorial for beginners first to get comfortable with the language basics. Then come back here and build a simple if-based script -- something like a bar color indicator that changes when price crosses a moving average. Once you have that running, experiment with else if chains for multiple conditions.

For more advanced projects, the Pineify platform can generate Pine Script code with conditional logic, including multi-condition if blocks, without writing everything by hand. I have not tested every edge case Pineify generates, but it handles standard patterns like EMA crosses and RSI thresholds reliably.

What is an if statement in Pine Script?

An if statement in Pine Script is a conditional block that runs code only when a specific condition is true. It's how you make your script react to price movements -- changing a color, triggering an alert, or deciding to enter a trade when price crosses a level.

How do you write an if-else statement in Pine Script?

Put the condition on one line -- if close > open -- then indent the action below it with 4 spaces or a tab. Add else at the same indent level as if to handle the alternative. If you are assigning the result to a variable, both branches need to return the same data type or Pine Script will refuse to compile.

Can an if statement return a value in Pine Script?

Yes. Assign the if-else block directly to a variable like var result = if close > open / 1 / else / 0. Just make sure both branches return compatible types. I have seen people try to return a string on one side and an int on the other, and that always throws an error.

How does else if work in Pine Script?

Chain multiple conditions using else if. Pine Script checks each condition in order and runs the first matching branch. I try to keep my else-if chains under four conditions -- after that, a switch statement or a separate function is usually cleaner.

Why does Pine Script complain about indentation in if blocks?

Pine Script uses indentation to define blocks, like Python. You need to use exactly 4 spaces or a single tab, and you cannot mix them. Most editors including TradingView's own have a setting to convert Tab to 4 spaces. If your code looks right but throws an error, indentation is the first thing I check.

What practical things can I do with if statements in Pine Script?

Change bar colors when conditions flip, toggle plot visibility depending on market regime, build strategy entry and exit rules, or compute different indicator values when price is above versus below a moving average. Start with one use case and expand from there.