Skip to main content
On this page

Pine Script v6 Cheat Sheet: Operators, Functions, and Data Types

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

Pine Script v6 is TradingView's language for indicators, strategies, and libraries. This reference separates syntax, types, and execution behavior. Function names in the tables are lookup entries, not complete executable calls; consult the linked reference for arguments and return types.

If you're wondering what language is Pine Script, it's TradingView's domain-specific scripting language for financial analysis and automated strategies.

The Basic Building Blocks​

The Best Pine Script Generator

Math Operators​

Just basic arithmetic:

SymbolWhat It Does
+Adds numbers (2 + 3 = 5)
-Subtracts numbers (5 - 2 = 3)
*Multiplies numbers (3 * 4 = 12)
/Divides numbers (10 / 2 = 5)
%Returns the remainder (10 % 3 = 1)

Comparison Operators​

SymbolWhat It's Asking
==Are these exactly the same?
!=Are these different?
>Is the first one bigger?
<Is the first one smaller?
>=Is the first one bigger or equal?
<=Is the first one smaller or equal?

Logic Operators​

WordWhat It Means
andBoth things must be true
orAt least one thing must be true
notFlip it: if it was true, make it false
?:Shorthand for "if this, then that, otherwise this other thing"

Assignment Operators​

SymbolWhat It Does
=Declare a variable and assign its initial value
:=Update the value
+=Add to what's already there
-=Subtract from what's already there
*=Multiply what's already there
/=Divide what's already there
%=Store the remainder

Words That Mean Something Special​

The Important Ones​

Pine Script has reserved keywords that do specific things:

WordWhat It Does
importImport an explicitly published Pine library
exportExpose supported declarations from a library
methodDefine a function callable with method notation on its typed first parameter
typeMake your own custom container for data
matrixWork with data in rows and columns (like Excel)
varCreate a variable that remembers its value across bars
varipPreserve assigned state across realtime updates by escaping rollback

