Thinking in Pine - Tricks and Tips of DebuggingWelcome to "Thinking in Pine" short video series on the topics of Pine Script.
Today's discussion point is debugging and tools that Pine script provide us to debug our programs.
🎲 Points Discussed
Debugging using `plot` for numerical series values.
Using Pine Logs to debug for cases where `plot` is not suitable
🎯 Example Program - Debugging using plot
length = input.int(14, 'Length')
multiplier = input.float(4, 'Multiplier')
var dir = 1
var stopDistance = ta.atr(length) * multiplier
// Remove var to fix the first issue
// stopDistance = ta.atr(length) * multiplier
buyStopCurrent = close-stopDistance
sellStopCurrent = close + stopDistance
var buyStop = buyStopCurrent
var sellStop = sellStopCurrent
buyStop := dir > 0? math.max(buyStop, buyStopCurrent) : buyStopCurrent
sellStop := dir < 0? math.min(sellStop, sellStopCurrent) : sellStopCurrent
// Use nz to overcome na issues with math.max/ math.min
// buyStop := dir > 0? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent) : buyStopCurrent
// sellStop := dir < 0? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent) : sellStopCurrent
dir := dir == 1 and close < buyStop? -1 : dir == -1 and close > sellStop ? 1 : dir
// Plot statements used for debugging. display is set to display.data_window as the debugging plots do not need to appear on the charts
plot(stopDistance, 'Stop Distance', color.purple, display = display.data_window)
plot(buyStopCurrent, 'buyStopCurrent', color.red, display = display.data_window)
plot(sellStopCurrent, 'sellStopCurrent', color.green, display = display.data_window)
plot(buyStop, 'buyStop', color.red, display = display.data_window)
plot(sellStop, 'sellStop', color.green, display = display.data_window)
plot(dir, 'Direction', color.white, display = display.data_window)
plot(dir > 0? buyStop : sellStop, 'Supertrend', dir > 0? color.red : color.green)
🎯 Example Program - Pine Logs
sum = 0
arr = array.new()
for i = 0 to 10
sum+=i
// Log on every bar and also on every tick on real time
// log.info('Sum at iteration {0} is {1}', i, sum)
// Run only for the first bar
// if(barstate.isfirst)
// log.info('Sum at iteration {0} is {1}', i, sum)
// Run on the last confirmed bar
// if(barstate.islastconfirmedhistory)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// if(barstate.isrealtime)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// Display only once
// varip showLog = true
// if(barstate.isrealtime and showLog)
// log.warning('Sum at iteration {0} is {1}', i, sum)
// if (i == 10)
// showLog := false
// Extract through the array and log outside the loop
arr.push(sum)
// Log the extracted array on real time and print only once
varip showLog = true
if(barstate.isrealtime and showLog)
log.error('Sum at different iterations : {0}', arr)
showLog := false
plot(sum)
🎲 References
Pine Logs - Reference Manual
plot - Reference Manual