Tuesday, July 7, 2015

Intraday Breakout Trading Setup


 



_SECTION_BEGIN("IBL");

    SetChartOptions(0,chartShowArrows|chartShowDates);
    ScanLookBack = Param("Scan Lookback", 2, 1, 25 );
    fraction= IIf(StrRight(Name(),3) == "", 3.2, 3.2);

_SECTION_END();

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

_SECTION_BEGIN("Up Trend Line");
   
    UTValue1=LastValue(Trough(L,0.5,2));
    UTValue2=LastValue(Trough(L,0.5,1));
    UTBar1=BarCount - 1 - LastValue(TroughBars(L,0.5 ,2));
    UTBar2=BarCount - 1 - LastValue(TroughBars(L,0.5 ,1)); 
    UpTrendLine = LineArray( UTBar1, UTValue1, UTBar2,UTValue2, 1 );
    UTLine = LineArray( UTBar1, UTValue1, UTBar2,UTValue2, 0 );
    Plot( UpTrendLine , _DEFAULT_NAME(), colorGreen,styleLine | styleNoTitle | styleNoLabel);
    Plot( UTLine , _DEFAULT_NAME(), colorGreen,styleLine | styleNoTitle | styleNoLabel);

_SECTION_END();


_SECTION_BEGIN("Down Trend Line");

    DTValue1=LastValue(Peak(H,0.5 ,2));
    DTValue2=LastValue(Peak(H,0.5 ,1));
    DTBar1=BarCount - 1 - LastValue(PeakBars(H,0.5 ,2));    
    DTBar2=BarCount - 1 - LastValue(PeakBars(H,0.5 ,1)); 
    DownTrendLine = LineArray( DTBar1, DTValue1, DTBar2,DTValue2, 1 );
    DTLine = LineArray( DTBar1, DTValue1, DTBar2,DTValue2, 0 );

    Plot( DownTrendLine ,_DEFAULT_NAME(), colorRed,styleLine | styleNoTitle | styleNoLabel);
    Plot( DTLine ,_DEFAULT_NAME(), colorRed,styleLine | styleNoTitle | styleNoLabel);
   
    PlotText("PV = " + WriteVal(DTValue2 ,fraction), LastValue(BarIndex())+2, (DTValue2 ), colorRed);
    PlotText("TV = " + WriteVal(UTValue2,fraction), LastValue(BarIndex())+2, UTValue2, colorGreen);
    PlotOHLC( UpTrendLine , UpTrendLine , DownTrendLine , DownTrendLine , "", colorYellow, styleCloud | styleNoRescale);
   
    Plot(LineArray( DTBar2, DTValue2, BarCount,DTValue2, 0 ),"",colorRed);
    Plot(LineArray( UTBar2, UTValue2, BarCount,UTValue2, 0 ),"",colorGreen);

_SECTION_END();

_SECTION_BEGIN("Pivot");

    YH = TimeFrameGetPrice("H", inDaily, -1);        // yesterdays high
    YL = TimeFrameGetPrice("L", inDaily, -1);        //                low
    YC = TimeFrameGetPrice("C", inDaily, -1);        //                close
    TO = TimeFrameGetPrice("O", inDaily);            // current day open

    //Normal Pivot
    PP = (YH + YL + YC) / 3;
    R1 = (2 * PP) - YL;
    R2 = PP + (YH - YL);
    R3 = YH + 2*(PP-YL);
    S1 = (2 * PP) - YH;
    S2 = PP - (YH - YL);
    S3 = YL - 2*(YH - PP) ;
   
_SECTION_END();

_SECTION_BEGIN("Title");

Title = EncodeColor(colorBlack)+ Date() + "   Close = " + EncodeColor(colorRed) +Close +
        EncodeColor(colorBlack) + "     Open = " + EncodeColor(colorBlack) + O +
        EncodeColor(colorBlack) + "     High = " + EncodeColor(5) + H +
        EncodeColor(colorBlack) + "      Low = " + EncodeColor(colorRed) + L +
        EncodeColor(colorBlack) + "     Volume = " + EncodeColor(colorOrange) + V + "\n\n"+
        EncodeColor(colorBlack) + "Pivot Point= " + EncodeColor(colorBlack) + PP +
        EncodeColor(colorBlack) + "     Day's Open= " + EncodeColor(colorBlack) + TO +"\n\n"+
        EncodeColor(colorGreen) + "If days open is greater than Pivot Point, market is in uptrend and \n"+EncodeColor(colorRed)+"if days Open is less than Pivot Point, market is in downtrend" +"\n\n"+
        EncodeColor(colorRed) + "R1= " + EncodeColor(colorBlack) + R1 +
        EncodeColor(colorRed) + "  R2= " + EncodeColor(colorBlack) + R2 +
        EncodeColor(colorRed) + "  R3= " + EncodeColor(colorBlack) + R3 +"\n"+
        EncodeColor(colorGreen) + "S1= " + EncodeColor(colorBlack) + S1 +
        EncodeColor(colorGreen) + "  S2= " + EncodeColor(colorBlack) + S2 +
        EncodeColor(colorGreen) + "  S3= " + EncodeColor(colorBlack) + S3 +"\n"+
        EncodeColor( colorBlack) +"____  _____  _______  _______  _______"+"\n";

_SECTION_END();

_SECTION_BEGIN("Target");

    CBuy = Cross(C,DownTrendLine);
    CSell = Cross(UpTrendLine ,C);

    baratbuy = ValueWhen(CBuy ,BarIndex()) ;
    baratsell = ValueWhen(CSell ,BarIndex()) ;

    PlotShapes(shapeUpTriangle* CBuy ,colorBlue,O,L);
    PlotShapes(shapeDownTriangle * CSell ,colorRed,O,H);


_SECTION_END();


_SECTION_BEGIN("Magnified Market Price");
FS=Param("Font Size",30,30,100,1);
GfxSelectFont("Arial", FS, 700, italic = False, underline = False, True );
GfxSetBkMode( colorBlack );
GfxSetTextColor( ParamColor("Color",colorYellow) );
Hor=Param("Horizontal Position",750,800,800,800);
Ver=Param("Vertical Position",27,27,27,27);
GfxTextOut(""+C,Hor , Ver );
YC=TimeFrameGetPrice("C",inDaily,-1);
DD=Prec(C-YC,2);
xx=Prec((DD/YC)*100,2);
GfxSelectFont("Arial", 12, 700, italic = False, underline = False, True );
GfxSetBkMode( colorBlack );
GfxSetTextColor(ParamColor("Color",colorYellow) );
GfxTextOut(""+DD+" ("+xx+"%)", Hor+5, Ver+45 );
_SECTION_END();

Friday, July 3, 2015

Harmonic Pattern

This is one another fantastic AFL which detects Harmonic patterns...................

....

_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorBlue)+" (" +  Name() + ") " + EncodeColor(colorBlue)+ Interval(2) +
 "  " + Date() +" " +" •  Open "+WriteVal(O,1.2)+"  •  "+"Hi "+WriteVal(H,1.2)+"  •  "+"Lo "+WriteVal(L,1.2)+"  •  "+
"Close "+WriteVal(C,1.2)+" ("+WriteVal(C-Ref(C,-1),1,0)+" "+WriteVal((C-Ref(C,-1))*100/Ref(C,-1),1.1)+ "%)  •  Vol= "+ WriteVal(V,1.0)

);


MAPeriod = Param("MA Period", 4, 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));


//////////////////////////////////////////////////////////////////////////
_SECTION_BEGIN("Peak");

PK = HaHigh > Ref(HaHigh,-1) AND Ref(HaHigh,1) < HaHigh;//Peak
PKV0 = ValueWhen(PK,HaHigh,0);//PeakValue0
PKV1 = ValueWhen(PK,HaHigh,1);//PeakValue1
PKV2 = ValueWhen(PK,HaHigh,2);//PeakValue2
MPK = PKV2 < PKV1 AND PKV1 > PKV0 ;//MajorPeak
MPKV = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,1); //MajorPeakValue
MPKD = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),1); //MajorPeakDate
SD = IIf(DateNum() < LastValue(MPKD,lastmode = True ), Null, LastValue(MPKV,Lastmode = True));//SelectedDate
Plot(SD, "LastMinorResistance",colorRed,styleLine,styleThick);

//PLOT THE SECOND LAST MAJOR PEAK RESISTANCE LINE
MPKV2 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, PKV1,2); //MajorPeakValue
MPKD2 = ValueWhen(Ref(MPK,-1) == 0 AND MPK == 1, DateNum(),2); //MajorPeakDate
SD2 = IIf(DateNum() < LastValue(MPKD2,lastmode = True ), Null, LastValue(MPKV2,Lastmode = True));//SelectedDate
Plot(SD2, "LastMajorResistance",colorRed,styleLine);
_SECTION_END();

_SECTION_BEGIN("Support");
SP = Ref(HaLow,1) > HaLow AND HaLow < Ref(HaLow,-1);//Peak
SPV0 = ValueWhen(SP,HaLow,0);//PeakValue0
SPV1 = ValueWhen(SP,HaLow,1);//PeakValue1
SPV2 = ValueWhen(SP,HaLow,2);//PeakValue2
MSP = SPV2 > SPV1 AND SPV1 < SPV0 ;//MajorPeak
MSPV = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,1);
MSPD = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),1);
SD = IIf(DateNum() < LastValue(MSPD,lastmode = True ), Null, LastValue(MSPV,Lastmode = True));
Plot(SD,"LastMinorSupport",colorGreen,styleLine,styleThick);


MSPV2 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, SPV1,2);
MSPD2 = ValueWhen(Ref(MSP,-1) == 0 AND MSP == 1, DateNum(),2);
SD2 = IIf(DateNum() < LastValue(MSPD2,lastmode = True ), Null, LastValue(MSPV2,Lastmode = True));
Plot(SD2,"LastMajorSupport",colorGreen,styleLine);

_SECTION_END();



_SECTION_BEGIN("");
R = RSI(3);
SK = StochK(8, 3);
SD = StochD(8, 3, 3);
MH = MACD(8, 16) - Signal(8, 16, 5);
e= EMA(C,62);
//Conditions for Buying

Cond1 = ValueWhen(C,O<C);
Cond2 = R > 20;
Cond3 = SD > 20 ;
Cond4 = MH > 0 ;
Cond5 = e > Ref(e,-1);
//Conditions for Selling

Cond6 = ValueWhen(C,O>C);
Cond7 = R < 80;
Cond8 = SD < 80;
Cond9 = MH < 0 ;
Cond10 = e < Ref(e,-1);
Buy =  Cond1 AND Cond2 AND Cond3 AND Cond4 AND Cond5;
Sell =  Cond6 AND Cond7 AND Cond8 AND Cond9 AND Cond10;

Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);

