Can I do this in 1 loop?

 

I am trying to program an indicator that draws the MN Pivot, W1 Pivot and D1 Pivot, (or additional H4 and H1 pivot, if preferred). I want to also look back on the chart to see if the 'pivot confluence' area is valid. (The idea to program this came from the book FOREX Conquered) on any lower time frame. but the pivot lines are all over the place because of the loop parameters used and I am confused as to how to fix this problem.


The pivot line for a particular time frame only works when that time-frame is open. But when looking from a lower time frame because of the for loop, the shift is making lines messy when they should be flat. And seems only valid if your looking at the most current data. (so most current (0) on M30 would show pivot of last D1,W1,MN... but when a new bar emerges on 30M the previous valid pivot becomes in valid because its using pivot from 2 months ago, 2 weeks ago and 2 days ago.. when it should still be looking at the current month because it is only a 30 min bar and falls within the current(0) month & week & day.


For those who still are confused: When I look at the M30 frame and I look back 5 periods on M30 it's showing me MN pivot of 5 months ago, W1 pivot of 5 weeks ago, and D1 pivot of 5 days ago...



Code:


int limit, i, counted_bars=IndicatorCounted();
double PivotD1, PivotW1, PivotMN;
//----

if(counted_bars > 0) limit=Bars-counted_bars;
if(counted_bars < 0) return(0);
if(counted_bars ==0) limit=Bars-1;

for(i = limit - 1; i >= 0; i--){
P1Buffer[i] = PivotD1;
P2Buffer[i] = PivotW1;
P3Buffer[i] = PivotMN;
PivotD1 = iHigh(Symbol(),PERIOD_D1, i)/3 + iLow(Symbol(),PERIOD_D1,i)/3 + iClose(Symbol(),PERIOD_D1,i)/3;
PivotW1 = iHigh(Symbol(),PERIOD_W1,i)/3 + iLow(Symbol(),PERIOD_W1,i)/3 + iClose(Symbol(),PERIOD_W1,i)/3;
PivotMN = iHigh(Symbol(),PERIOD_MN1,i)/3 + iLow(Symbol(),PERIOD_MN1,i)/3 + iClose(Symbol(),PERIOD_MN1,i)/3;


SetPrice("MonthlyPivot", Time[i], PivotMN, Red);
SetText("txtMonthly", "Monthly", Time[i], PivotMN, Red);

SetPrice("WeeklyPivot", Time[i], PivotW1, Red);
SetText("txtWeekly", "Weekly", Time[i], PivotW1, Red);


SetPrice("DailyPivot", Time[i], PivotD1, Red);
SetText("txtDaily", "Daily", Time[i], PivotD1, Red);

}

Reason: