Rsi divergence plot on chart

please help me regarding this topic i have done ploted the signals in divergence but there are some issue in plotting the line from previous peak to next peak when signal is been generated as shown in picture

plot

_SECTION_BEGIN("RSI Divergence");

SetChartOptions(0,chartShowArrows|chartShowDates);
P = ParamField( "Price field" );
periods = Param("Periods", 14, 1, 200, 1 );

Overbought = 70;
Oversold = 30;
Centre = 50;

Plot(Overbought,"",colorRed);
Plot(Oversold,"",colorGreen);
Plot(Centre,"",colorWhite,styleDashed);

Plot( RSIa( P, periods), _DEFAULT_NAME(), ParamColor( "Color", colorcycle ), ParamStyle("Style")  );

LineWidth = Param("Linewidth", 1, 1,10, 1);
zorder = Param("Zorder", 1, -2, 2, 1);
n=Param("% Reverse ",14,0,100,1);

Buy=Sell=0;
Var = Zig(RSI(), n); 
t= Trough(RSI(), n, 1); 
p= Peak(RSI(), n, 1); 
x[0] =Var[0];
price[0] = C[0];
j=0;

// bearish divergence
for ( i=0; i<BarCount; i++) 
{
if(Var[i] == p[i])
{

j++;
x[j] =Var[i];
price[j] =C[i];
if(x[j] <x[j-1] && price[j-1]< price[j]) 
Sell[i] =1 && y1 = x[j] && y2 = x[j-1];
}
}

// bullish divergence
for ( i=0; i<BarCount; i++) 
{
if(Var[i] == t[i])
{
j++;
x[j] =Var[i];
price[j] =C[i];
if(x[j] >x[j-1] && price[j]<price[j-1]) 
Buy[i] =1;
}
}

/*
//plot line
for ( i=0; i<BarCount; i++) 
{
 if(Sell[i]==1)
{
j++;
y0 = Var[i];
y1 = x[j];
x0 = j;
x1 = x[j-1];

Line1 = LineArray(x0,y0,x1,y1,0,False);

Plot(LINE1,"yes", colorYellow, styleLine | styleNoLabel | styleNoRescale, Null, Null, 0, zorder, Linewidth);
}
else 0;
}
*/

Plot( Var,"peak value", colorBlue, ParamStyle("Style")  );
PlotShapes ( IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0 , Var,Offset =-20);
PlotShapes( IIf(Buy, shapeUpArrow, shapeNone),  colorBrightGreen, 0, Var,Offset =-20);

_SECTION_END();
 
1 Like
SetChartOptions( 0, chartShowArrows | chartShowDates );

P = ParamField( "Price field" );
periods = Param( "Periods", 14, 1, 200, 1 );

Overbought = 70;
Oversold = 30;
Centre = 50;

Plot( Overbought, "", colorRed );
Plot( Oversold, "", colorGreen );
Plot( Centre, "", colorWhite, styleDashed );

Plot( RSIa( P, periods ), _DEFAULT_NAME(), ParamColor( "Color", colorcycle ), ParamStyle( "Style" ) );

n = Param( "% Reverse ", 14, 0, 100, 1 );

Buy = Sell = 0;

bi = BarIndex();

Var = Zig( RSI(), n );
t = Trough( RSI(), n, 1 );
p = Peak( RSI(), n, 1 );

onlywhen = Var == p;
pkPrice = SparseCompress(onlywhen, Close); 
pkRsi = SparseCompress(onlywhen, p);
Sell = pkPrice > Ref(pkPrice, -1) AND pkRsi < Ref(pkRsi, -1);
Sell = SparseExpand(onlywhen, Sell);
Sy0 = SparseExpand(onlywhen, Ref(pkRsi, -1));
Sy1 = SparseExpand(onlywhen, pkRsi);
pkBi = SparseCompress(onlywhen, bi);
Sx0 = SparseExpand(onlywhen, Ref(pkBi, -1));