/*
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-20);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-30);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-25);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=20);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=30);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-25);


SetPositionSize(300,spsShares);
ApplyStop(0,1,10,1);
//-----------end--------------
Long=Flip(Buy,Sell);
Shrt=Flip(Sell,Buy);

BuyPrice=ValueWhen(Buy,C);
SellPrice=ValueWhen(Sell,C);


Edc=(
WriteIf (Buy AND Ref(shrt,-1), " BUY@ "+C+"  ","")+
WriteIf (Sell AND Ref(Long,-1), " SEll@ "+C+"  ","")+
WriteIf(Sell , "Last Trade Profit Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Last trade Profit Rs."+(SellPrice-C)+"","")+
WriteIf(Long AND NOT Buy, "Trade: Long Profit: "+WriteVal((C-BuyPrice))+"","")+
WriteIf(shrt AND NOT Sell, "Trade: Short Profit: "+WriteVal((SellPrice-C))+"",""));

dist = 3*ATR(10);
dist1 = 3*ATR(10);
for( i = 0; i < BarCount; i++ )
{
 if( Buy[i] )
 {
  PlotText( "\nBuy@:" + C[ i ], i, C[ i ]-dist[i], colorGreen, colorDarkOliveGreen );
 }
 if( Sell[i] )
 {
  PlotText( "Sell@:" + C[ i ], i, C[ i ]+dist1[i], colorRed, colorDarkOliveGreen );
 }

}*/

_SECTION_END();

_SECTION_BEGIN("Background text");
C11=ParamColor("up panel",colorViolet );
C12=ParamColor("dn panel",colorGreen );
C13=Param("fonts",20,10,30,1 );
C14=Param("left-right",2.1,1.0,5.0,0.1 );
C15=Param("up-down",12,1,20,1 );
Miny = Status("axisminy");
Maxy = Status("axismaxy");
lvb = Status("lastvisiblebar");
fvb = Status("firstvisiblebar");
pxwidth = Status("pxwidth");
pxheight = Status("pxheight");
GfxSetBkMode( 0 );
GfxSetOverlayMode(1);
GfxGradientRect(0,0,pxwidth, pxheight, C11, C12 );
GfxSelectFont("Tahoma", Status("pxheight")/C13 );
GfxSetTextAlign( 6 );
GfxTextOut( "LTP "+WriteVal(C,1.2), Status("pxwidth")/C14, Status("pxheight")/C15);
GfxSelectFont("Tahoma", Status("pxheight")/C13*0.5 );
GfxTextOut( " amibrokertn.blogspot.in", Status("pxwidth")/C14, Status("pxheight")/C15*4 );
GfxSelectFont("MS Sans Serif", 10, 500, False, False, 0);
GfxSetTextColor(colorYellow);
//GfxTextOut(""+edc+"", Status("pxwidth")/1.15, Status("pxheight")/C15*0.3 );

/*                     HARMONIC PATTERN DETECTION                      

*/


_SECTION_BEGIN("Gartley");

GBmin = Param("Swing B Min.",0.55,0.3,1,0.01);
GBmax = Param("Swing B Max.",0.72,0.4,1,0.01);
GCmin = Param("Swing C Min.",0.38,0.3,1.27,0.01);
GCmax = Param("Swing C Max.",1.0,0.4,1.27,0.01);
GDmin = Param("Swing D Min.(XA)",0.55,0.3,1,0.01);
GDmax = Param("Swing D Max.(XA)",1.0,0.4,1.0,0.01);

_SECTION_END();

_SECTION_BEGIN("Bat");

BatBmin = Param("Swing B Min.",0.38,0.3,1,0.01);
BatBmax = Param("Swing B Max.",0.55,0.4,1,0.01);
BatCmin = Param("Swing C Min.",0.38,0.3,1.62,0.01);
BatCmax = Param("Swing C Max.",1.27,0.4,1.62,0.01);
BatDmin = Param("Swing D Min.(XA)",0.5,0.3,1,0.01);
BatDmax = Param("Swing D Max.(XA)",1.0,0.4,1.0,0.01);

_SECTION_END();

_SECTION_BEGIN("Butterfly");

BtBmin = Param("Swing B Min.",0.55,0.3,1,0.01);
BtBmax = Param("Swing B Max.",0.9,0.4,1,0.01);
BtCmin = Param("Swing C Min.",0.38,0.3,1.62,0.01);
BtCmax = Param("Swing C Max.",1.27,0.4,1.62,0.01);
BtDmin = Param("Swing D Min.(XA)",1,1,1.8,0.01);
BtDmax = Param("Swing D Max.(XA)",1.8,1,1.8,0.01);                        // Max XA of Butterfly = (1.0 - 1.618)

_SECTION_END();

_SECTION_BEGIN("Crab");

CBmin = Param("Swing B Min.",0.38,0.3,1,0.01);
CBmax = Param("Swing B Max.",0.65,0.4,1,0.01);
CCmin = Param("Swing C Min.",0.38,0.3,1.62,0.01);
CCmax = Param("Swing C Max.",1.270,0.4,1.62,0.01);
CDmin = Param("Swing D Min.(XA)",1.25,1,1.8,0.01);
CDmax = Param("Swing D Max.(XA)",1.8,1,2,0.01);

_SECTION_END();

_SECTION_BEGIN("AB=CD");

abcd_Cmin = Param("Swing C Min.",0.3,        0.3    ,    1,        0.01);
abcd_Cmax = Param("Swing C Max.",0.8,        0.8    ,    1,        0.01);
abcd_Dmin = Param("Swing D Min.",1.2,        1,        2.7,    0.01);
abcd_Dmax = Param("Swing D Max.",3.7,        1,        4,        0.01);

_SECTION_END();

_SECTION_BEGIN("Patterns");
  
//strength = Param("Strength",5,2,15,1);                                    // Best use: 3, 4, 5
strength = Param("BARS of each LINE",5,2,15,1);                            // So luong bar cho moi duong XA, AB, BC,
bu = ParamToggle("Bullish Pattern","Off|On",1);                            // So bar/lines se quyet dinh. mo^ hinh` duoc ve the' nao`
be = ParamToggle("Bearish Pattern","Off|On",1);

bi = Cum(1)-1;

function GetTop(bars)                                                         // Lay' gia' tri cao nhat' = di?nh
    {
        Top = H == HHV(H,2*bars) AND Ref(HHV(H,bars),bars) < H;
        Top = Top AND LastValue(bi)-ValueWhen(Top,bi) > bars;
        return Top;
    }

function GetValley(bars)                                                    // La'y gia tri thap' nhat' = day'
    {
        Valley = L == LLV(L,2*bars) AND Ref(LLV(L,bars),bars) > L;
        Valley = Valley AND LastValue(bi)-ValueWhen(Valley,bi) > bars;
        return Valley;
    }


// Build fractals array

P1 = GetTop(strength);                                        // so' bar cho 1 duong` XA, AB, BC, CD
V1 = GetValley(Strength);

P1 = IIf(P1,IIf(ValueWhen(P1,bi,2) < ValueWhen(V1,bi),P1,IIf(ValueWhen(P1,H,2) > H,False,P1)),P1);
P1 = IIf(P1 AND ValueWhen(P1,bi,0) > bi,IIf(ValueWhen(P1,bi,0) < ValueWhen(V1,bi,0),IIf(ValueWhen(P1,H,0) >= H,False,P1),P1),P1);
V1 = IIf(V1,IIf(ValueWhen(V1,bi,2) < ValueWhen(P1,bi),V1,IIf(ValueWhen(V1,L,2)<L,False,V1)),V1);
V1 = IIf(V1 AND ValueWhen(V1,bi,0) > bi ,IIf(ValueWhen(V1,bi,0) < ValueWhen(P1,bi,0),IIf(ValueWhen(V1,L,0) <= L, False,V1),V1),V1);


P1H1 = ValueWhen(P1,H);
P1Bar1 = ValueWhen(P1,bi);
P1H2 = ValueWhen(P1,H,2);
P1Bar2 = ValueWhen(P1,bi,2);
V1L1 = ValueWhen(V1,L);
V1Bar1 = ValueWhen(V1,bi);
V1L2 = ValueWhen(V1,L,2);
V1Bar2 = ValueWhen(V1,bi,2);


//============================================
//                BULLISH PATTERNS
//============================================
/*
    Mo hinh Bullish:
    A    =    P1H2
    B    =    V1L1
    C    =    P1H1
    X    =    V1L2

*/

PTvalid = (P1Bar1 > V1Bar1 AND V1Bar1 > P1Bar2 AND P1bar2 > V1Bar2) AND P1; // Peaks and troughs are in order

myAX            =    P1H2-V1L2;
myAB            =    P1H2-V1L1;
myBC            =    P1H1-V1L1;

myAB_AX        =    myAB/ myAX;
myBC_AB        =    myBC/ myAB;  

BullGartley4         = PTvalid     AND     (    myAB_AX > GBmin    )         AND (    myAB_AX < GBmax    )
                                AND      (    myBC_AB > GCMin     )         AND (    myBC_AB < GCMax    );

BullBat4             = PTvalid     AND     (    myAB_AX > BatBmin )         AND (    myAB_AX < BatBmax    )
                                AND     (    myBC_AB > BatCMin )         AND (    myBC_AB < BatCMax    );

BullButterfly4     = PTvalid     AND     (    myAB_AX > BtBmin )         AND (    myAB_AX < BtBMax    )
                                AND      (    myBC_AB > BtCmin )         AND (    myBC_AB < BtCmin     );

BullCrab4             = PTvalid     AND     (    myAB_AX > CBmin )              AND (    myAB_AX < CBmax     )
                                AND      (    myBC_AB > CCmin )         AND (    myBC_AB < CCmax    );

BullABCD4            = PTvalid AND     (    myBC_AB > abcd_Cmin)     AND (    myBC_AB < abcd_Cmax    );

strPattern = "";

//==================================================
//                 BULLISH ABCD
//     Bullish pattern found. D retracement level is not evaluated
//==================================================
    dHigh        =        HighestSince(BullABCD4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BullABCD4,L);
  
    myC            =        ValueWhen(BullABCD4,P1H1);
    myB            =        ValueWhen(BullABCD4,V1L1);
    myA            =        ValueWhen(BullABCD4,P1H2);
    myX            =        ValueWhen(BullABCD4,V1L2);
    myCB        =        myC - myB;

    my_d_min    =        myCB    *    abcd_DMin ;                    // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myCB    *    abcd_DMax ;
    my_Cd_min    =        myC - my_d_min;                       // Khoang dich chuyen cua duong Ad con.
    my_Cd_max    =        myC - my_d_max;

BullABCD         =         IIf(        ( dLow  <    my_Cd_min    )    AND        ( dLow    > my_Cd_max )  
                                AND    ( dHigh    <=    myC        )    AND        ( dLow    ==    L),
                                True, False
                            );

BullABCD        =        BullABCD    AND (dLow        <    myB);


