AFL for Price Patterns

#1
Hi All,
I have found the AFL codes for price pattern in Amibroker Library. I tried to run some of the codes but getting errors. Being a beginner for Amibroker (AFL) couldnt resolve the issue. I request to all the seniors & experts to look into the code & resolve the issue. This will help to everyone.

Head & Shoulder/Inverted Head & Shoulder:
x = Cum(1);
per = 5;
back=50;
inter=100;
s11=H;s12=L;
/* H & S */
pR = PeakBars( s11, per, 1 ) == 0;
endt1= LastValue(ValueWhen( pR, x, 1 ));
medt1=LastValue(ValueWhen( pR, x, 2 ));
startt1=LastValue(ValueWhen( pR, x, 3 ));
dt1=endt1-startt1;
C1=x==endt1 OR x==medt1 OR x==startt1;
endR = LastValue(ValueWhen( pR, s11, 1 ) );
medR=LastValue(ValueWhen( pR, s11, 2 ) );
startR = LastValue( ValueWhen( pR, s11, 3 ));
Filter1=medR>endR AND medR>startR AND abs(startR-endR)<0.02*(startR+endR) AND dt1<inter AND endt1>LastValue(x)-back;
MaxGraph=10;Graph1=C;Graph1Style=64;GraphXSpace=5;
/*H&S Neck Line*/
Aper=medt1-startt1;bper=endt1-medt1;
La= LastValue(ValueWhen(x==medt1,LLV(L,Aper)));
Lb=LastValue(ValueWhen(x==-1+endt1,LLV(L,bper)));
Fa=L==La AND x>startt1 AND x<medt1;
Fb=L==Lb AND x>medt1 AND x<endt1;
endt= LastValue(ValueWhen( Fb, x ));
startt=LastValue(ValueWhen( Fa, x ));
dtS =endt-startt;endS = Lb;startS = La;
aS = (endS-startS)/dtS;bS = endS;
trendlineS = aS * ( x -endt ) + bS;
Graph3 = IIf(Filter1 AND x>startt-5,trendlineS,-1e10);Graph3BarColor=7;
/*Inverted H & S*/
tpR = TroughBars( s12, per, 1 ) == 0;
tendt1=LastValue(ValueWhen(tpr,x,1));
tmedt1=LastValue(ValueWhen(tpr,x,2));
tstartt1=LastValue(ValueWhen(tpr,x,3));
tdt1=tendt1-tstartt1;
C2=x==tendt1 OR x==tmedt1 OR x==tstartt1;
tendR = LastValue(ValueWhen( tpR, s12, 1 ) );
tmedR=LastValue(ValueWhen( tpR, s12, 2 ) );
tstartR = LastValue( ValueWhen( tpR, s12, 3 ));
Filter2=tmedR<tendR AND tmedR<tstartR AND abs(tstartR-tendR)<0.02*(tstartR+tendR) AND tdt1<inter AND tendt1>LastValue(x)-back;
Graph1BarColor=IIf(C1 AND Filter1,7,IIf(C2 AND Filter2,10,1));
/*Inverted H&S Neck Line*/
tAper=tmedt1-tstartt1;tbper=tendt1-tmedt1;
Ha= LastValue(ValueWhen(x==tmedt1,HHV(H,tAper)));
Hb=LastValue(ValueWhen(x==-1+tendt1,HHV(H,tbper)));
tFa=H==Ha AND x>tstartt1 AND x<tmedt1;
tFb=H==Hb AND x>tmedt1 AND x<tendt1;
Rendt= LastValue(ValueWhen(tFb, x ));
Rstartt=LastValue(ValueWhen( tFa, x ));
Rdt =Rendt-Rstartt;endR = Hb;startR = Ha;
aR = (endR-startR)/Rdt;bR = endR;
trendlineR = aR * ( x -Rendt ) + bR;
Graph4 = IIf(Filter2 AND x>Rstartt-5,trendlineR,-1e10);Graph4BarColor=10;
Filter=Filter1 OR Filter2;
NumColumns=2;/*Graph2=x==-1+tendt1;*/
Column0=Filter1;
Column1=Filter2;
Column0Format=Column1Format=1.0;
Column0Name="H&S";
Column1Name="inv H&S";


Double top & bottom:

/* Detecting double tops and bottoms*/
percdiff = 5; /* peak detection threshold */
fwdcheck = 5; /* forward validity check */
mindistance = 10;
validdiff = percdiff/10;

PK= Peak( H, percdiff, 1 ) == High;
TR= Trough( L, percdiff, 1 ) == Low;


x = Cum( 1 );
XPK1 = ValueWhen( PK, x, 1 );
XPK2 = ValueWhen( PK, x, 2 );
xTR1 = ValueWhen( Tr, x, 1 );
xTr2 = ValueWhen( Tr, x, 2 );

peakdiff = ValueWhen( PK, H, 1 )/ValueWhen( PK, H, 2 );
Troughdiff=ValueWhen( tr, L, 1 )/ValueWhen( tr, L, 2 );

doubletop = PK AND abs( peakdiff - 1 ) < validdiff AND (Xpk1 -Xpk2)>mindistance AND High > HHV( Ref( H, fwdcheck ), fwdcheck - 1 );
doubleBot=tr AND abs( troughdiff - 1 ) < validdiff AND (Xtr1 -Xtr2)>mindistance AND Low < LLV( Ref( L, fwdcheck ), fwdcheck - 1 );

Sell = doubletop;
Buy = doublebot;

WriteIf( Highest( doubletop ) == 1, "AmiBroker has detected some possible
double top patterns for " + Name() + "\nLook for green arrows on the price
chart.", "There are no double top patterns for " + Name() );

WriteIf(Highest( doublebot)==1,"AmiBroker has detected some possible double
bottom patterns for " + Name() + "\nLook for red arrows on the price
chart.", "There are no double bottom patterns for " + Name() );

Filter=Sell OR Buy ;

AddColumn( IIf( doubletop , 88, 01), "Double TOP", formatChar );
AddColumn( IIf( doublebot , 88, 01), "Double BOT", formatChar );


Triangles, Flags/Rectangle Base Breakout on High Volume:


Triangles:

// Triangle search Extended

/*This scan/exploration extends the triangle search by Graham Kavanagh
The original scans for triangles using Highest High AND Lowest Low over a 20 bar period,
then next High over a chosen period after these HHV AND LLV. He requires the order of the
highs AND lows are to be in alternate order and his test will pick up ascending, descending
AND equal triangles. His 'variable' d1 (set to 20)is the number of days to lookback and search
for the last Highest High, AND d2 is the gap after this HH to start searching for the next HH
after the first. Similarly for the Lowest lows
The variables z? represent the highs, AND w? the lows.

This extended program adds a number of options, as follows:-
a. It automatically searches over different lookback periods between d1max and d1min, set to
60 and 20 (but easily changed) and records all succeses. Because of the nature of triangles,a
single value for d1 can miss many valid cases.
b. Where the triangle criteria are satisfied on successive days, only the last of these is retained
in order to reduce the amount of output.
c. The user can toggle between searches based on the data H and L, or the highs and lows of the candle body.
d. The lengthy test to yield a "buy" in the original has been broken down into 7 separate conditions,
allowing the user to easily change the conditions. Thus, Condition 3 tests for the triangle shape. This can
use a more liberal test via the parameter toggle that has been added. Similarly, Cond5 is a volume test which
can now be left in or excluded.
Finally, the user should note that conds 6 and 7 test that the general price trend is up. If interested in
potential downward moves, a user might want to delete these from the "buying" test.
*/

d1max = 60;
d1min = 20;
Buy = 0;


for (d1=d1min;d1<d1max;d1++)
{
d2=4;
Hi = H;
Lo = L;
Body = ParamToggle("Use candle body rather than H & L","No|Yes", 0);
if(Body == 1)
{
Hi = Max(O,C);
Lo = Min(O,C);
}
z1=HHV(Hi,d1);
za1=HHVBars(Hi,d1);
zb1=za1-d2;
z2=HHV(Hi,zb1);
za2=HHVBars(Hi,zb1);
w1=LLV(Lo,d1);
wa1=LLVBars(Lo,d1);
wb1=wa1-d2;
w2=LLV(Lo,wb1);
wa2=LLVBars(Lo,wb1);

aa1=LastValue(Hi);
aa2=LastValue(Lo);

C3 = ParamToggle("Use a more liberal triangle shape test?", "No|Yes",0);
ExVol = ParamToggle("Exclude volume test?","No|Yes",0);

Cond1 = ((z1>=z2 AND w2>w1) OR(z1>z2 AND w2>=w1));//Allows for horizontal top or bottom
Cond2 = za1>za2 AND wa1>wa2;//Automatically satisfied if za1,za2,wa1 and wa2 all exist
//Cond3 ensures triangle shape
Cond3 =((za1>wa1 AND wa1>za2 AND za2>wa2) OR (wa1>za1 AND za1>wa2 AND wa2>za2)) ;//Original
if(C3 == 1)
Cond3 =((za1>wa1 AND wa1>za2) OR (wa1>za1 AND za1>wa2)) ;//a more liberal test

Cond4 = aa1<z2 AND aa2>w2 ;// Triangle shape continues to last Value

Cond5 = Ref(Volume,-za1) > MA(Volume,d2);
if(ExVol == 1) Cond5 =1;
//Conditions 6 & 7 require close price trend to be up
Cond6 = Ref(MA(Close,d1),-za1) > Ref(MA(Close,d1),-2*za1) ;
Cond7= MA(Close,d1) > Ref(MA(Close,d1),-2*za1);
Buying = Cond1 AND Cond2 AND Cond3 AND Cond4 AND Cond5 AND Cond6 AND Cond7;
Buy = Buy + Buying;
}
for(i=1;i<BarCount;i++)
if(Buy>=1)
{
Buy[i-1]=0;
Buy = 1;
}
//Retain only the last of consecutive buy signals

Filter=Buy;
/*
NumColumns = 8;

Column0 = z1;
Column1 = z2;
Column2 = w1;
Column3 = w2;
Column4 = za1;
Column5 = za2;
Column6 = wa1;
Column7 = wa2;
*/

NumColumns = 8;
Column0 = Cond1;
Column1 = Cond2;
Column2 = Cond3;
Column3 = Cond4;
Column4 = Cond5;
Column5 = Cond6;
Column6 = Cond7;
Column7 = Buy;

Flag/Rectangle Base Breakout on High Volume:
Description:

A powerful script that that the author created the function but did not create the exploration. It had put on the shelf for 5 years since 2003 till now.

Not a lot people understand it and know how to script it to make it operatable.

Run Analysis, click "Scan" or "Explore" will do.
Click on "Parameters" to change the "Min. Average Volume" in Million, step is 0.1M
Formula:

/*
Exploration:

Detects an upwards breakout from a rectangular base formation on a high
volume.

Original amibroker script by Jitu Telang
http://www.amibroker.com/library/detail.php?id=297

*/

minAvgVolume = Param("Min Average Volume (Million)", 1, 0.1, 1000, 0.1);
minAvgVolume = minAvgVolume *1000000;

function rectBaseBreakout()
{

hhv9d = HHV(H, 9);
llv9d = LLV(L, 9);

hhv1m = HHV(H, 20);
llv1m = LLV(L, 20);

hhv2m = HHV(H, 40);
llv2m = LLV(L, 40);

hhv50d = HHV(H, 50);
llv50d = LLV(L, 50);

vhhv60d = HHV(V, 60);

cav50d = MA(C, 50);
vav20d = MA(V, 20);

C1 = H > Ref(hhv9d, -1);
C2 = L > Ref(llv9d, -1);
C3 = C > Ref(hhv50d, -1);
C4 = C > cav50d;
C5 = V > (vav20d * 2);
C6 = vav20d > minAvgVolume;
C7 = cav50d > 0;
C8 = (llv1m < (llv2m * 1.05)) OR (llv1m <= (llv2m + 1));
C9 = (hhv1m > (hhv2m * 0.95)) OR (hhv1m >= (hhv2m - 1));

return( C1 AND C2 AND C3 AND C4 AND C5 AND C6 AND C7 AND C8 AND C9 );
}

Buy = rectBaseBreakout();
Filter = Buy;
AddColumn(C, "Close", 5.3);
AddColumn(V, "Volumn", 8.0);


I have found out this below mentioned code. It correlates price data marked by "markers" in the price chart with price data inside a given list of symbols. Its pretty interesting. Please have a look on it.


/*
Program correlates price data marked by "markers" in the
price chart with price data inside a given list of symbols.

Purpose: find similar pattern in order to see how the price
reacted to a similar pattern.

Also this code looks at the first "lpred" days following the
fit (as default lpred is set to 5). It finds the highest
and the lowest price during this period.

1) Put this code in the Automatic Analysis window.
2) Select a symbol.
3) Select a piece of the chart you want to fit using the
Amibroker markers.
4) Explore a certain list of symbols ("use filter") for "all
quotations" (or select a range).
5) Sort the sum by clicking on "sum" in the AA window
(smallest Sum is best fit).

ed2000nl, Jan 2004, [email protected]

*/

// select the symbol from the active chart
EnableScript("jscript");
<%
AB = new ActiveXObject("Broker.Application");
AFL("symb")=AB.ActiveDocument.Name;
%>

// extract the period from the graph selected by using the markers
period = EndValue( BarIndex() ) - BeginValue( BarIndex() );

// test to avoid that marked period is out of range of the available data.
if (period > 0 AND BeginValue( BarIndex() ) != 0 AND EndValue( BarIndex() ) != BarCount) {

// define the length of period to predict
lpred = 5;

// select the variables of the stock you want to correlate
xo=Foreign(symb,"Open");
xh=Foreign(symb,"High");
xl=Foreign(symb,"Low");
xc=Foreign(symb,"Close");
xv=Foreign(symb,"Volume");

// define help arrays in which to store the data you want to fit
xoh = xo; xoh = 0;
xhh = xh; xhh = 0;
xlh = xl; xlh = 0;
xch = xc; xch = 0;
xvh = xv; xvh = 0;

// store the piece of array you selected by using the markers
cnt = 0;
for( i = BeginValue( BarIndex() ); i < BeginValue( BarIndex() ) + period + 1; i++ ) {

xoh[cnt] = xo;
xhh[cnt] = xh;
xlh[cnt] = xl;
xch[cnt] = xc;
xvh[cnt] = xv;
cnt = cnt + 1;

}

// define a storage array to store the fit
st = C; st = 100000; pr1 = st; pr2 = pr1;

// correlate this selected piece of data with all data in the list
for( i = period + 1; i < BarCount - lpred; i++) {

// calculate scale factor
scl = xch[0] / C[i-period];

hsum = 0;
for( j = 0; j < period + 1; j++) {

// the fit procedure
hsum = hsum +
((xoh[j] - O[i-period+j]*scl)/xoh[j])^2 +
((xhh[j] - H[i-period+j]*scl)/xhh[j])^2 +
((xlh[j] - L[i-period+j]*scl)/xlh[j])^2 +
((xch[j] - C[i-period+j]*scl)/xch[j])^2;

//AddColumn(C[i-period+j],"Clp");
//AddColumn(xch[j],"Cfit");


}

st = hsum/(period+1);

// highest profit possible within lpred days
hlp = ( HHV(Ref(H,lpred),lpred) - O ) / O * 100;
pr1 = hlp;

// greatest loss possible within lpred days
hlp = ( LLV(Ref(L,lpred),lpred) - O ) / O * 100;
pr2 = hlp;

}

Filter=1;
AddColumn(st,"sum",format = 1.6);
AddColumn(pr1,"greatest possible gain",1.2,colorBlack,colorGreen);
AddColumn(pr2,"greatest possible loss",1.2,colorBlack,colorRed);
AddColumn(period,"period fitted");
AddColumn(scl,"scale");
AddTextColumn(symb,"Symbol Fitted");


}

AFL Experts Please Comment.

Thanks & Regards,
TT
 
#3
hi,
Can we have candlestick patterns here
eg,
Bullish engulfing
Bearish Engulfing
doji
harami
morning star
evening star etc...and other basic patterns

if we have it here itself in traderji please share the link

KEVIN