Reserved Words (Don't Use These)​

These are set aside for future use:

catch, class, do, ellipse, in, is, polygon, range, return, struct, text, throw, try

Just don't name your variables after any of them and you'll be fine.

How to Store Your Data​

Think of these as different types of containers:

Container TypeWhat It's Like
MatrixA spreadsheet with rows and columns
ArrayA shopping list: items in order
string[]Older way to say "list of text items"
stringA single piece of text

Types of Information You Can Work With​

TypeWhat It HoldsExample
stringText and words"Apple stock is rising"
Integer (int)Whole numbers42, 100, -5
floatNumbers with decimals3.14, 99.9, -0.5
Boolean (bool)True or falsetrue, false
colorColors for your chartsred, blue, custom colors
lineLines you can drawTrend lines, support lines
linefillColored areas between linesShaded regions
boxRectangles on your chartPrice ranges
labelText labels on your chart"Buy here!"
tableOrganized data displayInfo tables

Creating Your Own Data Types​

Sometimes you need to group related information: like a trading setup with entry price, direction, and targets:

PartWhat It IsExample
Basic IdeaGroup related data togetherLike a trading setup with entry price, direction, and signals
How to Make OneUse the type keywordtype MyTradingSetup
What Goes InsideDifferent pieces of related informationPrice levels, trade direction, stop loss
Field defaultsDefaults have restrictions; runtime function calls cannot initialize a field declarationPass a newly created array to the constructor
Creating an instanceUse .new(); copying an existing object is a separate operationMyTradingSetup.new()
Getting Data OutUse a dot to access the informationmySetup.entryPrice

This complete indicator illustrates a user-defined type and constructor. It plots a stored reference price, not a trade signal. The array is created in the constructor call rather than in a field default.

//@version=6
indicator("UDT reference example", overlay = true)
type TradingIdea
float buyPrice = na
string direction = "unassigned"
array<float> targets
var TradingIdea idea = TradingIdea.new(close, "example", array.new<float>())
plot(idea.buyPrice, "Stored reference price")

The first confirmed value persists through var; this example does not update an entry or calculate returns. See the type-system documentation for field defaults and object references.

Variables and Constants​

Pine Script is pretty good at figuring types out on its own:

ConceptWhat It Means
Statically TypedTypes are checked even when an explicit type keyword is omitted
Type InferencePine Script figures it out from what you assign
Immutable TypeOnce determined, the type can't change later

Examples​

What You WriteWhat Pine Script Thinks
price = 100"This is a whole number"
price = 100.50"This is a decimal number"
symbol = "AAPL""This is text"
isRising = true"This is true/false"

Built-in Functions​

Pine Script ships with dozens of pre-built functions so you don't have to code everything from scratch. These are common lookup entries:

Technical Analysis​

What You WantFunctionWhat It Does
RSI indicatorta.rsi()Shows if something is overbought or oversold: learn how to code RSI from scratch
Moving averagesta.sma(), ta.ema()Smooths out price movements: check out this EMA coding guide
Bollinger Bandsta.bb()Shows price channels
Volume analysista.obv, ta.pvtTracks volume patterns
Money flowta.mfi()Price-and-volume oscillator; not a record of investor cash flows

Math Helpers​

What You NeedFunctionWhat It Does
Remove negative signsmath.abs()Makes -5 become 5
Round numbersmath.round()Makes 3.7 become 4
Square rootmath.sqrt()Mathematical square root
Random numbersmath.random()Gives you random values
Find extremesmath.max(), math.min()Finds highest/lowest values

Time and Data​

What You WantFunctionWhat It Does
Bar yearyear(time)Calendar year of the bar timestamp, using the exchange timezone by default
Bar monthmonth(time)Calendar month of the bar timestamp, not necessarily the current wall-clock month
Other market datarequest.security()Gets data from other symbols
Company financialsrequest.financial()Gets fundamental data

Arrays​

What You WantFunctionWhat It Does
Make a new listarray.new<float>()Creates an empty float array when size is omitted
Add to listarray.push()Adds item to the end
Remove from listarray.pop()Takes item from the end
Find somethingarray.indexof()Finds where something is
Sort the listarray.sort()Puts items in order

Matrices​

What You WantFunctionWhat It Does
Make a matrixmatrix.new<float>()Creates a matrix; a chart table is a different object
Put data inmatrix.setAdds a value
Get data outmatrix.getRetrieves a value
Add matrices or a scalarmatrix.sum()Returns element-wise addition; does not reduce all cells to one total
Flip the tablematrix.transposeSwaps rows and columns

Things to Remember​

TopicWhat You Need to Know
Storing DataSingle values are simple. Arrays are lists. Matrices are like spreadsheets.
Custom TypesMust have at least one field. Field defaults cannot contain arbitrary runtime expressions.
FunctionsCan have zero or more parameters. Return the final expression or supported result from their body.
CommentsStart with "//" for notes. Use supported annotations such as "//@variable" for documentation.

Execution details that syntax alone does not show​

  • var preserves state across bars; varip additionally preserves intrabar changes across rollback. Neither keyword causes a strategy to execute on every tick by itself. See variable declarations.
  • A historical offset reads earlier values; it does not request future prices. Multi-timeframe requests need a separate check for confirmation timing and lookahead.
  • Pine v6 changes include lazy and/or evaluation and removal of the na state for booleans. User-defined types, arrays, and var were available before v6. Use the v6 migration guide when converting a script.
  • Check a small reproducible calculation before adding strategy orders. Compilation checks syntax and types; it does not validate a trading hypothesis.
Pineify | Best Pine Script Editor

Website: Pineify

Pineify's visual editor generates Pine Script from supported inputs and conditions. Its Coding Agent can help draft custom logic. Review the resulting code and behavior in TradingView; a generated script still needs the same timing and data checks as handwritten code. See the Visual Pine Script Editor manual.

Primary reference pages​

Use TradingView's v6 reference manual for exact overloads, the time guide for timestamps, the matrices guide for matrix operations, and user-defined functions for parameter and return rules.

Frequently Asked Questions​

What is Pine Script v6 and how is it different from earlier versions?

Pine Script v6 supports indicators, strategies, and libraries. Its migration guide documents behavior changes such as lazy boolean evaluation and booleans no longer accepting na. Types, arrays, and var are not new v6 features; older scripts require migration checks.

How do I use comparison operators in Pine Script v6?

Same as standard math. == for equality, != for inequality, > and < for comparisons, >= and <= for inclusive checks. Combine them with and, or, and not to build multi-condition signals.

Is Pine Script v6 beginner-friendly for traders with no coding experience?

Type inference can reduce explicit declarations, but Pine is statically typed and has a bar-based execution model. If coding's not your thing, Pineify's visual script generator creates indicators through a point-and-click interface without writing code.

How can I create custom data types in Pine Script v6?

Use the type keyword. For example, type TradingIdea groups fields like entry price, direction, and targets into one structure. Instantiate with .new() and access fields with dot notation. Field defaults have restrictions. For a newly created array, pass the array into the constructor instead of calling its constructor in the field declaration.

What built-in functions does Pine Script v6 offer for technical analysis?

Pine Script v6 includes ta.rsi() for RSI, ta.sma() and ta.ema() for moving averages, ta.bb() for Bollinger Bands, ta.obv for volume analysis, and ta.mfi() for money flow. Plus math helpers (math.abs(), math.round(), math.sqrt()) and full array and matrix manipulation libraries.

What words and keywords are reserved in Pine Script v6?

Reserved for future use: catch, class, do, ellipse, in, is, polygon, range, return, struct, text, throw, try. Active keywords you shouldn't use as variable names: import, export, method, type, matrix, var, varip.


If you're curious about other approaches to Pine Script development, check out how AI is changing Pine Script coding and some real Pine Script v6 strategy examples to see what's possible.