//==================================================
//                 BULLISH GARTLEY
//==================================================
    dHigh        =        HighestSince(BullGartley4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BullGartley4,L);

    myC            =        ValueWhen(BullGartley4,P1H1);
    myB            =        ValueWhen(BullGartley4,V1L1);
    myA            =        ValueWhen(BullGartley4,P1H2);
    myX            =        ValueWhen(BullGartley4,V1L2);
    myAX        =        myA - myX;

    my_d_min    =        myAX    *    GDmin;                            // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    GDMax;
    my_Ad_min    =        myA - my_d_min;                            // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA - my_d_max;

BullGartley     =         IIf(        ( dLow  <    my_Ad_min    )    AND        ( dLow    > my_Ad_max )  
                                AND    ( dHigh    <=    myC        )    AND        ( dLow    ==    L),
                                True, False
                            );
BullGartley     =        BullGartley     AND (dLow        <    myB);                        // diem D thap' hon B
strPattern     =        WriteIf(BullGartley,"BULLISH GARTLEY",strPattern);



//==================================================
//                 BULLISH BAT
//==================================================
    dHigh        =        HighestSince(BullBat4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BullBat4,L);  

    myC            =        ValueWhen(BullBat4,P1H1);
    myB            =        ValueWhen(BullBat4,V1L1);
    myA            =        ValueWhen(BullBat4,P1H2);
    myX            =        ValueWhen(BullBat4,V1L2);
    myAX        =        myA - myX;

    my_d_min    =        myAX    *    BatDmin;                        // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    BatDmax ;
    my_Ad_min    =        myA - my_d_min;                            // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA - my_d_max;

BullBat         =         IIf(        ( dLow  <    my_Ad_min    )    AND        ( dLow    > my_Ad_max )  
                                AND    ( dHigh    <=    myC        )    AND        ( dLow    ==    L),
                                True, False
                            );
BullBat         =        BullBat     AND (dLow        <    myB);            // diem d thap hon diem B
strPattern     =        WriteIf(BullBat,"BULLISH BAT",strPattern);


//==================================================
//                 BULLISH CRAB - CUA
//==================================================
    dHigh        =        HighestSince(BullCrab4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BullCrab4,L);

    myC            =        ValueWhen(BullCrab4,P1H1);
    myB            =        ValueWhen(BullCrab4,V1L1);
    myA            =        ValueWhen(BullCrab4,P1H2);
    myX            =        ValueWhen(BullCrab4,V1L2);
    myAX        =        myA - myX;

    my_d_min    =        myAX    *    CDmin ;                    // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    CDmax ;
    my_Ad_min    =        myA - my_d_min;                        // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA - my_d_max;

BullCrab         =         IIf(        ( dLow  <    my_Ad_min    )    AND        ( dLow    > my_Ad_max )  
                                AND    ( dHigh    <=    myC        )    AND        ( dLow    ==    L),
                                True, False
                            );
BullCrab         =        BullCrab     AND (dLow        <    myX);                    // diem D thap' hon X
strPattern     =        WriteIf(BullCrab ,"BULLISH CRAB",strPattern);


//==================================================
//                 BULLISH  BUTTTERFLY
//==================================================
    dHigh        =        HighestSince(BullButterfly4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BullButterfly4,L);

    myC            =        ValueWhen(BullButterfly4,P1H1);
    myB            =        ValueWhen(BullButterfly4,V1L1);
    myA            =        ValueWhen(BullButterfly4,P1H2);
    myX            =        ValueWhen(BullButterfly4,V1L2);
    myAX        =        myA - myX;

    my_d_min    =        myAX    *    BtDmin ;                                // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    BtDmax ;
    my_Ad_min    =        myA - my_d_min;                                    // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA - my_d_max;

BullButterfly     =         IIf(        ( dLow  <    my_Ad_min    )    AND        ( dLow    > my_Ad_max )  
                                    AND    ( dHigh    <=    myC        )    AND        ( dLow    ==    L),
                                True, False
                                );
BullButterfly     =        BullButterfly     AND (dLow        <    myX);                    // diem D thap' hon X
strPattern         =        WriteIf(BullButterfly ,"BULLISH BUTTERFLY",strPattern);



//==========================================================
//   VE DUONG CHO MO HINH BULLISH ABCB
//==========================================================
BullHar4     =  BullABCD4;
BullHar     =  BullABCD;

Point4 = IIf(BullHar,ValueWhen(BullHar4,bi),Null);
BullHar = IIf(BullHar, IIf(Point4 == ValueWhen(BullHar,point4,0) AND ValueWhen(BullHar,bi,0) > bi ,False,BullHar),BullHar);

A = ValueWhen(BullHar4,P1H2);
Abar = ValueWhen(BullHar4,P1bar2);
B = ValueWhen(BullHar4,V1L1);
Bbar = ValueWhen(BullHar4,V1bar1);
C1 = ValueWhen(BullHar4,P1H1);
C1bar = ValueWhen(BullHar4,P1bar1);
D = ValueWhen(BullHar,L);
Dbar = ValueWhen(BullHar,bi);

BCdAB = (C1-B)/(A-B);
BCdCD = (C1-D)/(C1-B);

PlotPattern = Dbar > C1bar;

if(LastValue(PlotPattern) AND bu)
{
        ColorX = colorGreen;
    // Ve cac duong AB, BC, CD
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(Bbar),LastValue(B)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(C1bar),LastValue(C1),LastValue(Dbar),LastValue(D)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleDashed);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(Dbar),LastValue(D)),"",ColorX ,styleDashed);

    // Ve cac gia tri Fibo
        PlotText(NumToStr(LastValue(BCdAB),1.2),(LastValue(C1bar)+LastValue(Abar))/2,(LastValue(C1)+LastValue(A))/2,ColorX );
        PlotText(NumToStr(LastValue(BCdCD),1.2),(LastValue(Bbar)+LastValue(Dbar))/2,(LastValue(B)+LastValue(D))/2,ColorX );

    //---------- Viet cac diem X, A, B, C, D: by binhnd---------------------
        xlech        =    0;
        ylech         =     2;
        PlotText("A",LastValue(Abar)    +     xlech,    LastValue(A)    +    ylech,    ColorX );
        PlotText("B",LastValue(Bbar)    +     xlech,    LastValue(B)    -    ylech,    ColorX );
        PlotText("C",LastValue(C1bar)    +     xlech,    LastValue(C1)    +    ylech,    ColorX );
        PlotText("D",LastValue(Dbar)    +     xlech,    LastValue(D)    -    ylech,    ColorX );

    //--------- Viet thuyet minh mo hinh: by binhnd--------------
        if (strPattern!="")
        {
            myStr            =    "Pattern: BULLISH AB=CD";
            toadoX            =    LastValue(Abar);
            toadoY            =    LastValue(D);

            PlotText(myStr,toadoX,toadoY,ColorX );
        }

}            //    end of Ve duong` bullish abcd



//==========================================================
//   VE DUONG CHO MO HINH BULLISH BAT, GARTLEY, BUTTERFLY, CRAB
//==========================================================


BullHar4 = BullGartley4 OR BullButterfly4 OR BullBat4 OR BullCrab4 ;
BullHar = BullGartley OR BullButterfly OR BullBat OR BullCrab;

Point4 = IIf(BullHar,ValueWhen(BullHar4,bi),Null);
BullHar = IIf(BullHar, IIf(Point4 == ValueWhen(BullHar,point4,0) AND ValueWhen(BullHar,bi,0) > bi ,False,BullHar),BullHar);

X = ValueWhen(BullHar4,V1L2);
Xbar = ValueWhen(BullHar4,V1Bar2);
A = ValueWhen(BullHar4,P1H2);
Abar = ValueWhen(BullHar4,P1bar2);
B = ValueWhen(BullHar4,V1L1);
Bbar = ValueWhen(BullHar4,V1bar1);
C1 = ValueWhen(BullHar4,P1H1);
C1bar = ValueWhen(BullHar4,P1bar1);
D = ValueWhen(BullHar,L);
Dbar = ValueWhen(BullHar,bi);

ABdXA = (A-B)/(A-X);
BCdAB = (C1-B)/(A-B);
ADdXA = (A-D)/(A-X);
BCdCD = (C1-D)/(C1-B);

PlotPattern = Dbar > C1bar;

if(LastValue(PlotPattern) AND bu)
{
            ColorX    = colorBlue;
        // Ve cac duong XA, AB, BC, CD
            Plot( LineArray(LastValue(Xbar),LastValue(X),LastValue(Abar),LastValue(A)),"",ColorX,styleThick);
            Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(Bbar),LastValue(B)),"",ColorX,styleThick);
            Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(C1bar),LastValue(C1)),"",ColorX,styleThick);
            Plot(LineArray(LastValue(C1bar),LastValue(C1),LastValue(Dbar),LastValue(D)),"",ColorX,styleThick);
            Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Bbar),LastValue(B)),"",ColorX,styleDashed);
            Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Abar),LastValue(A)),"",ColorX,styleThick);
            Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(C1bar),LastValue(C1)),"",ColorX,styleDashed);
            Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(Dbar),LastValue(D)),"",ColorX,styleDashed);
            Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Dbar),LastValue(D)),"",ColorX,styleDashed);

        // Ve cac gia tri Fibo
            PlotText(NumToStr(LastValue(ABdXA),1.2),(LastValue(Bbar)+LastValue(Xbar))/2,(LastValue(B)+LastValue(X))/2,ColorX);
            PlotText(NumToStr(LastValue(BCdAB),1.2),(LastValue(C1bar)+LastValue(Abar))/2,(LastValue(C1)+LastValue(A))/2,ColorX);
            PlotText(NumToStr(LastValue(ADdXA),1.2) ,(LastValue(Dbar)+LastValue(Xbar))/2,(LastValue(D)+LastValue(X))/2,ColorX);
            PlotText(NumToStr(LastValue(BCdCD),1.2),(LastValue(Bbar)+LastValue(Dbar))/2,(LastValue(B)+LastValue(D))/2,ColorX);

        //---------- Viet cac diem X, A, B, C, D: by binhnd---------------------
            xlech        =    0;
            ylech         =     2;
            PlotText("X",LastValue(Xbar)    +     xlech,    LastValue(X)    -    ylech,    ColorX);
            PlotText("A",LastValue(Abar)    +     xlech,    LastValue(A)    +    ylech,    ColorX);
            PlotText("B",LastValue(Bbar)    +     xlech,    LastValue(B)    -    ylech,    ColorX);
            PlotText("C",LastValue(C1bar)    +     xlech,    LastValue(C1)    +    ylech,    ColorX);
            PlotText("D",LastValue(Dbar)    +     xlech,    LastValue(D)    -    ylech,    ColorX);

        //--------- Viet thuyet minh mo hinh: by binhnd--------------
            if (strPattern!="")
            {
                strPattern     =     "Pattern: " + strPattern;
                toadoX            =    (LastValue(Dbar)+LastValue(Xbar))/2;
                toadoY            =    (LastValue(D)+LastValue(X))/2;

                PlotText(strPattern,toadoX,toadoY-2,ColorX);
            }

}            // end of Ve duong cho cac mo hinh Crab, Butterfly, Bat


