0
votes

In tradingview's pine-script, I am trying to find the previous fractal (HF1), higher than last closing price, and plot the level of HF1

My code so far doesn't really work:

//@version=4
strategy("Fractal Breakout Strategy", overlay=true)

HF = bar_index>5 and high[2]>high[1] and high[2]>high and high[2]>high[3] and high[2]>high[4] ? -1 : 0
LF = bar_index>5 and low[2]<low[1] and low[2]<low and low[2]<low[3] and low[2]<low[4] ? 1 : 0

tot = HF + LF
pl = abs(tot)>=1 ? 1 : 0

//Plot fractal arrows:
plotarrow(pl==1 ? tot : na, colorup=color.teal, colordown=color.orange,offset=-2,maxheight=15)

HF1 = 0.0

for i = 0 to 40
    HF1_temp = valuewhen(HF, high[2],i)
    if (HF1_temp > close[1])
        HF1 := HF1_temp
        break

plot(HF1, color = color.blue)

I suspect it has to do with the last paragraph in the documentation here

To avoid this you may use your own, stateless function implementation. This is the list of built-in functions which have the same behavior:

sma(source, length): length is stateful.

ema(source, length): length is stateful.

sum(source, length): length is stateful.

valuewhen(condition, source, occurrence): occurrence is stateful.

rsi(x, y): when y is of type integer and behaves like a length, y is stateful.

..but can't really figure out how to implement this... Any help will be much appreciated, thanks!

1

1 Answers

1
votes

Your suspicion was correct. Needs to be tested but think this does the job:

//@version=4
strategy("Fractal Breakout Strategy", overlay=true)

ofst = 2
HF = bar_index>5 and high[2]>high[1] and high[2]>high and high[2]>high[3] and high[2]>high[4] ? -1 : 0
LF = bar_index>5 and low[2]<low[1] and low[2]<low and low[2]<low[3] and low[2]<low[4] ? 1 : 0
// Save fractal's hi/lo when we find one, offset `ofst` bars later.
//      This could also be done in the 2 lines above but didn't want to change them 
//      in case you will need their -1 and 1 values elsewhere in your code.
HFval = HF != 0 ? high[ofst] : na
LFval = LF != 0 ? low[ofst] : na

tot = HF + LF
pl = abs(tot)>=1 ? 1 : 0

//Plot fractal arrows:
plotarrow(pl==1 ? tot : na, colorup=color.teal, colordown=color.orange,offset=-ofst,maxheight=15)

float HF1 = na
for i = 0 to 40
    if (HFval[i] > close[1])
        HF1 := HFval[i]
        break

// Plotting circles eliminates the inelegant joins between non `na` values.
plot(HF1, "HF1", color.blue, 2, plot.style_circles)

enter image description here