Search code examples
loopsfor-looppine-scripttradingview-apipine-script-v4

loop not breaking in pinescript, tradingview. Need it to stop at first true


i have a if statement and it makes a label every time the condition is true. I would like it to stop when first true and break.

below is my code


//@version=5
indicator("My script", overlay=true)
entry=92.40
current_price=close
price_higher=entry+0.40


CrossedUp = current_price <= price_higher
//CrossedDown = current_price < price_lower   
if CrossedUp
      
    LongBE = label.new(
      x=bar_index, 
      y=na, 
      text="BE Long",
      xloc=xloc.bar_index,
      yloc=yloc.abovebar, 
      color=color.orange, 
      textcolor=color.white, 
      style=label.style_label_down, 
      size=size.tiny)
 

so it is showing a label each time the condition is true, however i just want it to show once?


Solution

  • If you want to show it once, use a var flag to see if the condition has occured before.

    //@version=5
    indicator("My script", overlay=true)
    entry=92.40
    current_price=close
    price_higher=entry+0.40
    var is_label_created = false
    
    CrossedUp = current_price <= price_higher
    //CrossedDown = current_price < price_lower   
    if CrossedUp and not is_label_created
          
        LongBE = label.new(
          x=bar_index, 
          y=na, 
          text="BE Long",
          xloc=xloc.bar_index,
          yloc=yloc.abovebar, 
          color=color.orange, 
          textcolor=color.white, 
          style=label.style_label_down, 
          size=size.tiny)
        
        is_label_created := true