//=============================================================
//                BEARISH PATTERNS
//=============================================================

PTvalid = (V1Bar1 > P1Bar1 AND P1Bar1 > V1Bar2 AND V1Bar2 > P1Bar2) AND V1;

/*=====================
        X     =     P1H2                     Trong mo hinh` bear: Die^m X cao hon diem A. MyAX = X-> A
        A    =    V1L2
        B    =    P1H1
        C    =    V1L1

=======================*/
myAX            =    P1H2-V1L2;              
myAB            =    P1H1-V1L2;
myBC            =    P1H1-V1L1;

myAB_AX        =    myAB/ myAX;
myBC_AB        =    myBC/ myAB;  

BearGartley4         = PTvalid     AND     (    myAB_AX > GBmin    )         AND (    myAB_AX < GBmax    )
                                AND      (    myBC_AB > GCMin     )         AND (    myBC_AB < GCMax    );

BearBat4             = PTvalid     AND     (    myAB_AX > BatBmin )         AND (    myAB_AX < BatBmax    )
                                AND     (    myBC_AB > BatCMin )         AND (    myBC_AB < BatCMax    );

BearButterfly4     = PTvalid     AND     (    myAB_AX > BtBmin )         AND (    myAB_AX < BtBMax    )
                                AND      (    myBC_AB > BtCmin )         AND (    myBC_AB < BtCmin     );

BearCrab4             = PTvalid     AND     (    myAB_AX > CBmin )              AND (    myAB_AX < CBmax     )
                                AND      (    myBC_AB > CCmin )         AND (    myBC_AB < CCmax    );

BearABCD4            = PTvalid AND     (    myBC_AB > abcd_Cmin)     AND (    myBC_AB < abcd_Cmax    );

strPattern = "";



//==========================================================
//                 BEARISH ABCD
//     Bearish pattern found. D retracement level is not evaluated
//==========================================================
    dHigh        =        HighestSince(BearABCD4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BearABCD4,L);
  
    myA            =        ValueWhen(BearABCD4,V1L2);
    myB            =        ValueWhen(BearABCD4,P1H1);
    myC            =        ValueWhen(BearABCD4,V1L1);
    myCB        =        myB - myC;

    my_d_min    =        myCB    *    abcd_DMin ;                    // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myCB    *    abcd_DMax ;
    my_Cd_min    =        myC + my_d_min;                       // Khoang dich chuyen cua duong Ad con.
    my_Cd_max    =        myC + my_d_max;

BearABCD         =         IIf(        ( dHigh      >    my_Cd_min    )    AND        ( dHigh    < my_Cd_max )  
                                AND    ( dLow        >=    myC            )    AND        ( dHigh    ==    H),
                                True, False
                            );

BearABCD        =        BearABCD    AND (dHigh        >    myB);

//=============================================================
//                BEARISH GARTLEY
//=============================================================
    dHigh        =        HighestSince(BearGartley4,H);        // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BearGartley4,L);

    myX            =        ValueWhen(BearGartley4,P1H2);
    myA            =        ValueWhen(BearGartley4,V1L2);
    myAX        =        myX - myA;

    myB            =        ValueWhen(BearGartley4,P1H1);
    myC            =        ValueWhen(BearGartley4,V1L1);


    my_d_min    =        myAX    *    GDmin;                        // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    GDMax;
    my_Ad_min    =        myA     +     my_d_min;                    // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA     +     my_d_max;

BearGartley     =         IIf(        ( dHigh    >    my_Ad_min    )    AND        ( dHigh    < my_Ad_max )  
                                AND    ( dLow        >=    myC            )    AND        ( dHigh    ==    H),
                                True, False
                            );
BearGartley     =        BearGartley     AND (dHigh        >    myB);                        // diem D cao hon B
strPattern     =        WriteIf(BearGartley ,"BEARISH GARTLEY",strPattern);

//=============================================================
//                BEARISH BAT
//=============================================================
    dHigh        =        HighestSince(BearBat4,H);        // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BearBat4,L);

    myX            =        ValueWhen(BearBat4,P1H2);
    myA            =        ValueWhen(BearBat4,V1L2);
    myAX        =        myX - myA;

    myB            =        ValueWhen(BearBat4,P1H1);
    myC            =        ValueWhen(BearBat4,V1L1);


    my_d_min    =        myAX    *    BatDmin ;                        // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    BatDMax ;
    my_Ad_min    =        myA     +     my_d_min;                    // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA     +     my_d_max;

BearBat         =         IIf(        ( dHigh    >    my_Ad_min    )    AND        ( dHigh    < my_Ad_max )  
                                AND    ( dLow        >=    myC            )    AND        ( dHigh    ==    H),
                                True, False
                            );
BearBat         =        BearBat     AND (dHigh        >    myB);                        // diem D cao hon B
strPattern     =        WriteIf(BearBat ,"BEARISH BAT",strPattern);


//=============================================================
//                BEARISH BUTTERFLY
//=============================================================
    dHigh        =        HighestSince(BearButterfly4,H);        // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BearButterfly4,L);

    myX            =        ValueWhen(BearButterfly4,P1H2);
    myA            =        ValueWhen(BearButterfly4,V1L2);
    myAX        =        myX - myA;

    myB            =        ValueWhen(BearButterfly4,P1H1);
    myC            =        ValueWhen(BearButterfly4,V1L1);


    my_d_min    =        myAX    *    BtDmin ;                        // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    BtDmax ;
    my_Ad_min    =        myA     +     my_d_min;                        // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA     +     my_d_max;

BearButterfly =         IIf(        ( dHigh    >    my_Ad_min    )    AND        ( dHigh    < my_Ad_max )  
                                AND    ( dLow        >=    myC            )    AND        ( dHigh    ==    H),
                                True, False
                            );
BearButterfly    =        BearButterfly     AND (dHigh        >    myX);                        // diem D cao hon X
strPattern        =        WriteIf(BearButterfly ,"BEARISH BUTTERFLY",strPattern);



//=============================================================
//                BEARISH CRAB
//=============================================================
    dHigh        =        HighestSince(BearCrab4,H);                // Tinh' gia' tri min, max cua duong Ad. Duong Ad la duong con cua AD
    dLow         =         LowestSince(BearCrab4,L);

    myX            =        ValueWhen(BearCrab4,P1H2);
    myA            =        ValueWhen(BearCrab4,V1L2);
    myAX        =        myX - myA;

    myB            =        ValueWhen(BearCrab4,P1H1);
    myC            =        ValueWhen(BearCrab4,V1L1);


    my_d_min    =        myAX    *    CDmin ;                        // Tinh' gia' tri cua duong Ad con. Khi gia' giam? tu` tre^n xuong' thi` max -> min
    my_d_max    =        myAX    *    CDmax ;
    my_Ad_min    =        myA     +     my_d_min;                        // Khoang dich chuyen cua duong Ad con.
    my_Ad_max    =        myA     +     my_d_max;

BearCrab         =         IIf(        ( dHigh    >    my_Ad_min    )    AND        ( dHigh    < my_Ad_max )  
                                AND    ( dLow        >=    myC            )    AND        ( dHigh    ==    H),
                                True, False
                            );
BearCrab         =        BearCrab     AND (dHigh        >    myX);                        // diem D cao hon X
strPattern     =        WriteIf(BearCrab ,"BEARISH CRAB",strPattern);



//==========================================================
//   VE DUONG CHO MO HINH BEARISH ABCD
//==========================================================


BearHar4 = BearABCD4;
BearHar = BearABCD;

Point4 = IIf(BearHar,ValueWhen(BearHar4,bi),Null);
BearHar = IIf(BearHar, IIf(Point4 == ValueWhen(BearHar,point4,0) AND ValueWhen(BearHar,bi,0) > bi ,False,BearHar),BearHar);

A = ValueWhen(BearHar4,V1L2);
Abar = ValueWhen( BearHar4,V1bar2);
B = ValueWhen(BearHar4,P1H1);
Bbar = ValueWhen(BearHar4,P1bar1);
C1 = ValueWhen(BearHar4,V1L1);
C1bar = ValueWhen(BearHar4,V1bar1);
D = ValueWhen(BearHar,H);
Dbar = ValueWhen(BearHar,bi);

BCdAB = (B-C1)/(B-A);
BCdCD = (D-C1)/(B-C1);

PlotPattern = Dbar > C1bar;

//--------- Ve duong ------------------
if(LastValue(Plotpattern) AND be)
{
        ColorX = colorYellow;
    // Ve duong AB, BC
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(Bbar),LastValue(B)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(C1bar),LastValue(C1),LastValue(Dbar),LastValue(D)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleDashed);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(Dbar),LastValue(D)),"",ColorX ,styleDashed);

    // Viet cac gia tri Fibo tren duong AB, BC
        PlotText(NumToStr(LastValue(BCdAB),1.2),(LastValue(C1bar)+LastValue(Abar))/2,(LastValue(C1)+LastValue(A))/2,ColorX );
        PlotText(NumToStr(LastValue(BCdCD),1.2) ,(LastValue(Dbar)+LastValue(Bbar))/2,(LastValue(D)+LastValue(B))/2,ColorX );

    //---------- Viet cac diem A, B, C, D: by binhnd---------------------
        xlech        =    -1;
        ylech         =     1;
        PlotText("A",LastValue(Abar)    +     xlech,    LastValue(A)    -    ylech,    ColorX );
        PlotText("B",LastValue(Bbar)    +     xlech,    LastValue(B)    +    ylech,    ColorX );
        PlotText("C",LastValue(C1bar)    +     xlech,    LastValue(C1)    -    ylech,    ColorX );
        PlotText("D",LastValue(Dbar)    +     xlech,    LastValue(D)    +    ylech,    ColorX );

    //--------- Viet thuyet minh mo hinh: by binhnd--------------
        if (strPattern!="")
            {
                myStr            =    "Pattern: BEARISH AB=CD";
                toadoaX        =    LastValue(Abar);
                toadoY            =    LastValue(D);

                PlotText(myStr,toadoaX,toadoY+1,ColorX );
            }
  
}            // end of VE DUONG CHO MO HINH BEARISH ABCD


//==========================================================
//   VE DUONG CHO MO HINH BEARISH BAT, GARTLEY, BUTTERFLY, CRAB
//==========================================================

BearHar4 = BearGartley4 OR BearButterfly4 OR BearBat4 OR BearCrab4 ;
BearHar = BearGartley OR BearButterfly OR BearBat OR BearCrab ;

