TradingView's if/else statement: make code decisions between two options
TradingView’s if/else statement: make code decisions between two options
Section titled “TradingView’s if/else statement: make code decisions between two options”TL;DR
ifevaluates a condition; if it’strue, run one block of code, otherwise run theelseblock. Useelse iffor additional branches.
At a Glance
Section titled “At a Glance”| Difficulty | Beginner |
| Time to implement | 10-15 min |
| Category | Language Basics |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=5indicator("If/Else demo", overlay=false)
priceColor = if close > open color.greenelse if close < open color.redelse color.gray
plot(close, "Close", color=color.new(priceColor, 0))Why It Matters
Section titled “Why It Matters”Whether you’re colouring plots, switching between stop-loss styles, or triggering different orders, branching logic is essential. Without if/else, every bar would follow the same path regardless of market context.
What You’ll Learn
Section titled “What You’ll Learn”- The basic
if/elsestructure and indentation rules. - Nesting and chaining conditions with
else if. - Assigning values from
if/elsestatements for cleaner code. - Practical examples for indicators and strategies.
Quick Reference
Section titled “Quick Reference”| Pattern | Description | Example |
|---|---|---|
| `if condition |
// code` | Run code when condition is true. | `if high > hhbreakout := true` || if ... else | Choose between two blocks. | if isLong strategy.close("Long") else strategy.close("Short") |
| if ... else if ... else | Multiple branches. | if rsi > 70 ... else if rsi < 30 ... else ... |
| Assignment | Capture the value returned by each branch. | color = if trendUp then color.green else color.red |
Implementation Blueprint
Section titled “Implementation Blueprint”-
Start with a simple branch
Evaluate a boolean expression and run one block when it’s true.if close > openlabel.new(bar_index, high, "Bullish") -
Add the alternative path
Useelseto handle the opposite case.if close > openlabel.new(bar_index, high, "Bullish")elselabel.new(bar_index, low, "Bearish") -
Return values directly
Assign the outcome to a variable for later use.direction = if close > open1else-1
Example Playbook
Section titled “Example Playbook”//@version=5indicator("If/Else signal demo", overlay=true)
rsiLen = input.int(14, "RSI length")overbought = input.int(70, "Overbought")oversold = input.int(30, "Oversold")
rsiValue = ta.rsi(close, rsiLen)
signalLabel = if rsiValue > overbought "Sell"else if rsiValue < oversold "Buy"else "Hold"
plot(rsiValue, "RSI", color=color.new(color.blue, 0))hline(overbought, "OB", color=color.new(color.red, 60))hline(oversold, "OS", color=color.new(color.green, 60))
if barstate.islast label.new(bar_index, rsiValue, signalLabel, style=label.style_label_left, textcolor=color.white, bgcolor=signalLabel == "Sell" ? color.new(color.red, 70) : signalLabel == "Buy" ? color.new(color.green, 70) : color.new(color.gray, 70))- `signalLabel` holds a different string for each condition, making it easy to reuse in labels, alerts, or strategy logic.
- Chained `else if` keeps all RSI states in one tidy block.
- Background colours reflect the decision, providing instant visual feedback.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”- Complex logic becomes hard to read quickly—extract repeated expressions into variables or helper functions.
- For “value only” decisions, consider the ternary operator
condition ? value1 : value2to keep code concise. - The
elsebranch is optional; omit it when you only need to act on the true condition. - In strategies, guard against duplicate orders by combining
if/elsewith state flags (var bool inPosition).
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”I get an “Undeclared identifier” error inside else
Section titled “I get an “Undeclared identifier” error inside else”Double-check indentation: if the else block isn’t indented, Pine thinks you’re declaring a new global variable.
How do I skip assignment entirely when a condition is false?
Section titled “How do I skip assignment entirely when a condition is false?”Use na to represent the absence of a value: result = if condition value else na.
Can I nest if statements?
Section titled “Can I nest if statements?”Yes, but keep readability in mind. Often, else if is clearer than nesting multiple if blocks.
Key Takeaways
Section titled “Key Takeaways”if/elseis the primary branching tool in Pine Script, letting you run different code paths per bar.- Keep indentation consistent and leverage assignments to return values directly from conditions.
- Use
else ifand ternaries to handle multiple branches without deeply nested blocks. - Combine with plots, labels, or orders to make decisions visible and actionable.
Keep Going
Section titled “Keep Going”- Open AI Editor to experiment interactively
- Browse How-To Guides to apply control flow in real scripts
- Connect to Live Trading when you’re ready to automate decisions
Adapted from tradingcode.net, optimised for Algo Trade Analytics users.