onlywhen = Var == t;
thPrice = SparseCompress(onlywhen, Close); 
thRsi = SparseCompress(onlywhen, t);
Buy = thPrice < Ref(thPrice, -1) AND thRsi > Ref(thRsi, -1);
Buy = SparseExpand(onlywhen, Buy);
By0 = SparseExpand(onlywhen, Ref(thRsi, -1));
By1 = SparseExpand(onlywhen, thRsi);
thBi = SparseCompress(onlywhen, bi);
Bx0 = SparseExpand(onlywhen, Ref(thBi, -1));

PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorRed, 0 , Var, Offset = -20 );
PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ),  colorBrightGreen, 0, Var, Offset = -20 );

// Plot the Lines
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status( "LastVisibleBar" );

for ( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++ )
{
    if ( Buy[b] )
        Plot( LineArray( Bx0[b], By0[b], b, By1[b] ), "", colorRed, styleThick );
    else if ( Sell[b] )
        Plot( LineArray( Sx0[b], Sy0[b], b, Sy1[b] ), "", colorBlue, styleThick );
}


5 Likes

From Zig help description....

AFL Function Reference - ZIG

Caveat: this function is based on Zig-Zag indicator and may look into the future - this means that you can get unrealistic results when back testing trading system using this indicator.

1 Like

It means that use Zig-Zag indicator for backtesting strategies is nonsense?

@Mactoub, EXACTLY. Don't use Zig Zag in Back test.

2 Likes

Well, you can use it, if you know how..

https://www.amibroker.com/kb/2014/03/06/using-zig-zag-in-trading-systems/

3 Likes

Thank you awilson. The idea is to use ZigZagTrend indicator instead of common ZigZag indicator in BackTest?

The idea is to understand how any indicator works so before you go real trade you know that you are trading something that is real

1 Like

Thank you for answer. Do you have please working RSI Divergence strategy, which is useable for Back testing?

Define what do you mean by

Any indicator, even ones that look into the future , can work if you introduce delays acting after it is fixed and no longer see in the future. The problem is that when you do this, it does not make any profit that compensates the risk

3 Likes

I mean RSI divergence strategy without any "look in the future" and more realistic result.

If you use the technique @Tomasz used in the link below with my code above you will get what you want

http://www.amibroker.com/members/traders/11-2003.html

Thank you I will try...

I have try this code on realtime data, I scanned divergences on stocks, unfortunately there is same problem like most of divergences code using Zig. Open signals appear couple of candles back....

I am using this code for RSI Divergence, while scanning Buy signals are giving 1 bar delay. When I scanned on 18.03.2021 with date range 18.03.2021 to 18.03.2021, there was no buy signals. When I scanned on 19.03.2021 with date range 18.03.2021 to 19.03.2021, there are buy signals for 18.03.2021. Am I missing something?

I'm assuming you're using EOD data?
I suspect you would need two or more data points (for each of both the price and RSI) to denote a divergence.

Yes, I am using EOD data only. While scanning, giving the date range as todays date only.

nice coding @awilson. I never used SparseCompress/SparseExpand before, pretty handy.

I made a version that uses the price as the main array and RSI as confirmation. Then you can drag it on top of a price chart. Also I added the "hidden" divergence. Also I added lines at the price where the divergence line is confirmed. I have set the percentage n to 0.5% as default which gives a bunch of signals in 5min charts of silver, gold and platinum which I follow.

_SECTION_BEGIN( "awilson1a Divergence using RSI" );

//SetBarsRequired( sbrAll, 0 );
periods = Param( "Periods", 14, 1, 200, 1 );
n = Param( "% Reverse ", 0.5, 0.01, 10, 0.01 );

func1 = C;
func2 = RSIa( C, periods );
Buy = Sell = 0;
bi = BarIndex();
Var = Zig( func1, n );
t = Trough( func1, n, 1 );
p = Peak( func1, n, 1 );