Point4 = IIf(BearHar,ValueWhen(BearHar4,bi),Null);
BearHar = IIf(BearHar, IIf(Point4 == ValueWhen(BearHar,point4,0) AND ValueWhen(BearHar,bi,0) > bi ,False,BearHar),BearHar);

X = ValueWhen(BearHar4,P1H2);
Xbar = ValueWhen(BearHar4,P1Bar2);
A = ValueWhen(BearHar4,V1L2);
Abar = ValueWhen( BearHar4,V1bar2);
B = ValueWhen(BearHar4,P1H1);
Bbar = ValueWhen(BearHar4,P1bar1);
C1 = ValueWhen(BearHar4,V1L1);
C1bar = ValueWhen(BearHar4,V1bar1);
D = ValueWhen(BearHar,H);
Dbar = ValueWhen(BearHar,bi);

ABdXA = (B-A)/(X-A);
BCdAB = (B-C1)/(B-A);
ADdXA = (D-A)/(X-A);
BCdCD = (D-C1)/(B-C1);

PlotPattern = Dbar > C1bar;

//--------- Ve duong ------------------
if(LastValue(Plotpattern) AND be)
{
        ColorX = colorRed;
    // Ve duong XA, AB, BC
        Plot( LineArray(LastValue(Xbar),LastValue(X),LastValue(Abar),LastValue(A)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(Bbar),LastValue(B)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(C1bar),LastValue(C1),LastValue(Dbar),LastValue(D)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Bbar),LastValue(B)),"",ColorX ,styleDashed);
        Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Abar),LastValue(A)),"",ColorX ,styleThick);
        Plot(LineArray(LastValue(Abar),LastValue(A),LastValue(C1bar),LastValue(C1)),"",ColorX ,styleDashed);
        Plot(LineArray(LastValue(Bbar),LastValue(B),LastValue(Dbar),LastValue(D)),"",ColorX ,styleDashed);
        Plot(LineArray(LastValue(Xbar),LastValue(X),LastValue(Dbar),LastValue(D)),"",ColorX ,styleDashed);

    // Viet cac gia tri Fibo tren duong XA, AB, BC
        PlotText(NumToStr(LastValue(ABdXA),1.2),(LastValue(Bbar)+LastValue(Xbar))/2,(LastValue(B)+LastValue(X))/2,ColorX );
        PlotText(NumToStr(LastValue(BCdAB),1.2),(LastValue(C1bar)+LastValue(Abar))/2,(LastValue(C1)+LastValue(A))/2,ColorX );
        PlotText(NumToStr(LastValue(BCdCD),1.2) ,(LastValue(Dbar)+LastValue(Bbar))/2,(LastValue(D)+LastValue(B))/2,ColorX );
        PlotText(NumToStr(LastValue(ADdXA),1.2) ,(LastValue(Dbar)+LastValue(Xbar))/2,(LastValue(D)+LastValue(X))/2,ColorX );

    //---------- Viet cac diem X, A, B, C, D: by binhnd---------------------
        xlech        =    -1;
        ylech         =     1;
        PlotText("X",LastValue(Xbar)    +     xlech,    LastValue(X)    +    ylech,    ColorX );
        PlotText("A",LastValue(Abar)    +     xlech,    LastValue(A)    -    ylech,    ColorX );
        PlotText("B",LastValue(Bbar)    +     xlech,    LastValue(B)    +    ylech,    ColorX );
        PlotText("C",LastValue(C1bar)    +     xlech,    LastValue(C1)    -    ylech,    ColorX );
        PlotText("D",LastValue(Dbar)    +     xlech,    LastValue(D)    +    ylech,    ColorX );

    //--------- Viet thuyet minh mo hinh: by binhnd--------------
        if (strPattern!="")
            {
                strPattern     =     "Pattern: " + strPattern;
                toadoaX        =    (LastValue(Dbar)+LastValue(Xbar))/2;
                toadoY            =    (LastValue(D)+LastValue(X))/2;

                PlotText(strPattern,toadoaX,toadoY+1,ColorX );
            }
  
}            // end of VE DUONG CHO MO HINH BEARISH BAT, GARTLEY, BUTTERFLY, CRAB




//=================================
// Show diem ho^~ tro. va` khang' cu. ko?
//=================================

plotFractals = ParamToggle("Plot Fractals","Off|On",1);              
if(PlotFractals)
{
    PlotShapes(shapeSmallCircle*P1,colorRed,0,H,10);
    PlotShapes(shapeSmallCircle*V1,colorBlue,0,L,-10);
}



//==============================================
// DAT DIEU KIEN cho TIM KIEM BULL
//==============================================
dkBull = False;
ListBull         =     ParamList("Type of Bullish", "None|AB=CD|Gartley|Butterfly|Bat|Crab|All Patterns", 6);
    if     (    ListBull == "None"        )        dkBull =     True;
    if (    ListBull =="AB=CD"        )         dkBull    =    BullABCD ;
    if (    ListBull =="Gartley"        )         dkBull    =    BullGartley ;
    if (    ListBull =="Butterfly"    )         dkBull    =    BullButterfly ;
    if (    ListBull =="Bat"            )         dkBull    =    BullBat ;
    if (    ListBull =="Crab"            )         dkBull    =    BullCrab ;
    if (    ListBull =="All Patterns")         dkBull    =    (BullABCD) OR (BullGartley) OR (BullButterfly ) OR (BullBat ) OR (BullCrab);

//==============================================
// DAT DIEU KIEN cho TIM KIEM BEAR
//==============================================
dkBear = False;
ListBear         =     ParamList("Type of Bearish", "None|AB=CD|Gartley|Butterfly|Bat|Crab|All Patterns", 0);
    if     (    ListBear == "None"        )        dkBear =     True;
    if (    ListBear =="AB=CD"        )         dkBear    =    BearABCD ;
    if (    ListBear =="Gartley"        )         dkBear    =    BearGartley ;
    if (    ListBear =="Butterfly"    )         dkBear    =    BearButterfly ;
    if (    ListBear =="Bat"            )         dkBear    =    BearBat ;
    if (    ListBear =="Crab"            )         dkBear =    BearCrab ;
    if (    ListBear =="All Patterns")         dkBear =    (BearABCD ) OR (BearGartley ) OR (BearButterfly ) OR (BearBat ) OR (BearCrab );
//===============================

AddColumn(V,"Volume",1.0);
Filter = (dkBull) AND (dkBear);

Nirvana

This is one of the finest afl which is also used for day trading.   
  
_SECTION_BEGIN("Background_Setting");
SetChartBkGradientFill( ParamColor("BgTop", colorBlack),
ParamColor("BgBottom", colorBlack),ParamColor("titleblock",colorDarkGrey ));
_SECTION_END();

_SECTION_BEGIN("colorMeBad");

flowerClose =EMA((O+H+L+C)/4,3); // Woodie
//flowerClose = EMA((Open+High+Low+Close)/4,3) ;
m = 17;
a=MA(flowerClose,m)+abs(MA(flowerClose,m)-Ref(MA(flowerClose,m),-1));
b=MA(flowerClose,m)+MA(flowerClose,m)-Ref(MA(flowerClose,m),-1);
balance=IIf(MA(flowerClose,m)<b,b,MA(flowerClose,m));
pma=balance;
sig = MA(2*balance-EMA(flowerClose,3),1);
//Plot(sig,"Signal", 7, 1);
s=(pma>sig);
pm=MA(flowerClose,5);
pmcolor=IIf(pm>Ref(pm,-1),colorLightYellow,colorRed);
Plot(pm,"", pmcolor,4);
_SECTION_END();

_SECTION_BEGIN("Haiken");

 Show_color = ParamToggle("Display CandleColor", "No|Yes", 1);
 r1 =5; //Param( "ColorFast avg", 5, 2, 200, 1 );
 r2 =10; //Param( "ColorSlow avg", 10, 2, 200, 1 );
 r3 =5; //Param( "ColorSignal avg", 5, 2, 200, 1 );

 Prd1=4; //Param("ATR Period",4,1,20,1);
 Prd2=7; //Param("Look Back",7,1,20,1);
 green = HHV(LLV(L,Prd1)+ATR(Prd1),Prd2);
 red = LLV(HHV(H,Prd1)-ATR(Prd1),Prd2);

 HaClose =EMA((O+H+L+C)/4,3); // Woodie
 //HaClose =(O+H+L+C)/4;
 HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
 HaHigh = Max( H, Max( HaClose, HaOpen ) );
 HaLow = Min( L, Min( HaClose, HaOpen ) );
 //HaClose = ( HaClose + HaOpen + HaHigh + HaLow )/4; // // Velvoort is using not original, but modified Heikin-Ashi close
 Temp = Max(High, HaOpen);
 Temp = Min(Low,HaOpen);


 m1=MACD(r1,r2);
 s1=Signal(r1,r2,r3);
 mycolor=IIf(m1<0 AND m1>s1, ColorRGB(230,230,0),IIf(m1>0 AND m1>s1,colorBrightGreen,IIf(m1>0 AND m1<s1,colorOrange,colorDarkRed)));

 if(Show_color)

 {
 ColorHighliter = myColor;
 SetBarFillColor( ColorHighliter );


 }

 //////////
 m1=MACD(r1,r2);
 s1=Signal(r1,r2,r3);
 mycolor=IIf(m1<0 AND m1>s1, ColorRGB(230,230,0),IIf(m1>0 AND m1>s1,colorWhite,IIf(m1>0 AND m1<s1,colorOrange,colorDarkRed)));
 if(Show_color)

 {
 ColorHighliter = mycolor;
 SetBarFillColor( ColorHighliter );
 }

 barColor=IIf(C>Green ,colorWhite,IIf(C < RED,colorRed,colorYellow));
 barColor2=IIf(Close > Open, colorWhite, colorRed);




 if( ParamToggle("Plot Normal Candle", "No,Yes", 1 ) )
 PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, " " , barcolor, styleCandle | styleThick );
 else
 PlotOHLC( Open, High, Low, Close, " " , barcolor2, styleCandle | styleThick );

 _SECTION_END();

_SECTION_BEGIN("Flower");
Show_color = ParamToggle("Display CandleColor", "No|Yes", 1);
r1 = Param( "ColorFast avg", 5, 2, 200, 1 );
r2 = Param( "ColorSlow avg", 10, 2, 200, 1 );
r3 = Param( "ColorSignal avg", 5, 2, 200, 1 );

Prd1=Param("ATR Period",4,1,20,1);
Prd2=Param("Look Back",7,1,20,1);
green = HHV(LLV(L,Prd1)+ATR(Prd1),Prd2);
red = LLV(HHV(H,Prd1)-ATR(Prd1),Prd2);
flowerClose = EMA((Open+High+Low+Close)/4,3) ;
flowerOpen = EMA((Ref(Open,-1) + Ref(flowerClose,-1))/2,3);
Temp = Max(High, flowerOpen);
flowerHigh = EMA(Max(Temp, flowerClose),3);
Temp = Min(Low,flowerOpen);
flowerLow = EMA(Min(Temp, flowerClose),3);



