Drawing Horizontal line dynamically

I am trying to draw two horizontal lines based on previous 5 days' high & low.

The code written is able to draw these two lines for last values.

I want the horizontals lines to be dynamic, by default it should pick the last candle as reference and consider previous 5 candles for calculation of average Low & average High.
=> this is working.

If I put the cursor on a particular candle, that candle should be the reference and 5 prior candles to be taken for calculation of average Low and Average High and horizontal line to be drawn.
=> Please suggest how to achieve this.

SetChartOptions(0,chartShowArrows|chartShowDates);
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

lowavg=(Ref(L,-1)+Ref(L,-2)+Ref(L,-3)+Ref(L,-4)+Ref(L,-5))/5;
highavg=(Ref(h,-1)+Ref(h,-2)+Ref(h,-3)+Ref(h,-4)+Ref(h,-5))/5;

printf("\nLOW AVG="+lowavg);
printf("\nHIGH AVG="+lowavg);

clowavg=LastValue(lowavg);
chighavg=LastValue(highavg);

printf("\nLast LOW AVG="+clowavg);
printf("\nLast HIGH AVG="+chighavg);

Plot(clowavg," ",colorred);
Plot(chighavg," ",coloryellow);

@snbarma this code of yours:

lowavg=(Ref(L,-1)+Ref(L,-2)+Ref(L,-3)+Ref(L,-4)+Ref(L,-5))/5;

is equivalent to:

MAL5 = Ref(MA(L, 5), -1);

So to get the desired result you can experiment a little with SelectedValue() instead of the LastValue():

Plot(SelectedValue(MAL5), "Mal5", colorGreen);

I suggest you to use an exploration to see the values of the calculated arrays to better understand how it works.

2 Likes

Thank you Beppe.

It is the solution I was looking for.

Is it possible to draw dynamic Supp/Res line as shown in the image below?

Res

  1. A fresh line drawn on the price swing resistance- Red Normal line
  2. Price tested the line – Line to be changed as Red Dotted line
  3. Price crossed the line upwards – Resistance become support – Line to be changed as Green Normal line
  4. Price tested the line from above - Line to be changed as Green Dotted line
  5. Price comes back and closed below the line- The line is not valid anymore so entire line should be removed from the chart.

Thank you