Candle Pattern Detector Heiken Ashi



Candle Pattern Detector Heiken Ashi
Candle Pattern Detector Heiken Ashi


//www.aflcode.com
_SECTION_BEGIN("Heikin-Ashi (Koma");
/*
Heikin-Ashi(Koma-Ashi) with Moving Average Type
 */
SetChartOptions(2, chartWrapTitle);
// Calculate Moving Average
MAPeriod = Param("MA Period", 15, 1, 100);
MAOpen = EMA(Open, MAPeriod);
MAHigh = EMA(High, MAPeriod);
MALow = EMA(Low, MAPeriod);
MAClose = EMA(Close, MAPeriod);
HaClose = (MAOpen + MAHigh + MALow + MAClose) / 4;
HaOpen = AMA(Ref(HaClose,  - 1), 0.5);
// for graph collapse
for (i = 0; i <= MAPeriod; i++)
  HaClose[i] = Null;
/*
// same 
// HaOpen = (Ref(HaOpen, -1) + Ref(HaClose, -1)) / 2;
HaOpen[ 0 ] = HaClose[ 0 ]; 
for(i = 1; i < BarCount; i++) { 
HaOpen[i] = (HaOpen[i - 1] + HaClose[i - 1]) / 2;
} 
 */
HaHigh = Max(MAHigh, Max(HaClose, HaOpen));
HaLow = Min(MALow, Min(HaClose, HaOpen));
// outs comments
"BarIndex = " + BarIndex();
"Open = " + Open;
"High = " + High;
"Low = " + Low;
"Close = " + Close;
"HaOpen = " + HaOpen;
"HaHigh = " + HaHigh;
"HaLow = " + HaLow;
"HaClose = " + HaClose;
// Plot graphs
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} HaOpen %g, HaHigh %g, HaLow %g, HaClose %g (%.1f%%) {{VALUES}}", HaOpen, HaHigh, HaLow, HaClose, SelectedValue(ROC(HaClose, 1))));
PlotOHLC(HaOpen, HaHigh, HaLow, HaClose, _DEFAULT_NAME(), ParamColor("Color", colorBlack), styleCandle);
/* **********************************
Code to automatically identify pivots
 ********************************** */
// -- what will be our lookback range for the hh and ll?
farback = Param("How Far back to go", 100, 50, 5000, 10);
nBars = Param("Number of bars", 12, 5, 40);
// -- Title.
Title = Name() + " (" + StrLeft(FullName(), 15) + ") O: " + Open + ", H: " + High + ", L: " + Low + ", C: " + Close;
// -- Plot basic candle chart
PlotOHLC(Open, High, Low, Close, "BIdx = " + BarIndex() + "\n" + "O = " + O + "\n" + "H = " + H + "\n" + "L = " + L + "\n" + "C ", colorYellow, styleLine | styleThick);
GraphXSpace = 7;
// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
// -- More for future use, not necessary for basic plotting
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
nHPivs = 0;
nLPivs = 0;
lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;
// -- looking back from the current bar, how many bars 
// back were the hhv and llv values of the previous 
// n bars, etc.?
aHHVBars = HHVBars(H, nBars);
aLLVBars = LLVBars(L, nBars);
aHHV = HHV(H, nBars);
aLLV = LLV(L, nBars);
// -- Would like to set this up so pivots are calculated back from
// last visible bar to make it easy to "go back" and see the pivots
// this code would find. However, the first instance of 
// _Trace output will show a value of 0
aVisBars = Status("barvisible");
nLastVisBar = LastValue(Highest(IIf(aVisBars, BarIndex(), 0)));
_TRACE("Last visible bar: " + nLastVisBar);
// -- Initialize value of curTrend
curBar = (BarCount - 1);
curTrend = "";
if (aLLVBars[curBar] < 
aHHVBars[curBar])
{
  curTrend = "D";
}
else
{
  curTrend = "U";
}
// -- Loop through bars. Search for 
// entirely array-based approach
// in future version
for (i = 0; i < farback; i++)
{
  curBar = (BarCount - 1) - i;
  // -- Have we identified a pivot? If trend is down...
  if (aLLVBars[curBar] < aHHVBars[curBar])
  {
    // ... and had been up, this is a trend change
    if (curTrend == "U")
    {
      curTrend = "D";
      // -- Capture pivot information
      curPivBarIdx = curBar - aLLVBars[curBar];
      aLPivs[curPivBarIdx] = 1;
      aLPivLows[nLPivs] = L[curPivBarIdx];
      aLPivIdxs[nLPivs] = curPivBarIdx;
      nLPivs++;
    }
    // -- or current trend is up
  }
  else
  {
    if (curTrend == "D")
    {
      curTrend = "U";
      curPivBarIdx = curBar - aHHVBars[curBar];
      aHPivs[curPivBarIdx] = 1;
      aHPivHighs[nHPivs] = H[curPivBarIdx];
      aHPivIdxs[nHPivs] = curPivBarIdx;
      nHPivs++;
    }
    // -- If curTrend is up...else...
  }
  // -- loop through bars
}
// -- Basic attempt to add a pivot this logic may have missed
// -- OK, now I want to look at last two pivots. If the most 
// recent low pivot is after the last high, I could
// still have a high pivot that I didn't catch
// -- Start at last bar
curBar = (BarCount - 1);
candIdx = 0;
candPrc = 0;
lastLPIdx = aLPivIdxs[0];
lastLPL = aLPivLows[0];
lastHPIdx = aHPivIdxs[0];
lastHPH = aHPivHighs[0];
if (lastLPIdx > lastHPIdx)
{
  // -- Bar and price info for candidate pivot
  candIdx = curBar - aHHVBars[curBar];
  candPrc = aHHV[curBar];
  if (
  lastHPH < candPrc AND 
  candIdx > lastLPIdx AND 
  candIdx < curBar)
  {
    // -- OK, we'll add this as a pivot...
    aHPivs[candIdx] = 1;
    // ...and then rearrange elements in the 
    // pivot information arrays
    for (j = 0; j < nHPivs; j++)
    {
      aHPivHighs[nHPivs - j] = aHPivHighs[nHPivs - 
      (j + 1)];
      aHPivIdxs[nHPivs - j] = aHPivIdxs[nHPivs - (j + 1)];
    }
    aHPivHighs[0] = candPrc;
    aHPivIdxs[0] = candIdx;
    nHPivs++;
  }
}