m1=MACD(r1,r2);
s1=Signal(r1,r2,r3);
mycolor=IIf(m1<0 AND m1>s1, colorYellow,IIf(m1>0 AND m1>s1,colorGreen,IIf(m1>0 AND m1<s1,colorCustom12,colorRed)));
if(Show_color)
{
ColorHighliter = myColor;
SetBarFillColor( ColorHighliter );


}

barColor=IIf(C>Green ,colorBrightGreen,IIf(C < RED,colorRed,colorWhite));


PlotOHLC( IIf(flowerOpen<flowerClose, flowerOpen, flowerClose),flowerHigh,flowerLow,IIf(flowerOpen<flowerClose, flowerClose, flowerOpen), "Close", barColor, styleNoTitle | styleCandle);



_SECTION_END();


//**********************************************************************************
//        Plot price horizontal line                                               *
//**********************************************************************************/


 _SECTION_BEGIN("Pivot Box");
 Hi=Param("High_Period",7,1,50,1);
 Lo=Param("Low_Period",7,1,50,1);
 A1=ExRemSpan(Ref(High,-2)==HHV(High,Hi),3);
 A2=ExRemSpan(Ref(Low,-2)==LLV(Low,Lo),3);
 A3=Cross(A1,0.9);
 A4=Cross(A2,0.9);
 TOP=Ref(HaHigh,-BarsSince(A3));


 breakoutLine=Param("BrOutLineLength",10,2,30,0.1);
 upDaysback1 = breakoutLine;
 upFirstBar1 = BarCount - upDaysBack1;
 upst2=TOP;

 upYYY2=IIf(BarIndex() >= upFirstbar1,EndValue(upSt2),Null);

 Plot(upYYY2,"",ParamColor("BreakoutColor", colorOrange) ,ParamStyle("BreakoutLine",styleLine|styleThick|styleStaircase,maskAll));
 //Plot(top,"",11,styleDots+styleLine+styleThick);


 bot=Ref(HaLow,-BarsSince(A4));
 breakDownLine=Param("BrDownLineLength",10,2,30,0.1 );
 dnDaysback1 = breakDownLine;
 dnFirstBar1 = BarCount - dnDaysBack1;
 dnst2=BOT;

 dnYYY2=IIf(BarIndex() >= dnFirstbar1,EndValue(dnSt2),Null);


 Plot(dnYYY2,"",ParamColor("BreakDownColor", colorBrightGreen) ,ParamStyle("BreakdownLine",styleLine|styleThick|styleStaircase,maskAll));
 //Plot(bot,"",6,styleDots+styleLine);
 _SECTION_END();

_SECTION_BEGIN("Color_Me_Bad");
a =5; //Param("Average Pds", 5, 1, 10, 1 );
n =8; //Param("Short Pds", 8, 5, 21, 1 );
m =60; //Param("Long Pds", 60, 0, 90, 1 );

Var4 =(Low+High+2*Close)/4;
OP = EMA(Var4,a);
res1 = HHV(OP,n);

res2 =HHV(OP,m);
sup2 =LLV(OP,m);
sup1 =LLV(OP,n);


Linecolor1 = IIf(Op==sup1,ColorRGB(48,0,81),IIf(Op==res1,colorGreen,ColorRGB(80,80,80)));
Linecolor2 = IIf(Op==sup1,ColorRGB(38,0,60),IIf(Op==res1,colorGreen,colorDarkGrey));
Linecolor3 = IIf(Op==sup1,ColorRGB(27,0,70),IIf(Op==res1,colorGreen,ColorRGB(77,70,75)));
_SECTION_END();

/*_SECTION_BEGIN("ATR");
ParmCloud1 = ParamToggle("TrailingCloud", "No|Yes", 1);
Pp1=Param("Ray_Period1",2,1,20,1); // or 4
Pp2=Param("ATR_Period1",3,1,20,1); // or 2

avgClose = EMA((Open+High+Low+Close)/4,3) ;
avgOpen = EMA((Ref(Open,-1) + Ref(avgClose,-1))/2,3);
Temp = Max(High, avgOpen);
avgHigh = EMA(Max(Temp, avgClose),3);
Temp = Min(Low,avgOpen);
avgLow = EMA(Min(Temp, avgClose),3);
Plot(HHV(LLV(avgHigh,Pp1)-ATR(Pp2),4),"",Linecolor1 ,ParamStyle("styleLine 1",styleLine|styleThick|styleNoTitle|styleNoLabel,maskAll));
Plot(HHV(LLV(avgHigh,Pp1)-ATR(Pp2),5),"",Linecolor2 ,ParamStyle("styleLine 2",styleLine|styleThick|styleNoTitle|styleNoLabel,maskAll));
Plot(HHV(LLV(avgHigh,Pp1)-ATR(Pp2),6),"",Linecolor1 ,ParamStyle("styleLine 3",styleLine|styleThick|styleNoTitle|styleNoLabel,maskAll));
Plot(HHV(LLV(avgHigh,Pp1)-ATR(Pp2),7),"",Linecolor1 ,ParamStyle("styleLine 4",styleLine|styleThick|styleNoTitle|styleNoLabel,maskAll));




CS33=HHV(LLV(avgHigh,Pp1)-ATR(Pp2),4);
CR33=HHV(LLV(avgHigh,Pp1)-ATR(Pp2),5);
CT33=HHV(LLV(avgHigh,Pp1)-ATR(Pp2),6);
CM33=HHV(LLV(avgHigh,Pp1)-ATR(Pp2),7);

if(parmCloud1 == 1)
{
PlotOHLC( CS33, CS33, CR33,CR33, "Band1", LineColor1, styleCloud | styleNoLabel|styleNoTitle);
PlotOHLC( CR33, CR33, CT33, CT33, "Band2", LineColor2, styleCloud | styleNoLabel|styleNoTitle);
PlotOHLC( CR33, CR33, CM33, CM33, "Band3", LineColor3, styleCloud | styleNoLabel|styleNoTitle);

}


_SECTION_END();*/

_SECTION_BEGIN("Bands");

SupResB =Param("Sup-Res Short",6,0,100,1);
nn=SupResB;



Bandlinecol=ParamColor("SupResLineColor",ColorRGB(82,82,82));
ParmCloud = ParamToggle("Cloud", "No|Yes", 0);
BoxCloudColor=ParamColor("BoxCloudColor",ColorRGB(27,27,27));


Line2=Param("ResLineLength",100,2,500,0.1);
Daysback1    = Line2;
FirstBar1    = BarCount - DaysBack1;
Hh=HHV(flowerHigh,nn);
LL=LLV(flowerLow,nn);

Res2=Hh;
Sup2=LL;

BandRes=IIf(BarIndex() >= Firstbar1,EndValue(Res2),Null);
BandSup=IIf(BarIndex() >= Firstbar1,EndValue(Sup2),Null);
//Plot(BandRes,"",Bandlinecol,ParamStyle("ShortSupBand",styleLine|styleDashed|stylehidden|styleNoTitle|styleNoLabel|styleThick,maskAll));
//Plot(BandSup,"",Bandlinecol,ParamStyle("ShortResBand",styleLine|styleDashed|stylehidden|styleNoTitle|styleNoLabel|styleThick,maskAll));




CS=BandRes;
CR=BandSup;


/*if(parmCloud == 1)
{
    PlotOHLC( CS, CS, CR,CR, "Band",BoxCloudColor, styleCloud | styleNoLabel|styleNoTitle);
}

_SECTION_END();*/




_SECTION_BEGIN("SupRes_Short");
supresshortcolor=ParamColor("SupResShort",ColorRGB(82,82,82));

//this is for short term support line
TimeFrameSet(inWeekly);
ShortSupLenght=Param( "ShortResistLength", 4, 1, 55 ,1);
ShortSupCond1=HHV(High,ShortSupLenght);
ShortSupCond2=Close<Ref(LLV(Low,4),-1);
ShortSupA=IIf(L>Ref(ShortSupCond2,-1),1,IIf(H<Ref(ShortSupCond1,-1),-1,0));
ShortSupB=ValueWhen(ShortSupA!=0,ShortSupA,1);
ShortSupResult=IIf(ShortSupB==1,ShortSupCond1,ShortSupCond2);
TimeFrameRestore();
FinalShortSup=TimeFrameExpand(ShortSupResult,inWeekly,expandFirst);

//Plot(FinalShortSup ,"ShortResistance",supresshortcolor,styleLine|styleStaircase|styleThick|styleNoRescale|styleNoLabel|styleNoTitle);


//this is for short term resistance line
TimeFrameSet(inWeekly);
ShortResLenght=Param( "ShortSupportLenght", 4, 1, 55 ,1);
ShortResCond1=Close>Ref(HHV(High,4),-1);
ShortResCond2=LLV(Low,ShortResLenght);
ShortResA=IIf(H>Ref(ShortResCond1,-1),1,IIf(L<Ref(ShortResCond2,-1),-1,0));
ShortResB=ValueWhen(ShortResA!=0,ShortResA,1);
ShortResResult=IIf(ShortResB==1,ShortResCond2,ShortResCond1);
TimeFrameRestore();
FinalShortRes=TimeFrameExpand(ShortResResult,inWeekly,expandFirst);
Plot(FinalShortRes ,"ShortSupport",supresshortcolor,styleLine|styleThick|styleStaircase|styleNoRescale|styleNoLabel|styleNoTitle);

CS=FinalShortSup;
CR=FinalShortRes;

Step = (CR-CS)/4;
KC = CS + Step;
KB = KC + Step;
KA = KB + Step;

CloudColor1 = ParamColor("CloudColor1",ColorRGB(128,31,17));
CloudColor2 = ParamColor("CloudColor2",ColorRGB(139,139,0));
CloudColor3 = ParamColor("CloudColor3",ColorRGB(1,70,1));
CloudColor4 = ParamColor("CloudColor4",ColorRGB(41,105,05));

//PlotOHLC( CS, CS, KC,KC, "Band", CloudColor1, styleCloud | styleNoLabel|styleNoTitle|styleNoRescale);
//PlotOHLC( KC, KC, KB,KB, "Band", CloudColor2, styleCloud | styleNoLabel|styleNoTitle|styleNoRescale);
//PlotOHLC( KB, KB, KA,KA, "Band", CloudColor3, styleCloud | styleNoLabel|styleNoTitle|styleNoRescale);
//PlotOHLC( KA, KA, CR,CR, "Band", CloudColor4, styleCloud | styleNoLabel|styleNoTitle|styleNoRescale);





_SECTION_END();



_SECTION_BEGIN("SupRes_Long");

supreslongcolor=ParamColor("SupReslong",ColorRGB(0,0,234));


