Search code examples
pine-scripttradingtradingview-api

How to code this Trading View indicator in Pine Script


How do I code the following for Trading View?

if a bars high - low is greater than 0.05 but less than 0.13 then plot the number 5

if a bars high - low is greater than 0.14 but less than 0.16 then plot the number 4

if a bars high - low is greater than 0.17 but less than 0.22 then plot the number 3

if a bars high - low is greater than 0.23 but less than 0.33 then plot the number 2

if a bars high - low is greater than 0.34 but less than 0.66 then plot the number 1


Solution

  • You can use labels to display your numbers because they will be dynamic.

    //@version=5
    indicator("My script", overlay=true, max_labels_count=500)
    
    diff = high - low
    
    string c = na
    
    if (diff > 0.34) and (diff < 0.66)
        c := "1"
    else if (diff > 0.23) and (diff < 0.33)
        c := "2"
    else if (diff > 0.17) and (diff < 0.22)
        c := "3"
    else if (diff > 0.14) and (diff < 0.16)
        c := "4"
    else if (diff > 0.05) and (diff < 0.13)
        c := "5"
    
    if (not na(c))
        label.new(bar_index, high, c, yloc=yloc.abovebar, style=label.style_none)