else
{
  // -- Bar and price info for candidate pivot
  candIdx = curBar - aLLVBars[curBar];
  candPrc = aLLV[curBar];
  if (
  lastLPL > candPrc AND 
  candIdx > lastHPIdx AND 
  candIdx < curBar)
  {
    // -- OK, we'll add this as a pivot...
    aLPivs[candIdx] = 1;
    // ...and then rearrange elements in the 
    // pivot information arrays
    for (j = 0; j < nLPivs; j++)
    {
      aLPivLows[nLPivs - j] = aLPivLows[nLPivs - (j + 1)];
      aLPivIdxs[nLPivs - j] = aLPivIdxs[nLPivs - (j + 1)];
    }
    aLPivLows[0] = candPrc;
    aLPivIdxs[0] = candIdx;
    nLPivs++;
  }
}
// -- Dump inventory of high pivots for debugging
/*
for (k=0; k<nHPivs; k++) {
_TRACE("High pivot no. " + k
+ " at barindex: " + aHPivIdxs[k] + ", " 
+ WriteVal(ValueWhen(BarIndex()==aHPivIdxs[k], 
DateTime(), 1), formatDateTime)
+ ", " + aHPivHighs[k]);
}
 */
// -- OK, let's plot the pivots using arrows
PlotShapes(IIf(aHPivs == 1, shapeDownArrow, shapeNone), colorRed, 0, High, Offset =  - 15);
PlotShapes(IIf(aLPivs == 1, shapeUpArrow, shapeNone), colorBrightGreen, 0, Low, Offset =  - 15);
_SECTION_END();

//*****************************************

//*****************************************