//this is for long term resistance line
TimeFrameSet(inWeekly);
LongResLength=Param( "ResistanceLength", 30, 1, 55 ,1);
LongResCond1=HHV(H,LongResLength);
LongResCond2=Close<Ref(LLV(Low,4),-1);
LongResA=IIf(L>Ref(LongResCond2,-1),1,IIf(H<Ref(LongResCond1,-1),-1,0));
LongResB=ValueWhen(LongResA!=0,LongResA,1);
LongResResult=IIf(LongResB==1,LongResCond1,LongResCond2);
TimeFrameRestore();
FinalResResult=TimeFrameExpand(LongResResult,inWeekly,expandFirst);

//Plot(FinalResResult ,"Resistance",supreslongcolor,styleLine|styleThick|styleNoRescale|styleNoLabel|styleNoTitle);


//this is for long term support line
TimeFrameSet(inWeekly);
LongSupLenght=Param( "SupportLenght", 30, 1, 55 ,1);
LongSupCond1=Close>Ref(HHV(High,4),-1);
LongSupCond2=LLV(Low,LongSupLenght);
LongSupA=IIf(H>Ref(LongSupCond1,-1),1,IIf(L<Ref(LongSupCond2,-1),-1,0));
LongSupB=ValueWhen(LongSupA!=0,LongSupA,1);
LongSupResult=IIf(LongSupB==1,LongSupCond2,LongSupCond1);
TimeFrameRestore();
FinalSupResult=TimeFrameExpand(LongSupResult,inWeekly,expandFirst);
//Plot(FinalSupResult ,"Support",supreslongcolor,styleLine|styleThick|styleNoRescale|styleNoLabel|styleNoTitle);



CloudResColor=ParamColor("LongColor",ColorRGB(0,0,45));


CS1=FinalResResult;
CR1=FinalSupResult;

    //PlotOHLC( CS1, CS1, CR1,CR1, "", CloudResColor, styleCloud |styleStaircase|styleNoRescale| styleNoLabel|styleNoTitle);




