# Detecting Divergence - was "Dual looping & plotting"

Hello All,
i have looked and looked and looked for a better divergence code but have always come back with 2 different sets which are available at many places. Unconvinced, i set out to try to make that code my self and looked up for the things required to assemble such code. Am putting down those requisites here.

Elements :-

1. Low array of price
2. High array of Price
3. Rsi(x)
4. ROC(element(H/L/Rsi), n bars)
5. n = current bar(0) upto 100 bars (scan period for ROC)
6. LB = scan the most recent 200 bars

Logic :-
Bullish Divergence : When rate of change of Low of nth bars {ROC(L,n)} is -ve and ROC(RSI(x),n) is +ve; plot trendline from L of nth bar to L of LB bar.
Bearish Divergence : When rate of change of High of n bars {ROC(H,n)} is +ve and ROC(RSI(x),n) is -ve; plot trendline from H of nth bar to H of LB bar.

The above code will loop for every bar from current 0 bar upto user defined bars(200), so as to mark any divergance which may have happened in the past as well. Thus if divergence is being looked for the current bar, the same will be looked for the past as well.

My attempt to code this logic is very raw and am not getting the desired output. Attaching the code below.
Any support is highly appreciated!
TIA, ``````_SECTION_BEGIN("Plot Div");
n = Param("lookback period for ROC",100,2,500,1);
LB = Param("Scan for X bars Back",200,2,500,1);

PlotOHLC( Open,  High,  Low,  Close, "", colorBlack, styleCandle | styleThick  );
RS=RSI(14);

for (i=1;i<(n+1);i++)
{
for(j=0;j<LB;j++)
{
if(j>0)
{
rocl = ROC(Ref(L,-j),i);
roch = ROC(Ref(H,-j),i);
rocr = ROC(Ref(RS,-j),i);
IIf(rocr>0 AND rocl<0, PlotShapes(shapesmallCircle,colorTeal,0,Ref(L,-j),-10),0);
IIf(rocr<0 AND roch>0, PlotShapes(shapesmallCircle,colorPink,0,Ref(H,-j),10),0);
}
if(j==0)
{
rocl = ROC(L,i);
roch = ROC(H,i);
rocr = ROC(RS,i);
IIf(rocr>0 AND rocl<0, PlotShapes(shapesmallCircle,colorTeal,0,L,-10),0);
IIf(rocr<0 AND roch>0, PlotShapes(shapesmallCircle,colorPink,0,H,10),0);
}
}
}
_SECTION_END();
``````

@maxis your post title is very misleading an perhaps the reason you have no answer. I certainly was not interested in reading a post about "dual looping" knowing that loops are not usually needed in AmiBroker.

I can't figure out your code (why all the looping??) and assume it is all wrong. There are many ways to define divergence so there must be many ways to code divergence. Try reviewing some simple codes to get started, start with the an old Official Knowledge Base code

http://www.amibroker.com/kb/index.php?s=divergence

Try reading a couple of Technical Analysis of Stocks and Commodities whose authors look at different ways of measuring divergence,

Comparing slope of regression curves on Price and Momentum,