Advanced Pine Script Techniques 🔧
Custom Data Structures
Implementing a Queue
//@version=5
indicator("Queue Implementation")
// Create a queue using arrays
var float[] queue = array.new_float(0)
var int maxSize = 100
// Queue operations
enqueue(value) =>
if array.size(queue) >= maxSize
array.shift(queue)
array.push(queue, value)
dequeue() =>
array.size(queue) > 0 ? array.shift(queue) : na
// Usage example
enqueue(close)
lastValue = dequeue()
Creating a Moving Window
//@version=5
indicator("Moving Window")
// Create sliding window
var matrix<float> window = matrix.new<float>(5, 2, 0.0)
// Update window
updateWindow() =>
// Shift data up
for i = 0 to 3
matrix.set(window, i, 0, matrix.get(window, i+1, 0))
matrix.set(window, i, 1, matrix.get(window, i+1, 1))
// Add new data
matrix.set(window, 4, 0, high)
matrix.set(window, 4, 1, low)
Advanced Calculations
Custom Statistical Functions
//@version=5
indicator("Custom Statistics")
// Calculate median
getMedian(float[] data) =>
sorted = array.copy(data)
array.sort(sorted)
size = array.size(sorted)
mid = size / 2
size % 2 == 0 ?
(array.get(sorted, int(mid-1)) + array.get(sorted, int(mid))) / 2 :
array.get(sorted, int(mid))
// Calculate mode
getMode(float[] data) =>
var map = array.new_float(0) // Values
var counts = array.new_int(0) // Counts
for value in data
index = array.indexof(map, value)
if index >= 0
array.set(counts, index, array.get(counts, index) + 1)
else
array.push(map, value)
array.push(counts, 1)
maxCount = array.max(counts)
modeIndex = array.indexof(counts, maxCount)
array.get(map, modeIndex)
Pattern Recognition
Advanced Candlestick Patterns
//@version=5
indicator("Advanced Patterns", overlay=true)
// Engulfing pattern
isEngulfing() =>
bullish = close[1] < open[1] and // Previous red
close > open and // Current green
open <= close[1] and // Opens below prev close
close >= open[1] // Closes above prev open
bearish = close[1] > open[1] and // Previous green
close < open and // Current red
open >= close[1] and // Opens above prev close
close <= open[1] // Closes below prev open
[bullish, bearish]
// Three Line Strike
isThreeLineStrike() =>
// Check for three consecutive candles
threeDown = close[3] < open[3] and
close[2] < open[2] and
close[1] < open[1] and
close[1] < close[2] and
close[2] < close[3]
// Check for reversal candle
reversal = close > open and
close > high[1]
threeDown and reversal
Machine Learning Concepts
Simple Moving Average Convergence
//@version=5
indicator("ML Concepts")
// Feature engineering
calculateFeatures(price, periods) =>
var features = array.new_float(0)
array.clear(features)
// Calculate multiple timeframe features
for period in periods
sma = ta.sma(price, period)
rsi = ta.rsi(price, period)
array.push(features, sma)
array.push(features, rsi)
features
// Simple prediction model
predictDirection(features) =>
weight = 1.0 / array.size(features)
sum = 0.0
for feature in features
sum += feature * weight
sum > close
Memory Management
Efficient Data Storage
//@version=5
indicator("Memory Management")
// Use circular buffer for data storage
var int bufferSize = 100
var float[] buffer = array.new_float(bufferSize, 0.0)
var int currentIndex = 0
// Add data efficiently
addToBuffer(value) =>
array.set(buffer, currentIndex, value)
currentIndex := (currentIndex + 1) % bufferSize
// Clean up old data
cleanBuffer() =>
if array.size(buffer) > bufferSize * 2
newBuffer = array.new_float(bufferSize, 0.0)
for i = 0 to bufferSize - 1
array.set(newBuffer, i, array.get(buffer, i))
buffer := newBuffer
Advanced Error Handling
Robust Error Checking
//@version=5
strategy("Error Handling")
// Custom error type
var string[] errorLog = array.new_string(0)
// Error handling function
handleError(condition, message) =>
if condition
array.push(errorLog, message)
false
else
true
// Usage example
safeCalculation(value) =>
if handleError(na(value), "Invalid input value")
if handleError(value <= 0, "Value must be positive")
math.sqrt(value)
else
na
else
na
Advanced Tips
- Use efficient data structures
- Implement proper error handling
- Optimize calculations for performance
- Document complex algorithms
- Test edge cases thoroughly
Common Pitfalls
❌ Memory leaks in arrays/matrices ❌ Inefficient loops ❌ Unnecessary calculations ❌ Missing error checks ❌ Poor code organization
Next Steps
Ready to learn about creating custom libraries? Move on to the next chapter! 🚀