onlywhen = Var == p;
pkPrice = SparseCompress( onlywhen, func2 );
pkRsi = SparseCompress( onlywhen, p );
Sell1 = pkPrice > Ref( pkPrice, -1 ) AND pkRsi < Ref( pkRsi, -1 ); // regular
Sell2 = pkPrice < Ref( pkPrice, -1 ) AND pkRsi > Ref( pkRsi, -1 ); // hidden
Sell = Sell1 OR Sell2;
Sell = SparseExpand( onlywhen, Sell );
Sell1 = SparseExpand( onlywhen, Sell1 );
Sell2 = SparseExpand( onlywhen, Sell2 );
Sy0 = SparseExpand( onlywhen, Ref( pkRsi, -1 ) );
Sy1 = SparseExpand( onlywhen, pkRsi );
pkBi = SparseCompress( onlywhen, bi );
Sx0 = SparseExpand( onlywhen, Ref( pkBi, -1 ) );

onlywhen = Var == t;
thPrice = SparseCompress( onlywhen, func2 );
thRsi = SparseCompress( onlywhen, t );
Buy1 = thPrice < Ref( thPrice, -1 ) AND thRsi > Ref( thRsi, -1 ); // regular
Buy2 = thPrice > Ref( thPrice, -1 ) AND thRsi < Ref( thRsi, -1 ); // hidden
Buy = Buy1 OR Buy2;
Buy = SparseExpand( onlywhen, Buy );
Buy1 = SparseExpand( onlywhen, Buy1 );
Buy2 = SparseExpand( onlywhen, Buy2 );
By0 = SparseExpand( onlywhen, Ref( thRsi, -1 ) );
By1 = SparseExpand( onlywhen, thRsi );
thBi = SparseCompress( onlywhen, bi );
Bx0 = SparseExpand( onlywhen, Ref( thBi, -1 ) );

PlotShapes( IIf( Sell1, shapeDownArrow, shapeNone ), colorRed, 0 , Var, Offset = -20 );
PlotShapes( IIf( Sell2, shapeDownArrow, shapeNone ), colorOrange, 0 , Var, Offset = -20 );
PlotShapes( IIf( Buy1, shapeUpArrow, shapeNone ),  colorBlue, 0, Var, Offset = -20 );
PlotShapes( IIf( Buy2, shapeUpArrow, shapeNone ),  colorAqua, 0, Var, Offset = -20 );

Plot( Var, "", colorLightGrey, styleLine | styleNoRescale, Null, Null, 0, 0, 1 );

buyLevel = ValueWhen( Buy, func1 + func1 * ( n / 100 ) );
buyLevel = IIf( Flip( Buy, Ref( Cross( func1, buyLevel ), -1 ) ), buyLevel, Null );
dotBuy = IIf( buyLevel AND Cross( func1, buyLevel ), 1, 0 );
Plot( buyLevel, "", colorYellow, styleDashed | styleNoRescale, Null, Null, 0, 0, 1 );
PlotShapes( IIf( dotBuy, shapeSmallSquare, shapeNone ), colorYellow, 0, func1, 0, 0 );

sellLevel = ValueWhen( Sell, func1 - func1 * ( n / 100 ) );
sellLevel = IIf( Flip( Sell, Ref( Cross( sellLevel, func1 ), -1 ) ), sellLevel, Null );
dotSell = IIf( sellLevel AND Cross( sellLevel, func1 ), 1, 0 );
Plot( sellLevel, "", colorYellow, styleDashed | styleNoRescale, Null, Null, 0, 0, 1 );
PlotShapes( IIf( dotSell, shapeSmallSquare, shapeNone ), colorYellow, 0, func1, 0, 0 );

// Plot the Lines
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status( "LastVisibleBar" );
for( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++ )
{
    // regular divergence
    if( Buy[b] AND Buy1[b] )
    {
        Plot( LineArray( Bx0[b], By0[b], b, By1[b] ), "", colorBlue, styleLine | styleNoRescale, Null, Null, 0, 15, 3 );
    }

    // hidden divergence
    if( Buy[b] AND Buy2[b] )
    {
        Plot( LineArray( Bx0[b], By0[b], b, By1[b] ), "", colorAqua, styleLine | styleNoRescale, Null, Null, 0, 15, 3 );
    }

    // regular divergence
    if( Sell[b] AND Sell1[b] )
    {
        Plot( LineArray( Sx0[b], Sy0[b], b, Sy1[b] ), "", colorRed, styleLine | styleNoRescale, Null, Null, 0, 15, 3 );
    }

    // hidden divergence
    if( Sell[b] AND Sell2[b] )
    {
        Plot( LineArray( Sx0[b], Sy0[b], b, Sy1[b] ), "", colorOrange, styleLine | styleNoRescale, Null, Null, 0, 15, 3 );
    }
}