_SECTION_END();
_SECTION_BEGIN("Average 0");
 //Average_switch = ParamToggle("Candle On/off", "Off|On");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 20, 2, 200 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );
 if( Type == "Wilders" ) m = Wilders( P, Periods );
 if( Type == "Simple" ) m = MA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", colorDarkYellow),ParamStyle("Style",styleLine |styleThick|styleDots|styleNoTitle ,maskAll),Displacement );

 _SECTION_END();


 _SECTION_BEGIN("Average 1");
 //Average_switch = ParamToggle("Candle On/off", "Off|On");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 60, 2, 200 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );
 if( Type == "Wilders" ) m = Wilders( P, Periods );
 if( Type == "Simple" ) m = MA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", colorDarkGreen),ParamStyle("Style",styleLine |styleThick|styleDots|styleNoTitle ,maskAll),Displacement );

 _SECTION_END();

 _SECTION_BEGIN("Average 2");
 //Average_switch = ParamToggle("Candle On/off", "Off|On");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 100, 2, 200 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );
 if( Type == "Wilders" ) m = Wilders( P, Periods );
 if( Type == "Simple" ) m = MA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", ColorRGB(70,70,70)),ParamStyle("Style",styleLine |styleThick|stylehidden|styleDots|styleNoTitle ,maskAll),Displacement );

 _SECTION_END();


 _SECTION_BEGIN("Average 5");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 120 ,2, 200 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );
 if( Type == "Wilders" ) m = Wilders( P, Periods );
 if( Type == "Simple" ) m = MA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", colorCustom13),ParamStyle("Style",styleLine |styleThick|styleDots|styleNoTitle ,maskAll),Displacement );
 _SECTION_END();


 _SECTION_BEGIN("Sell Average 3");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 180, 2, 800 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );
 if( Type == "Wilders" ) m = Wilders( P, Periods );
 if( Type == "Simple" ) m = MA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", ColorRGB(150,150,150)),ParamStyle("Style",styleLine |styleThick|styleDots|styleNoTitle ,maskAll),Displacement );
 _SECTION_END();


 _SECTION_BEGIN("Average 4");
 P = HaClose;
 Type = ParamList("Type", "Weighted,Lagless-21,Hull-26,Linear
 Regression-45,Exponential,Double Exponential,Tripple
 Exponential,Wilders,Simple");
 Periods = Param("Periods", 500, 2, 800 );
 Displacement = Param("Displacement", 1, -50, 50 );
 m = 0;

 if( Type == "Weighted" ) m= WMA( P, Periods );
 if( Type == "Lagless-21" ) m= 2*EMA(P, Periods)-EMA(EMA(P, Periods), Periods);
 if( Type == "Hull-26" ) m= WMA(2*(WMA(P, Periods/2))-WMA(P, Periods) ,4 );
 if( Type == "Linear Regression-45" ) m= LinearReg( P, Periods );
 if( Type == "Exponential" ) m = EMA( P, Periods );
 if( Type == "Double Exponential" ) m = DEMA( P, Periods );
 if( Type == "Tripple Exponential" ) m = TEMA( P, Periods );

 Plot( m, _DEFAULT_NAME(), ParamColor("Color", ColorRGB(190,190,190)),ParamStyle("Style",styleLine |styleThick|stylehidden|styleDots|styleNoTitle ,maskAll),Displacement );
 _SECTION_END();


_SECTION_BEGIN("PanDora");
///////////////////////////////////
Title =
EncodeColor(colorWhite)+  Title = Name () + " | "
+EncodeColor(colorYellow) + Date() + " | "

+EncodeColor(colorTurquoise)+ "Open : "+ EncodeColor(colorLightGrey)+ O + " | "
+EncodeColor(colorTurquoise)+ "High : "+ EncodeColor(colorLightGrey)+ H + " | "
+EncodeColor(colorTurquoise)+ "Low : "+ EncodeColor(colorLightGrey)+ L + " | "
+EncodeColor(colorTurquoise)+ "Close : "+ WriteIf(C> Ref(C, -1),EncodeColor(colorBrightGreen),EncodeColor(colorRed))+ C + " | "
+EncodeColor(colorTurquoise)+ "Change : ("+ WriteIf(C> Ref(C, -1),EncodeColor(colorBrightGreen),EncodeColor(colorRed)) + WriteVal(C-Ref(C,-1))+" Rs."
+EncodeColor(colorTurquoise)+ " /"+ WriteIf(C> Ref(C, -1),EncodeColor(colorBrightGreen),EncodeColor(colorRed))+ WriteVal( ROC( C, 1 ))+""+ " % "
+EncodeColor(colorTurquoise)+ ") | Volume : " + WriteIf(V> Ref(V, -1.0),EncodeColor(colorBrightGreen),EncodeColor(colorRed))+ WriteVal(V,1.0)
;

//#include <T3.AFL>;


 _SECTION_BEGIN("trending ribbon");

 //BT=ParamColor("BT", colorRed );

 TimeFrameSet (inDaily);
 uptrend=PDI()>MDI()AND Signal()<MACD();
 downtrend=MDI()>PDI()AND Signal()>MACD();
 UTM3=IIf( uptrend, colorGreen, IIf( downtrend, colorRed, colorLightGrey ));

 TimeFrameRestore();

 UpA=uptrend;
 DownB=downtrend;


 Trend1 = WriteIf( UpA,"Up1", "");
 Trend2 = WriteIf( DownB,"Down1", "");


 RequestTimedRefresh( 0 );
 GfxSelectFont( "Tahoma", 12, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorWhite );

 if ( Trend1 =="Up1")
 {
 GfxSelectSolidBrush(ColorRGB(0,70,0) ); //

 }
 else

 if ( Trend2 =="Down1")

 {
 GfxSelectSolidBrush( ColorRGB(70,0,0)); //

 }
 else

 if ( Trend2 =="")

 {
 GfxSelectSolidBrush( colorPaleBlue );

 }


 GfxSelectPen( colorBlack, 0 ); // broader color
 //GfxRoundRect( 15,305,135,215, 5, 5 );
 GfxCircle( 70,90,70 );
 _SECTION_END();







 _SECTION_BEGIN("Rays");

 //FT=ParamColor("FT", colorRed );

 Pp1=3;
 Pp2=2;

 CS33=HHV(LLV(flowerHigh,Pp1)-ATR(Pp2),4);
 CR33=HHV(LLV(flowerHigh,Pp1)-ATR(Pp2),5);

 AtrupTrendCond1 = flowerClose> CS33 ;
 AtrdnTrendCond1 =CS33>flowerClose ;


 ATRup = WriteIf(AtrupTrendCond1,"atrup", "");
 ATRdown= WriteIf( AtrdnTrendCond1,"atrdn", "");

 if ( ATRup =="atrup")
 {
 GfxSelectSolidBrush( ColorRGB(0,180,0) );

 }
 else

 if (ATRdown =="atrdn")

 {
 GfxSelectSolidBrush( ColorRGB(180,0,0));

 }

 else

 if ( ATRdown =="")

 {
 GfxSelectSolidBrush( colorGrey40 );

 }

 GfxSelectFont( "Arial", 10, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorBlack );

 GfxSelectPen( colorBlack, 1 ); // broader color
 GfxCircle( 70,90,60 );

 _SECTION_END();


 _SECTION_BEGIN("Exit_Beast-3");

 //GT=ParamColor("GT", colorRed );

 EntrylookbackPeriod=10;
 EntryATRperiod=1.9;
 EntrySig = C > ( LLV( flowerLow, EntrylookbackPeriod ) + EntryATRperiod * ATR( 10 ) );
 ExitSig = C < ( HHV( flowerHigh, EntrylookbackPeriod ) -EntryATRperiod * ATR( 10 ) );


 RequestTimedRefresh( 0 );
 GfxSelectFont( "Tahoma", 12, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorWhite );

 EntryB = WriteIf( EntrySig,"eu", "");
 ExitB = WriteIf( ExitSig,"ed", "");

 if ( EntryB =="eu")
 {
 GfxSelectSolidBrush( ColorRGB(0,210,0) ); //

 }
 else

 if ( ExitB =="ed")

 {
 GfxSelectSolidBrush( ColorRGB(210,0,0)); //

 }

 else

 if ( ExitB =="")

 {
 GfxSelectSolidBrush( colorGrey40 );

 }

 GfxSelectFont( "Arial", 10, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorBlack );

 GfxSelectPen( colorBlack, 1 ); // broader color
 GfxCircle( 70,90,45 );// changing the value of x,y,rad x-70, y-90, rad-24

 _SECTION_END();



 _SECTION_BEGIN("CCI9-2");

 //HT=ParamColor("HT", colorRed );

 ccidn=CCI(8) < 0;
 cciup=CCI(9) > 0;


 ccresult1 = WriteIf( cciup,"cu", "");
 ccresult2 = WriteIf( ccidn,"cd", "");




 RequestTimedRefresh( 0 );
 GfxSelectFont( "Tahoma", 12, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorWhite );

 if ( ccresult1 =="cu")
 {
 GfxSelectSolidBrush( ColorRGB(0,240,0) );

 }
 else

 if ( ccresult2 =="cd")

 {
 GfxSelectSolidBrush( ColorRGB(240,0,0));

 }

 else

 if ( ccresult2 =="")

 {
 GfxSelectSolidBrush( colorGrey40 );

 }

 GfxSelectFont( "Arial", 10, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorBlack );

 GfxSelectPen( colorBlack, 1 ); // broader color
 GfxCircle( 70,90,30);




 _SECTION_END();




 _SECTION_BEGIN("%BB7-1");

 //IT=ParamColor("IT", colorRed );
 p=7;
 x=((C+2*StDev(C,p)-MA(C,p))/(4*StDev(C,p)))*100;
 bbdown= x < 40;
 bbup= x > 40;

 bbresult1 = WriteIf( bbup,"bu", "");
 bbresult2 = WriteIf( bbdown,"bd", "");
 bbresult3 = WriteIf( C,"bearishrevers", "");



 RequestTimedRefresh( 0 );
 GfxSelectFont( "Tahoma", 12, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorWhite );

 if ( bbresult1 =="bu")
 {
 GfxSelectSolidBrush( ColorRGB(62,255,62) );

 }
 else

 if ( bbresult2 =="bd")

 {
 GfxSelectSolidBrush( ColorRGB(255,62,62) );

 }

 else

 if ( bbresult2 =="")

 {
 GfxSelectSolidBrush( colorGrey40 );

 }

 GfxSelectFont( "Arial", 10, 100 );
 GfxSetBkMode( 1 );
 GfxSetTextColor( colorBlack );

 GfxSelectPen( colorBlack, 1 ); // broader color
 GfxCircle( 70,90,15 );


 _SECTION_END();


_SECTION_BEGIN("Breakout Setting");
 Buyperiods=Param("Breakout periods best is usually 18",5,1,100,1,1);
 Sellperiods=Param("Exit Breakout",5,1,100,1,1);

 HaClose =EMA((O+H+L+C)/4,3); // Woodie

xx = EMA(ROC( EMA( High - Low,10),10 ),13);
 //HaClose =(O+H+L+C)/4;
 HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
 HaHigh = Max( H, Max( HaClose, HaOpen ) );
 HaLow = Min( L, Min( HaClose, HaOpen ) );
 Buy= C>Ref(HHV(High,Buyperiods),-1)  ;
 Sell= C<Ref(LLV(Low,Sellperiods),-1) ;

 /* exrem is one method to remove surplus strade signals. It removes excessive signals of arrow */
 Buy = ExRem(Buy, Sell);
 Sell = ExRem(Sell, Buy);

 PlotShapes( IIf( Buy, shapeHollowSmallUpTriangle, shapeNone ), colorWhite, layer = 0,yposition = HaLow, offset = -30);
 //PlotShapes( IIf( Buy, shapeSmallCircle, shapeNone ), colorWhite, layer = 0,yposition = HaLow, offset = -8);

 PlotShapes( IIf( Sell, shapeHollowSmallDownTriangle, shapeNone ), colorRed, layer = 0, yposition = HaHigh, offset = -30);
 //PlotShapes( IIf( Sell, shapeSmallCircle, shapeNone ), colorRed, layer = 0, yposition = HaHigh, offset = -8);
Buy10 = C>Ref(HHV(High,Buyperiods),-1) AND Cross(xx,0);
Sell10 = C<Ref(LLV(Low,Sellperiods),-1) AND Cross(xx,0);
PlotShapes( IIf( Buy10, shapeUpTriangle, shapeNone ), colorWhite, layer = 0,yposition = HaLow, offset = -15);
PlotShapes( IIf( Sell10, shapeDownTriangle, shapeNone ), colorRed, layer = 0, yposition = HaHigh, offset = -15);
 _SECTION_END();
_SECTION_BEGIN("Earth-2");

SetChartBkColor(16);
//Copyright 9Trading.com


trend = (5)*(EMA(((Close-LLV(Low,27))/(HHV(High,27)-LLV(Low,27)))*(100),5))-
    (3)*(EMA(EMA(((Close-LLV(Low,27))/(HHV(High,27)-LLV(Low,27)))*(100),5),3))-
    EMA(EMA(EMA(((Close-LLV(Low,27))/(HHV(High,27)-LLV(Low,27)))*(100),5),3),2);
Buy1 = Cross(trend,5);
PlotShapes( IIf( Buy1, shapeHollowSmallCircle, shapeNone ), colorWhite, layer = 0, yposition = HaLow, offset = -10  );
 _SECTION_END();


_SECTION_BEGIN("MACD");
r1 = Param( "Fast avg", 12, 2, 200, 1 );
r2 = Param( "Slow avg", 26, 2, 200, 1 );
r3 = Param( "Signal avg", 9, 2, 200, 1 );
r4 = Param( "Wk slow", 17, 2, 200, 1 );
r5 = Param( "Wk fast", 8, 2, 200, 1 );
m1=MACD(r1,r2);
s1=Signal(r1,r2,r3);


mycolor=IIf(m1<0 AND m1>s1, colorGreen,IIf(m1>0 AND m1>s1,colorBrightGreen,IIf(m1>0 AND m1<s1,colorPink,colorRed)));

histcolor = IIf((m1-s1)-Ref((m1-s1),-1)> 0,colorLime,colorRed );

TimeFrameSet( inDaily );// weekly
m1w=MACD(r4,r5);
s1w=Signal(r4,r5,r3);
kp=m1w-s1w;
kph=Ref(kp,-1);
TimeFrameRestore();

kw=TimeFrameExpand( kp, inDaily ); // expand for display
khw=TimeFrameExpand( kph, inDaily ); // expand for display
mw=TimeFrameExpand( m1w, inDaily ); // expand for display
sw=TimeFrameExpand( s1w, inDaily ); // expand for display

hcolor=IIf(mw<0 AND mw>sw, 51,IIf(mw>0 AND mw>sw,colorLime,IIf(mw>0 AND mw<sw,colorOrange,colorRed)));
gcolor=IIf(kw>khw,IIf(kw>0,colorDarkYellow,colorYellow),IIf(kw>0,colorSkyblue,colorBlue));

Plot(( m1 OR s1), "MACD Histogram",  mycolor, styleHistogram|styleArea|styleThick|styleOwnScale|styleNoLabel,0,30 );
_SECTION_END();

_SECTION_BEGIN("Signals");


j1=Cross(m1,0);


PlotShapes( IIf( j1, shapeHollowSmallCircle, shapeNone ), colorWhite, layer = 0, yposition = HaLow, offset = -10  );

j3=Cross(s1,m1) AND m1>0;

PlotShapes( IIf( j3, shapeHollowSmallCircle, shapeNone ), colorRed, layer = 0, yposition = Hahigh, offset = 20  );


_SECTION_END();
_SECTION_BEGIN("Spiker_Shadow");


C1 = Ref(C, -1);
uc = C > C1; dc = C <= C1;
ud = C > O; dd = C <= O;


green = 1; blue = 2; yellow = 3; red = 4; white = 5;
VType = IIf(ud,         
         IIf(uc, green, yellow),
       IIf(dd,
         IIf(dc, red, blue), white));

/* green volume: up-day and up-close*/
gv = IIf(VType == green, V, 0);
/* yellow volume: up-day but down-close */
yv = IIf(VType == yellow, V, 0);
/* red volume: down-day and down-close */
rv = IIf(VType == red, V, 0);
/* blue volume: down-day but up-close */
bv = IIf(VType == blue, V, 0);


uv = gv + bv; uv1 = Ref(uv, -1); /* up volume */
dv = rv + yv; dv1 = Ref(dv, -1); /* down volume */


VolPer = Param("Adjust Vol. MA per.", 10, 1, 255, 1);
ConvPer = Param("Adjust Conv. MA per.", 4, 1, 255, 1);


MAuv = TEMA(uv, VolPer ); mauv1 = Ref(mauv, -1);
MAdv = TEMA(dv, VolPer ); madv1 = Ref(madv, -1);
MAtv = TEMA(V, VolPer );//total volume




Converge = (TEMA(MAuv - MAdv, ConvPer));
Converge1 = Ref(Converge, -1);
ConvergeUp = Converge > Converge1;
ConvergeOver = Converge > 0;
rising = ConvergeUp AND ConvergeOver;
falling = !ConvergeUp AND ConvergeOver;


/*convergenceOscillator = Param("Show Oscillator", 0, 0, 1, 1);
OscillatorOnly = Param("Show Oscillator Only", 0, 0, 1, 1);
if(convergenceOscillator OR OscillatorOnly){
Plot(Converge, "Bull/Bear Volume Convergence/Divergence", colorViolet,
1|styleLeftAxisScale|styleNoLabel|styleThick);
Plot(0,"", colorYellow, 1|styleLeftAxisScale|styleNoLabel);
}*/


upshadow=ParamColor("UpShadowColor",colorDarkBlue );
downshadow=ParamColor("DownShadowColor",colorDarkGrey );
riseFallColor = IIf(rising, upshadow,downshadow);

riseFallShadows = Param("Show RiseFallShadows", 1, 0, 1, 1);
if(riseFallShadows){
Plot(IIf(rising OR falling, 1, 0), "", riseFallColor,ParamStyle("ShadeStyle",styleHistogram|styleArea|styleThick|styleOwnScale|styleNoLabel,maskAll));

/*Plot(IIf(rising OR falling, 1, 0), "", riseFallColor,
styleHistogram|styleArea|styleOwnScale|styleNoLabel);*/
}


//GraphXSpace =5;

//_N(Title="");
_SECTION_END();

_SECTION_BEGIN("Graphics");
GrpPrm=Param("Graphic Space",-5,-10,10);
GraphXSpace=GrpPrm;
_SECTION_END();
_SECTION_BEGIN("Magnified Market Price");
//by Vidyasagar, vkunisetty@yahoo.com//
FS=Param("Font Size",28,11,100,1);
GfxSelectFont("Arial", FS, 700, italic = False, underline = False, True );
GfxSetBkMode( colorWhite );
GfxSetTextColor( ParamColor("Color",colorWhite) );
Hor=Param("Horizontal Position",766,1,1200,1);
Ver=Param("Vertical Position",1,1,1,1);
GfxTextOut("CMP "+C,Hor , Ver );
YC=TimeFrameGetPrice("C",inDaily,-1);
DD=Prec(C-YC,2);
xx=Prec((DD/YC)*100,2);
GfxSelectFont("Arial", 12, 700, italic = False, underline = False, True );
GfxSetBkMode( colorWhite );
GfxSetTextColor(ParamColor("Color",colorWhite) );
//GfxTextOut(""+DD+" ("+xx+"%)", Hor+5, Ver+45 );

_SECTION_END();