How to Debug Pine Script Code

This video explores various methods we can use to debug our Pine Script code when things aren't going to plan - including how to look inside For Loops.

Check out my other free lessons!

Source Code

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// @version=5
indicator("PineScriptMastery.com", overlay=true)

// Set example chart scale
plot(close, color=color.blue, title="Closing Price")
// hline(20000)

// Create debugging values
float avgVolume = ta.sma(volume, 50)
bool raisedVolume = volume > avgVolume
bgcolor(raisedVolume ? color.new(color.green, 50) : na)

// Displaying debug data in the Data Window:
// Plot works, but preferred option is plotchar (as it will not affect chart scale)
plotchar(avgVolume, "Average Volume", "", color=color.new(color.white,100))
plotchar(volume, "Current Volume", "", color=color.new(color.white,100))

// Debugging inside For Loops using labels
float totalBarSize = 0
int loopLength = input.int(title="Lookback", defval=10)
string debugString = ""

for i = 0 to loopLength - 1
    totalBarSize := totalBarSize + (high[i] - low[i])
    debugString := debugString + "[" + str.tostring(i) + "] totalBarSize=" + str.tostring(totalBarSize) + 
         " barSize=" + str.tostring(high[i] - low[i]) + 
         " h=" + str.tostring(high[i]) + " l=" + str.tostring(low[i]) + "\n"

if barstate.islast
    label.new(bar_index, high, debugString, color=color.black, textcolor=color.white, textalign=text.align_left)

float avgBarSize = totalBarSize / loopLength
plotchar(loopLength, "Lookback Length", "", color=color.new(color.red,100))
plotchar(totalBarSize, "Total Bar Size", "", color=color.new(color.red,100))
plotchar(avgBarSize, "Average Bar Size", "", color=color.new(color.red,100))

// Using a confirm time input to display a debug label on selected bar
int barTime = input.time(title="Select Bar", defval=-1, confirm=true)

if barstate.islast and barTime != -1
    label.new(barTime, high, debugString, color=color.black, textcolor=color.white, textalign=text.align_left, xloc=xloc.bar_time, yloc=yloc.abovebar)

// Custom Function debugging
fn(float test) =>
    test1 = test * 2.5
    test2 = test1 * 4
    [test1, test2]

[customFun1, customFun2] = fn(1.0)
plotchar(customFun1, "Custom Function Number 1", " ")
plotchar(customFun2, "Custom Function Number 2", " ")