_SECTION_END();

si

5 Likes

I will explain my issue in detail, I have copied the AFL for RSI Divergence as below:

SetChartOptions( 0, chartShowArrows | chartShowDates );

P = ParamField( "Price field" );
periods = Param( "Periods", 14, 1, 200, 1 );

Overbought = 70;
Oversold = 30;
Centre = 50;

Plot( Overbought, "", colorRed );
Plot( Oversold, "", colorGreen );
Plot( Centre, "", colorWhite, styleDashed );

Plot( RSIa( P, periods ), _DEFAULT_NAME(), ParamColor( "Color", colorcycle ), ParamStyle( "Style" ) );

n = Param( "% Reverse ", 14, 0, 100, 1 );

Buy = Sell = 0;

bi = BarIndex();

Var = Zig( RSI(), n );
t = Trough( RSI(), n, 1 );
p = Peak( RSI(), n, 1 );

//SetTradeDelays(0,0,0,0);

SetStopPrecedence( stopTypeProfit,stopTypeLoss,stopTypeNBar, stopTypeTrailing);
ApplyStop( stopTypeLoss, stopModePercent, 20 ); // 20% max loss from buy price
ApplyStop( stopTypeProfit, stopModePercent, 10 ); // 10% profit target from buy price
ApplyStop( stopTypeNBar, stopModeBars, 15 );


onlywhen = Var == p;
pkPrice = SparseCompress(onlywhen, Close); 
pkRsi = SparseCompress(onlywhen, p);
Sell = pkPrice > Ref(pkPrice, -1) AND pkRsi < Ref(pkRsi, -1);
Sell = SparseExpand(onlywhen, Sell);
Sy0 = SparseExpand(onlywhen, Ref(pkRsi, -1));
Sy1 = SparseExpand(onlywhen, pkRsi);
pkBi = SparseCompress(onlywhen, bi);
Sx0 = SparseExpand(onlywhen, Ref(pkBi, -1));



onlywhen = Var == t;
thPrice = SparseCompress(onlywhen, Close); 
thRsi = SparseCompress(onlywhen, t);
Buy = thPrice < Ref(thPrice, -1) AND thRsi > Ref(thRsi, -1);
Buy = SparseExpand(onlywhen, Buy);
By0 = SparseExpand(onlywhen, Ref(thRsi, -1));
By1 = SparseExpand(onlywhen, thRsi);
thBi = SparseCompress(onlywhen, bi);
Bx0 = SparseExpand(onlywhen, Ref(thBi, -1));

PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorRed, 0 , Var, Offset = -20 );
PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ),  colorBrightGreen, 0, Var, Offset = -20 );

// Plot the Lines
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status( "LastVisibleBar" );

for ( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++ )
{
    if ( Buy[b] )
        Plot( LineArray( Bx0[b], By0[b], b, By1[b] ), "", colorRed, styleThick );
    else if ( Sell[b] )
        Plot( LineArray( Sx0[b], Sy0[b], b, Sy1[b] ), "", colorBlue, styleThick );
}

I am using this AFL for EOD data. I have scanned a list of stocks which also contains the below:
MCDOWELL-N
REPRO

When I scanned for date range from 18.03.2021 to 18.03.2021, it didn't return any stock.

When I scanned for date range from 18.03.2021 to 19.03.2021, it returned below stocks for 18.03.2021 which was not listed in the scanning of previous step:
P1

I observed that stocks are listed with a delay of 1 day. Could you please help to list the stocks thru scanning without any delay?

It has me stumped. I don't know why your scan results are like that.
I copied your afl with no change and get results as expected.
In the attached, if I restrict the date range to just one of the days (17th or 18th) I get just the two relevant stocks returned as expected.
Sorry, I can't help any. I really don't know why your results are like they are
ATR_diverg