//PRICE

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//TRENDING RIBBON
// Paste the code below to your price chart somewhere and green ribbon means both
// both MACD and ADX trending up so if the red ribbon shows up the MACD and the ADX 
// are both trending down.
_SECTION_BEGIN("trending ribbon");
uptrend=PDI()>MDI() AND MACD()>Signal();
downtrend=MDI()>PDI() AND Signal()>MACD();
Plot( 2, /* defines the height of the ribbon in percent of pane width */"",
    IIf( uptrend AND EMA(C,50)>=Ref(EMA(C,50),-1), colorLime, IIf( downtrend OR EMA(C,50)<Ref(EMA(C,50),-1),
     colorRed, colorTan)) , /* choose color */styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

//TREND ADVISER

pointer[0] = 0;

/* Phase filter */

Cond1 = Close > MA(Close, 50)AND NOT(Close > MA(Close, 200))AND NOT(MA(Close, 50) > MA(Close, 200));
Cond2 = Close > MA(Close, 50)AND Close > MA(Close, 200)AND NOT(MA(Close, 50) > MA(Close, 200));
Cond3 = Close > MA(Close, 50)AND Close > MA(Close, 200)AND MA(Close, 50) > MA(Close, 200);
Cond4 = NOT(Close > MA(Close, 50))AND Close > MA(Close, 200)AND MA(Close, 50) > MA(Close, 200);
Cond5 = NOT(Close > MA(Close, 50))AND NOT(Close > MA(Close, 200))AND MA(Close, 50) > MA(Close, 200);
Cond6 = NOT(Close > MA(Close, 50))AND NOT(Close > MA(Close, 200))AND NOT(MA(Close, 50) > MA(Close, 200));


for (i = 1; i < BarCount; i++)
{

  if (Cond1[i])
    pointer[i] = 1;
  if (Cond2[i])
    pointer[i] = 2;
  if (Cond3[i])
    pointer[i] = 3;
  if (Cond4[i])
    pointer[i] = 4;
  if (Cond5[i])
    pointer[i] = 5;
  if (Cond6[i])
    pointer[i] = 6;

}

/* Plot Graphic */
//GraphXSpace= 15 ;
dynamic_color = IIf(pointer < 4, colorGreen, colorRed);
//Plot(pointer, "TrendAdv2", dynamic_color, styleHistogram | styleThick, Null, Null, 0);
//SetChartBkGradientFill(ParamColor("BgTop", colorWhite), ParamColor("BgBottom", colorLightYellow));
Cond= pointer < 4 ;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

//KPL

/* my entry is very simple(daily data for trading)

kpl system for entry only & exit as follow:

1 st exit at x % from entry price only 1/3 quantity.(ie 1st profit target)
2 nd exit when exit Signal comes from kpl sys remaining 1/3 quantity.
3. scale-in to initial quantity if new kpl Buy Signal comes.
re-do above scaling-out & scaling-in till filal exit.
4. final exit all quantity when Close below 21 Day EMA.

kpl system code bellow :
*/
//AFL by Kamalesh Langote. Email:kpl@...
noR =Param( "SwingR", 5, 1, 55 ) ;
noS =Param( "SwingS", 2, 1, 55 ) ;
res=HHV(H,noR);
sup=LLV(L,noS);
avd=IIf(C>Ref(res,-1),1,IIf(C<Ref(sup,-1),-1,0));
avn=ValueWhen(avd!=0,avd,1);
tsl=IIf(avn==1,sup,res);
//tsl_col=ParamColor( "Color", colorCycle );
tsl_col= IIf(avn==1,colorBlue,colorRed );
Plot(tsl, "KPL", tsl_col, styleStaircase | styleThick);
//shape=Buy*shapeUpArrow + Sell*shapeDownArrow;
//PlotShapes(shape,IIf(Buy,colorBlue,colorRed),0,IIf(Buy,Low,High));
SetPositionSize(300,spsShares);
ApplyStop(0,1,10,1);
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

_SECTION_BEGIN("Background");
SetChartBkGradientFill(ParamColor("Top", colorTeal), ParamColor("Bottom", colorLightGrey), ParamColor("Title", colorTeal));
SetChartBkColor(ParamColor("Chart Background", colorWhite));
_SECTION_END();

_SECTION_BEGIN("trends trail SVE");
function trends_func(resistance)
{
 trends = (H+L)/2; // initialize
 support = (H+L)/2; // initialize
 
 for( i = 4; i < BarCount; i++ )
 {
  // support
  prev = support[ i - 1 ];
 
  if (L[ i ] >= L[ i - 2 ] 
   AND L[ i - 1 ] >= L[ i - 2 ] 
   AND L[ i - 3 ] >= L[ i - 2 ] 
   AND L[ i - 4 ] >= L[ i - 2 ])
  {
   support[ i ] = L[ i - 2 ];
  }
  else if (L[ i ] > H[ i - 1]*1.0013)
  {
   support[ i ] = H[ i - 1 ]*0.9945;
  }
  else if (L[ i ] > prev*1.1)
  {
   support[ i ] = prev*1.05;
  }
  else
  {
   support[ i ] = prev;
  } 
  // trends
  prev = trends[ i - 1 ];
 
  if (H[ i ] > prev AND H[ i - 1 ] > prev)
  {
   trends[ i ] = Max(prev,support[ i ]);
  }
  else if (H[ i ] < prev AND H[ i - 1 ] < prev)
  {
   trends[ i ] = Min(prev,resistance[ i ]);
  }
  else if (H[ i ] > prev)
  {
   trends[ i ] = support[ i ];
  }
  else
  {
   trends[ i ] = resistance[ i ];
  }
 }
 return trends;
}

// AFL code by E.M.Pottasch, 12/28/2010, 
// idea from: http://stocata.org/metastock/stop_trail_trends.html
atrfact = Param("atrfact",2, 1, 10, 0.1);
period = Param("period",10, 1, 100, 1);
HiLo = IIf(H-L<1.5*MA(H-L,period),H-L,1.5*MA(H-L,period));
Href = IIf(L<=Ref(H,-1),H-Ref(C,-1),(H-Ref(C,-1))-(L-Ref(H,-1))/2);
Lref = IIf(H>=Ref(L,-1),Ref(C,-1)-L,(Ref(C,-1)-L)-(Ref(L,-1)-H)/2);
diff1 = Max(HiLo,Href);
diff2 = Max(diff1,Lref);
ATRmod = Wilders(diff2,period);
loss = atrfact*ATRmod;
resistance = C + loss;
// calculate trends
trends = trends_func(resistance);

SetChartBkColor( ParamColor("ColorBG", ColorRGB( 0, 0, 0 ) ) );
GraphXSpace = 5;
SetChartOptions(0, chartShowDates);
Plot(IIf(trends > C,trends,Null),"\ntrailShort",ParamColor("ColorTrailShort",ColorRGB(255,0,0)),styleStaircase);
Plot(IIf(trends < C,trends,Null),"\ntrailLong",ParamColor("ColorTrailLong",ColorRGB(0,255,0)),styleStaircase);
_SECTION_END();

_SECTION_BEGIN("Candlesick Patterns");
Plot(C,"",colorLightGrey,styleCandle);

r=CdDoji( threshold = 0.05 );
s=CdHammer( rangefactor= 1.1 );
t=CdBearishEngulfing( bodyfactor = 0.4, rangefactor = 0.5);
u=CdBullishEngulfing( bodyfactor = 0.4, rangefactor = 0.5);
PlotShapes(r*shapeSmallCircle,colorRed,Layer=0,yposition=H,Offset=12); 
PlotShapes(s*shapeCircle,colorYellow,Layer=0,yposition=H,Offset=12); 
PlotShapes(t*shapeHollowSmallCircle,colorLime,Layer=0,yposition=H,Offset=12); 
PlotShapes(u*shapeHollowCircle,colorBlue,Layer=0,yposition=H,Offset=12); 

for(i=0;i<BarCount-1;i++) 
{
 if(r[i]==True)PlotText("Doji", i, H[i], colorRed, bkcolor = colorDefault); 
 if(s[i]==True)PlotText("Hammer", i, H[i], colorYellow, bkcolor = colorDefault); 
 if(t[i]==True)PlotText("BearishEngulf", i, H[i], colorLime, bkcolor = colorDefault); 
 if(u[i]==True)PlotText("BullishEngulf", i, H[i], colorBlue, bkcolor = colorDefault); 
}
_SECTION_END();

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

_SECTION_BEGIN("Show Values at H&L");

n=Param("Values back",20,1,200,1);
p=Param("zig %",5,1,100,1);
dist = 0.8*ATR(15);

for( i = 1; i < n; i++ )
{ 
 PlotText(""+LastValue(Peak(H,p,i),True),BarCount-3-LastValue(PeakBars(H,p,i)),LastValue(dist,True)+LastValue(Peak(H,p,i),False),colorBlack,ColorRGB(225,225,225));
 PlotText(""+LastValue(Trough(L,p,i),True),BarCount-3-LastValue(TroughBars(L,p,i)),LastValue(Trough(L,p,i),False)-LastValue(dist,True),colorBlack,ColorRGB(225,225,225));
}

_SECTION_END();

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

_SECTION_BEGIN("Average Side Way Mkt");
price = ParamField("field");
n = Param("periods",35);
SA=MA(Price,n);
v1=(StDev(Price,n))^2;

Ca=Null;
Ca[n]=sa[n];

for(i=n+1; i<BarCount;i++){
v2[i]=(CA[i-1]-SA[i])^2;
k[i]=IIf(V2[i]<V1[i],0,1-V1[i]/V2[i]);
CA[i]=CA[i-1]+K[i]*(SA[i-1]-CA[i-1]);
}
Plot(Ca,"OMA("+WriteVal(n,1.0)+")",colorYellow,styleThick);
Col = IIf(BarsSince(Ref(Ca,-1)>Ca)>BarsSince(Ref(Ca,-1)<Ca),colorBrightGreen,colorRed);
Plot(C,"",Col,styleBar);
_SECTION_END();

_SECTION_BEGIN("Bar Count Back V. Good");
//* Stephane Carrasset's Countback Line (CBL) popularized by Daryl Guppy

//Refer to amibroker posting 30th December 2004 */

nR=2;

Cbl[nR]=Null;

bCBL=False;

for( i=nR; i < BarCount; i++)

{

if( (Low[i-2]<Low[i-1]) && (Low[i-1]<Low[i]) )

{

Cbl[i] = Low[i-2];

bCBL = True;

}

else if (bCBL)

{

if (Low[i] < Cbl[i-1])

{

Cbl[i] = Cbl[i-1];

bCBL = False;

}

else

{

n = nR;

minval[i] = Low[i];

breakloop= False;

for (j = 1; NOT(breakloop) && j <= i; j++)

{

if (Low[i-j] < minval[i])

{

if (n>1)

{

minval[i] = Low[i-j];

n--;

}

else

{

Cbl[i] = Low[i-j];

breakloop=True;

}

}

}

if (Cbl[i] < Cbl[i-1])

Cbl[i] = Cbl[i-1];

}

}

else

{

Cbl[i] = Cbl[i-1];

}

if (Cbl[i]==0)

Cbl[i] = Cbl[i-1];

}

Plot(Cbl,"",colorGreen,1);

Plot(C,"",-1,64);

_SECTION_END();
_SECTION_END();



_SECTION_BEGIN("Background");
SetChartBkGradientFill(ParamColor("Top", colorTeal), ParamColor("Bottom", colorLightGrey), ParamColor("Title", colorTeal));
SetChartBkColor(ParamColor("Chart Background", colorWhite));
_SECTION_END();

_SECTION_BEGIN("Didi Index Indicator");
function DidiIndex( Curta, Media, Longa )
{
 global DidiLonga, DidiCurta;
 DidiLonga = MA( Close, Longa ) - MA( Close, Media );
 DidiCurta = MA( Close, Curta ) - MA( Close, Media );
 
 return IIf(DidiCurta > 0 AND DidiLonga < 0, 1,IIf(DidiCurta<0 AND DidiLonga>0, -1,0));
}

MAFast = Optimize("Curta",Param("MA Curta",3,1,5 ),1,5,1);
MAMid  = Optimize("Media",Param("MA Média",8,6,12),6,12,1);
MASlow = Optimize("Longa",Param("MA Longa",20,15,34),15,34,1);

Trend = DidiIndex(MAFast, MAMid, MASlow);
Buy = Cross(Trend,0) AND ADX()>MDI();
Sell = Cross(0,Trend);
Buy = ExRem(Buy,Sell); Sell = ExRem(Sell,Buy);

TrendColor = IIf(DidiCurta>0,colorLime,colorRed);

Plot( DidiCurta, _DEFAULT_NAME(), TrendColor, ParamStyle("Histogram style", styleThick | styleHistogram | styleNoLabel, maskHistogram ));
Plot(0,"", colorBrown ,styleLine);

Plot(DidiLonga,"",IIf(DidiLonga<0,colorGreen,colorRed),styleLine | styleThick);

Plot(DidiCurta,"",IIf(DidiCurta>0,colorGreen,colorRed),styleLine | styleThick);

//Normal Buy and Sell Signal
PlotShapes(Buy*shapeUpTriangle,colorBlue,0,-0.5);
PlotShapes(Sell*shapeDownTriangle,colorPink,0,0.5);

// The Best Signal: Didi Needleful
PlotShapes((Cross(DidiCurta,0) AND Cross(0,DidiLonga)) * shapeHollowCircle, colorYellow,0,0.25);
_SECTION_END();

Previous
Next Post »