Back to TradingView PineScript for CFD Traders
Part 1

Variables, operators, and comments

Variables, arithmetic, comparisons, logical operators, and how to leave notes for your future self.

Beginner5 min readBeginner → AdvancedLesson 03 / 17
Try it in TradingView
Ternary colouring plus a range filter

The ?: operator picks a colour per bar. Yellow dots mark bars with more than 2x the average range — try changing the multiplier.

//@version=5
indicator("Lesson 3 - Operators", overlay=true)

// Is this bar an up bar?
upBar = close > close[1]

// Ternary: green on up bars, red on down bars.
lineColor = upBar ? color.green : color.red

plot(close, "Close", color=lineColor, linewidth=2)

// Wide bars: range more than 2x the 20-bar average range.
avgRange = ta.sma(high - low, 20)
wideBar  = (high - low) > 2 * avgRange

plotshape(wideBar, "Wide bar", shape.circle, location.abovebar,
          color=color.yellow, size=size.tiny)
To run it
  1. 1. Open any chart in TradingView and click Pine Editor at the bottom.
  2. 2. Select everything in the editor and paste this over it, then click Save.
  3. 3. Click Add to chart. Open the Strategy Tester tab if it is a strategy.

Declaring variables

Pine uses = for assignment. length = 14 creates an integer variable. src = close assigns the close series. Once assigned, you can reuse them anywhere in the script.

Arithmetic and comparison

+, -, *, /, % work as you'd expect. Comparisons: ==, !=, >, <, >=, <=. A single = is assignment; == is comparison.

Logical operators

and, or, not are the keywords (not &&, ||, !). x and y is true only when both are true. not (a > b) is true when the comparison is false.

The ternary operator

Pine has a one-line if/else: condition ? valueIfTrue : valueIfFalse. Example: plot(close > close[1] ? color.green : color.red) paints the line green on up-bars and red on down-bars.

Comments

// starts a single-line comment. /* ... */ is a block comment. Comments are not just for other people — Pine runs them through the chart history too. If a line becomes long, break it across multiple lines and explain why you made the choice you made.

Variable scope

Variables declared at the top level of a script are global. Variables declared inside a function are local. Pine v5 also has var for state that persists across bars (we will use this heavily in Part 3 for entry/exit state).

What you just did

Lesson 03 of 17 in TradingView PineScript for CFD Traders. When you have run the examples or read the section, tick it off and move to the next lesson.