Here is my code:
Period := Input("Period " ,2 ,150 ,60 );
Distance := Input("Distance " ,5 ,100 ,30 );
Start:= DayOfWeek()<>Ref(DayOfWeek(),-1);
Hi := ValueWhen(1,Start, Ref(HighestSince(1,Start,H),-1));
Lo := ValueWhen(1,Start, Ref(LowestSince(1,Start,L),-1));
Clse := ValueWhen(1,Start,Ref(C,-1));
Pivot := (Hi+Lo+Clse)/3;
R1 := 2*Pivot -Lo;
S1 := 2*Pivot -Hi;
R2 := Pivot + (Hi-Lo);
S2 := Pivot - (Hi - Lo);
HiPeriod := HHV(H,Period)+Distance;
LoPeriod := LLV(L,Period)-Distance;
Default :=
If(R1<HiPeriod AND R1>LoPeriod,R1,
If(R2<HiPeriod AND R2>LoPeriod,R2,
If(S1<HiPeriod AND S1>LoPeriod,S1,
If(S2<HiPeriod AND S2>LoPeriod,S2, Pivot
)
)
)
);
HiPeriod := HiPeriod-Distance;
LoPeriod := LoPeriod+Distance;
If(Abs(Pivot- HiPeriod)<Distance,Pivot,Default);
If(Abs(R1- HiPeriod)<Distance OR Abs(R1- LoPeriod)<Distance,R1,Default);
If(Abs(R2- HiPeriod)<Distance OR Abs(R2- LoPeriod)<Distance,R2,Default);
If(Abs(S1- HiPeriod)<Distance OR Abs(S1- LoPeriod)<Distance,S1 ,Default);
If(Abs(S2- HiPeriod)<Distance OR Abs(S2- LoPeriod)<Distance,S2 ,Default);
It is a bit more complicated. Since I do not know what is the current display price range is I ask for a loopback period (variable Period). And I try to find at least a pivot within that range to use as default, If I do not find any and since I can not turn the indicator off I have chosen Pivot as my default value.
The above code is by no means elegant. It is much better to see what is the range of prices currently being displayed and show only relevant pivots.
Disadvantages of the above code so far are:
1- The default pivot could be far off from the current price if the price has been rising or falling significantly compare to yesterday range.
2- As the price moves, the default pivot position might change and you could see lines joining the Pivots gone out of range to the default value.
3- Any other things that you might come up or I can not remember now!