Advanced Pine Script Techniques ๐ง
This chapter covers powerful programming patterns that go beyond the basics. You will learn how to build custom data types, implement efficient data structures, model strategies as state machines, combine signals across multiple timeframes, detect advanced price patterns, and build weighted scoring systems. Every code example here uses correct Pine Script v5 syntax and is designed to compile in TradingView without modification.
Custom User-Defined Types (UDTs)
Pine Script v5 lets you define your own types using the type keyword. A UDT groups related fields into a single object, making your code cleaner and more organized than juggling separate variables.
The type Keyword and Constructors
You declare a type with type TypeName, list its fields with their types, and create instances with TypeName.new().
//@version=5
indicator("UDT Basics", overlay=true)
// Define a custom type
type TradeInfo
float entryPrice = 0.0
int direction = 0 // 1 = long, -1 = short, 0 = flat
float stopLoss = 0.0
float takeProfit = 0.0
float pnl = 0.0
// Create an instance using .new()
var TradeInfo currentTrade = TradeInfo.new()
// Access and modify fields
if ta.crossover(ta.sma(close, 10), ta.sma(close, 50))
currentTrade.entryPrice := close
currentTrade.direction := 1
currentTrade.stopLoss := close - ta.atr(14) * 2
currentTrade.takeProfit := close + ta.atr(14) * 3
// Calculate running P&L when in a trade
if currentTrade.direction != 0
currentTrade.pnl := (close - currentTrade.entryPrice) * currentTrade.direction
plot(currentTrade.pnl, "Trade P&L", color=currentTrade.pnl >= 0 ? color.green : color.red)Key points:
- Fields are listed below the
typedeclaration, each on its own indented line. - Default values are optional but recommended.
- Use
varwhen declaring the instance so it persists across bars instead of being re-created every bar. - Access fields with the dot operator:
currentTrade.entryPrice.
Continue reading
Sign in or create a free account to unlock Advanced Techniques and access the full academy.
Free account ยท No credit card required