correct the errors

#1
please correct the errors.........

_SECTION_BEGIN("Flower");
si=Param("Zoom/In Out",5,-50,100,1);
GraphXSpace=si;

r1 = Param( "ColorFast avg", 5, 2, 200, 1 );
r2 = Param( "ColorSlow avg", 10, 2, 200, 1 );
r3 = Param( "ColorSignal avg", 5, 2, 200, 1 );

m1=MACD(r1,r2);
s1=Signal(r1,r2,r3);
mycolor=IIf(m1<0 AND m1>s1, ColorRGB(155,155,155),IIf(m1>0 AND m1>s1,ColorRGB(0,125,0),IIf(m1>0 AND m1<s1,ColorRGB(180,30,160),ColorRGB(100,0,0))));

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);
barColor=IIf(Close>Open,ColorRGB(0,245,0),ColorRGB(255,0,0));

Ctmpl = E_TSKPCOLORTMPL(Open,High,Low,Close,Volume);
total = 0;
total = total + IIf(tskp_colortmplcnd0 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd1 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd2 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd3 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd4 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd5 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd6 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd7 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd8 > 0, 1, -1);


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

if( total >= 5 )
Color = colorLime;
else if( total <= -5 )
Color = colorRed;
else
Color = colorWhite;
}

Candle=ParamList("Candle","Modified Candlestick,Modified Heikin Ashi,Normal Candlestick",0);
if(Candle=="Modified Candlestick")
{
ColorHighliter = myColor;
SetBarFillColor( ColorHighliter );
Plot (Close,"- Modified Candlestick", Color,ParamStyle( "Style", styleCandle|styleLine | styleThick, maskAll));
}
if(Candle=="Modified Heikin Ashi")
{
ColorHighliter = myColor;
SetBarFillColor( ColorHighliter );
PlotOHLC( IIf(flowerOpen<flowerClose, flowerOpen, flowerClose),flowerHigh,flowerLow,IIf(flowerOpen<flowerClose, flowerClose, flowerOpen), "Modified Heikin Ashi", Color, styleCandle|styleLine);
}
if(Candle=="Normal Candlestick")
{
//ColorHighliter = myColor;
//SetBarFillColor( ColorHighliter );
PlotOHLC(O,H,L,C,"Normal Candlestick",barcolor,styleCandle|styleLine);
}


_SECTION_END();

_SECTION_BEGIN("Kpl System");
/* 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@...
no=Param( "Swing", 8, 1, 55 );
tsl_col=ParamColor( "Color", colorLightGrey );

res=HHV(H,no);
sup=LLV(L,no);
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);
Buy=Cover=Cross(C,tsl) ;
Sell=Short=Cross(tsl,C) ;


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

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorBrightGreen, 0,Low,-15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorRed, 0,High,-15);
PlotShapes(IIf(Cover, shapeHollowCircle, shapeNone),colorWhite, 0,Close,0);
PlotShapes(IIf(Short, shapeHollowCircle, shapeNone),colorYellow, 0,Close,0);



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)+"",""));
_SECTION_END();

_SECTION_BEGIN("Title");

DDayO = TimeFrameGetPrice("O", inDaily);
DHiDay = TimeFrameGetPrice("H", inDaily);
DLoDay = TimeFrameGetPrice("L", inDaily);
prvC = TimeFrameGetPrice("C", inDaily, -1);//close
Title =EncodeColor(colorYellow)+ Date()+EncodeColor(colorPink)+" "+Interval(format=2)+EncodeColor(colorOrange)+" "+Name()+EncodeColor(colorBrightGreen)+" Open:"+WriteVal(O,1.2)+EncodeColor(colorBrightGreen)+" High: "+WriteVal(H,1.2)+EncodeColor(colorWhite)+" Low: "+WriteVal(L,1.2)+EncodeColor(colorYellow)+" Close "+
WriteVal(C,1.2) +
" ~ Prev Close : " + EncodeColor(colorYellow) + prvC +EncodeColor(colorGold)+
"\n Day-Open : " +DDayO + " Day-High : " +DHiDay + " Day-Low : "+ DLoDay ;

_SECTION_END();


_SECTION_BEGIN("Background text");
SetChartBkColor(colorBlack);
strWeekday = StrMid("---sunday---Monday--TuesdayWednesday-Thursday--Friday--Saturday", SelectedValue(DayOfWeek())*9,9);
GraphXSpace=Param("GraphXSpace",0,-55,200,1);
C13=Param("fonts",30,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(transparent=1);
GfxSetOverlayMode(1);
GfxSelectFont("Candara", Status("pxheight")/C13 );
GfxSetTextAlign( 6 );
GfxSetTextColor( ColorRGB (217,217,213));
GfxTextOut( Name(), Status("pxwidth")/C14, Status("pxheight")/C15 );
GfxSelectFont("Tahoma", Status("pxheight")/C13*0.5 );
GfxSetTextColor( ColorRGB (103,103,103));
GfxTextOut( "By", Status("pxwidth")/C14, Status("pxheight")/C15*2.5 );
GfxSelectFont("Candara", Status("pxheight")/C13*0.5 );
GfxSetTextColor( ColorRGB (103,103,103));
GfxTextOut( "", Status("pxwidth")/C14, Status("pxheight")/C15*4 );
GfxSelectFont("MS Sans Serif", 10, 500, False, False, 0);
_SECTION_END();




/* HARMONIC PATTERN DETECTION


Automatic Detection of Harmonic Patterns - Gartley, Bat, Butterfly and Crab.

Zig Zag is not used in this AFL. It is based on fractals

Contact - [email protected]

*/



_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,colorYellow,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);

_SECTION_END( );

ppl = ParamToggle("","Off|On",1);
numbars = LastValue(Cum(Status("barvisible")));
fraction= IIf(StrRight(Name(),3) == "", 3.2, 3.2);
hts = -33.5;
_SECTION_BEGIN("Indicators");
RSI_Periods = Param("RSI Periods", 2, 1, 100, 1);
MA_Periods = Param("Periods for MAV", 50, 1, 200, 1);
Daily_Trend_MA_Pds = Param("Periods for Trend EMA", 6, 1, 100, 1);
MAV_Value = V/EMA(V, MA_Periods);
_SECTION_END();
// Check if previous day's close is above its 6-day EMA
DailyClose = TimeFrameCompress(Close, inDaily);
DailyEMA = EMA( DailyClose, Daily_Trend_MA_Pds);
DailyClose = TimeFrameExpand(DailyClose, inDaily, expandFirst);
DailyEma = TimeFrameExpand(DailyEMA, inDaily, expandFirst);
//Plot(DailyEma,"DailEma",colorCustom12,styleLine);

// Trend detection based on 6EMA for Daily
Daily_Trend_UP = DailyClose > DailyEMA;
Daily_Trend_DOWN = DailyClose < DailyEMA;
Trend_UP_Text = WriteIf(Daily_Trend_UP, "Daily Trend UP", "");
Trend_DOWN_Text = WriteIf(Daily_Trend_DOWN, "Daily Trend DOWN", "");
Trend_Neutral_Text = WriteIf(NOT Daily_Trend_DOWN AND NOT Daily_Trend_UP, "Neutral", "");
TrendCol = IIf(Daily_Trend_UP, colorGreen, IIf(Daily_Trend_DOWN, colorRed, colorLightGrey));
_SECTION_END();



_SECTION_BEGIN("Price");
pds = 20;
MAFAST = EMA( Close, 20 );
MASLOW = EMA( Close, 40 );

DonchianUpper = HHV( Ref( H, -1 ), pds ); // Highest high value of highs in last 20 periods
DonchianLower = LLV( Ref( L, -1 ), pds ); // Lowest low value of low in last 20 periods
DonchianMiddle = ( DonchianUpper + DonchianLower ) / 2;

UpTrend = C > ( LLV( L, 20 ) + 2 * ATR( 10 ) ) AND EMA( Close, 20 ) > EMA( Close, 40 );
DnTrend = C < ( HHV( H, 20 ) - 2 * ATR( 10 ) ) AND EMA( Close, 20 ) < EMA( Close, 40 );
Color = IIf( UpTrend, colorBlue, IIf( DnTrend, colorRed, colorYellow) );

// Plots a 20 period Donchian channel
Plot( C, "Price", Color, styleCandle | styleThick );
NewDay = IIf(Day() != Ref(Day(), -1) OR BarIndex() == LastValue(BarIndex()), 1, 0);
//Plot(NewDay, "", 47, 2 + 32768 + 4096, Minvalue = 0, Maxvalue = 1);
_SECTION_END();

_SECTION_BEGIN("PIVOT POINTS");

/* This code calculates the previous days high, low and close */
Hi1 = IIf(Day()!=Ref(Day(),-1),Ref(HighestSince(Day()!=Ref(Day(),-1),H,1),-1),0);
Hi = ValueWhen(Day()!=Ref(Day(),-1),Hi1,1);
Lo1 = IIf(Day()!=Ref(Day(),-1),Ref(LowestSince(Day()!=Ref(Day(),-1),L,1),-1),0);
Lo = ValueWhen(Day()!=Ref(Day(),-1),Lo1,1);
Cl1 = IIf(Day()!=Ref(Day(),-1),Ref(C,-1),0);
C1 = ValueWhen(Day()!=Ref(Day(),-1),Cl1,1);
wHi=TimeFrameGetPrice("H",inWeekly,-1);
wLo=TimeFrameGetPrice("L",inWeekly,-1);
wCl=TimeFrameGetPrice("C",inWeekly,-1);
mHi=TimeFrameGetPrice("H",inMonthly,-1);
mLo=TimeFrameGetPrice("L",inMonthly,-1);
mCl=TimeFrameGetPrice("C",inMonthly,-1);

//----------------------------------------------------------------------------------

/* This code calculates Daily Piovts */

rg = (Hi - Lo);
bp = (Hi + Lo + C1)/3; bpI = LastValue (bp,1);
r1 = (bp*2)-Lo; r1I = LastValue (r1,1);
s1 = (bp*2)-Hi; s1I = LastValue (s1,1);
r2 = bp + r1 - s1; r2I = LastValue (r2,1);
s2 = bp - r1 + s1; s2I = LastValue (s2,1);
r3 = bp + r2 - s1; r3I = LastValue (r3,1);
s3 = bp - r2 + s1; s3I = LastValue (s3,1);
r4 = bp + r2 - s2; r4I = LastValue (r4,1);
s4 = bp - r2 + s2; s4I = LastValue (s4,1);
wrg = (wHi - wLo);
wbp = (wHi + wLo + wCl)/3; wbpI = LastValue (wbp,1);
wr1 = (wbp*2)-wLo; wr1I = LastValue (wr1,1);
ws1 = (wbp*2)-wHi; ws1I = LastValue (ws1,1);
wr2 = wbp + wr1 - ws1; wr2I = LastValue (wr2,1);
ws2 = wbp - wr1 + ws1; ws2I = LastValue (ws2,1);
wr3 = wbp + wr2 - ws1; wr3I = LastValue (wr3,1);
ws3 = wbp - wr2 + ws1; ws3I = LastValue (ws3,1);
wr4 = wbp + wr2 - ws2; wr4I = LastValue (wr4,1);
ws4 = wbp - wr2 + ws2; ws4I = LastValue (ws4,1);
mrg = (mHi - mLo);
mobp = (mHi + mLo + mCl)/3; mobpI = LastValue (mobp,1);
mr1 = (mobp*2)-mLo; mr1I = LastValue (mr1,1);
ms1 = (mobp*2)-mHi; ms1I = LastValue (ms1,1);
mr2 = mobp + mr1 - ms1; mr2I = LastValue (mr2,1);
ms2 = mobp - mr1 + ms1; ms2I = LastValue (ms2,1);

if(ppl==1) {
Plot(bp,"",colorWhite,styleLine|styleLine|styleNoRescale);
Plot(s1,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s2,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s3,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s4,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(r1,"",colorRed,styleDashed|styleNoRescale);
Plot(r2,"",colorRed,styleDashed|styleNoRescale);
Plot(r3,"",colorRed,styleDashed|styleNoRescale);
Plot(r4,"",colorRed,styleDashed|styleNoRescale);
Plot(wbp,"",colorTan,styleDashed|styleLine|styleNoRescale);
Plot(ws1,"",colorBlue,styleDashed|styleNoRescale);
Plot(ws2,"",colorBlue,styleDashed|styleNoRescale);
//Plot(ws3,"",colorPaleGreen,styleDashed|styleNoRescale);
//Plot(ws4,"",colorPaleGreen,styleDashed|styleNoRescale);
Plot(wr1,"",colorYellow,styleDashed|styleNoRescale);
Plot(wr2,"",colorYellow,styleDashed|styleNoRescale);
//Plot(wr3,"",colorPaleBlue,styleDashed|styleNoRescale);
//Plot(wr4,"",colorPaleBlue,styleDashed|styleNoRescale);
Plot(mobp,"",colorTan,styleDashed|styleLine|styleNoRescale);
Plot(ms1,"",colorPaleGreen,styleDashed|styleNoRescale);
Plot(mr1,"",colorDarkRed,styleDashed|styleNoRescale);
PlotText(" Pivot = " + WriteVal(bp,fraction), LastValue(BarIndex())-(numbars/Hts), bpI +0.05, colorWhite);
PlotText(" Resistance 1 = " + WriteVal(r1,fraction), LastValue(BarIndex())-(numbars/Hts), r1I +0.05, colorRed);
PlotText(" Support 1 = " + WriteVal(s1,fraction), LastValue(BarIndex())-(numbars/Hts), s1I +0.05, colorGreen);
PlotText(" Resistance 2 = " + WriteVal(r2,fraction), LastValue(BarIndex())-(numbars/Hts), r2I +0.05, colorRed);
PlotText(" Support 2 = " + WriteVal(s2,fraction), LastValue(BarIndex())-(numbars/Hts), s2I +0.05, colorBrightGreen);
PlotText(" Resistance 3 = " + WriteVal(r3,fraction), LastValue(BarIndex())-(numbars/Hts), r3I +0.05, colorRed);
PlotText(" Support 3 = " + WriteVal(s3,fraction), LastValue(BarIndex())-(numbars/Hts), s3I +0.05, colorBrightGreen);
PlotText(" Resistance 4 = " + WriteVal(r4,fraction), LastValue(BarIndex())-(numbars/Hts), r4I +0.05, colorRed);
PlotText(" Support 4 = " + WriteVal(s4,fraction), LastValue(BarIndex())-(numbars/Hts), s4I +0.05, colorBrightGreen);
PlotText(" W Pivot = " + WriteVal(wbp,fraction), LastValue(BarIndex())-(numbars/Hts), wbpI +0.05, colorTan);
PlotText(" W Resistance 1 = " + WriteVal(wr1,fraction), LastValue(BarIndex())-(numbars/Hts), wr1I +0.05, colorYellow);
PlotText(" W Support 1 = " + WriteVal(ws1,fraction), LastValue(BarIndex())-(numbars/Hts), ws1I +0.05, colorBlue);
PlotText(" W Resistance 2 = " + WriteVal(wr2,fraction), LastValue(BarIndex())-(numbars/Hts), wr2I +0.05, colorYellow);
PlotText(" W Support 2 = " + WriteVal(ws2,fraction), LastValue(BarIndex())-(numbars/Hts), ws2I +0.05, colorBlue);
//PlotText(" W Resistance 3 = " + WriteVal(wr3,fraction), LastValue(BarIndex())-(numbars/Hts), wr3I +0.05, colorPaleBlue);
//PlotText(" W Support 3 = " + WriteVal(ws3,fraction), LastValue(BarIndex())-(numbars/Hts), ws3I +0.05, colorPaleGreen);
//PlotText(" W Resistance 4 = " + WriteVal(wr4,fraction), LastValue(BarIndex())-(numbars/Hts), wr4I +0.05, colorPaleBlue);
//PlotText(" W Support 4 = " + WriteVal(ws4,fraction), LastValue(BarIndex())-(numbars/Hts), ws4I +0.05, colorPaleGreen);
PlotText(" M Pivot = " + WriteVal(mobp,fraction), LastValue(BarIndex())-(numbars/Hts), mobpI+0.05, colorTan);
PlotText(" M Resistance 1 = " + WriteVal(mr1,fraction), LastValue(BarIndex())-(numbars/Hts), mr1I+0.05, colorPaleBlue);
PlotText(" M Support 1 = " + WriteVal(ms1,fraction), LastValue(BarIndex())-(numbars/Hts), ms1I+0.05, colorPaleGreen);
}


_SECTION_END();


_SECTION_BEGIN("PIVOTS Hourly");
TimeFrameSet(inHourly);
HourlyH= LastValue(Ref(H,-1));
HourlyL= LastValue(Ref(L,-1));
HourlyC= LastValue(Ref(C,-1));
TimeFrameRestore();

//Daily
HPP = (HourlyL + HourlyH + HourlyC)/3;HPPI = LastValue (HPP,1);
HR1 = (2 * HPP) - HourlyL;HR1I = LastValue (HR1,1);
HS1 = (2 * HPP) - HourlyH;HS1I = LastValue (HS1,1);
HR2 = HPP + (HourlyH - HourlyL);HR2I = LastValue (HR2,1);
HS2 = HPP - (HourlyH - HourlyL);HS2I = LastValue (HS2,1);
HR3 = HourlyH + 2*(HPP - HourlyL);HR3I = LastValue (HR3,1);
HS3 = HourlyL - 2*(HourlyH - HPP);HS3I = LastValue (HS3,1);
SHOWDPIVOTS = ParamToggle("Daily Pivots", "No|Yes",0);
SHOW3 = ParamToggle("3rd Line", "No|Yes",0);

if (SHOWDPIVOTS & SHOW3)
{
Plot(HS3, "S3",ColorR);
Plot(HR3, "R3",ColorG);
PlotText(" H Resis 3 = " + WriteVal(HR3,fraction), LastValue(BarIndex())-(numbars/Hts), HR3I +0.05, colorGreen);
PlotText(" H Sup 3 = " + WriteVal(HS3,fraction), LastValue(BarIndex())-(numbars/Hts), HS3I +0.05, colorRed);

}



for (i=BarCount-2;i>(BarCount-13);i--)//set the last bars to the final PP value
{
HPP = HPP[BarCount-1];
HR1 = HR1[BarCount-1];
HR2 = HR2[BarCount-1];
HS1 = HS1[BarCount-1];
HS2 = HS2[BarCount-1];

ColorG = colorGreen;
ColorB = colorBlue;
ColorR = colorRed;
}

//
// Conceal all but the trailing portion of the line
//
for (i=0;i<BarCount-15;i++) //hide the line except most recent 15 bars
{
ColorR = ColorG = ColorB = colorBlack;
}


if (SHOWDPIVOTS) {
Plot(HR2, "R2",ColorG);
Plot(HR1, "R1",ColorG);
Plot(HPP, "PP",ColorB);
Plot(HS1, "S1",ColorR);
Plot(HS2, "S2",ColorR);
PlotText(" H Pivot = " + WriteVal(HPP,fraction), LastValue(BarIndex())-(numbars/Hts), HPPI +0.05, colorBlue);
PlotText(" H Resis 1 = " + WriteVal(HR1,fraction), LastValue(BarIndex())-(numbars/Hts), HR1I +0.05, colorGreen);
PlotText(" H Sup 1 = " + WriteVal(HS1,fraction), LastValue(BarIndex())-(numbars/Hts), HS1I +0.05, colorRed);
PlotText(" H Resis 2 = " + WriteVal(HR2,fraction), LastValue(BarIndex())-(numbars/Hts), HR2I +0.05, colorGreen);
PlotText(" H Sup 2 = " + WriteVal(HS2,fraction), LastValue(BarIndex())-(numbars/Hts), HS2I +0.05, colorRed);

}

if (SHOWDPIVOTS & SHOW3)
{
Plot(S3, "S3",ColorR);
Plot(R3, "R3",ColorG);
PlotText(" H Resis 3 = " + WriteVal(HR3,fraction), LastValue(BarIndex())-(numbars/Hts), HR3I +0.05, colorGreen);
PlotText(" H Sup 3 = " + WriteVal(HS3,fraction), LastValue(BarIndex())-(numbars/Hts), HS3I +0.05, colorRed);

}


_SECTION_END();

_SECTION_BEGIN("FIBONACCI HIGH PROBABILITY ZONES");

ShowFibHiProbZone=ParamToggle("Show FIb High-Probability Zone","No|Yes",1);
HpzColor = ParamColor("Line Color",colorWhite);
Periodicity = inDaily;

if(ShowFibHiProbZone AND Interval()<inHourly)
{
Periodicity = inDaily;
}
else if(ShowFibHiProbZone AND Interval()==inHourly)
{
Periodicity = inWeekly;
}
else if (ShowFibHiProbZone AND Interval()>=inDaily AND Interval()<inMonthly)
{
Periodicity = inMonthly;
}
else if(ShowFibHiProbZone AND Interval()>inWeekly AND Interval()<inYearly)
{
Periodicity = inYearly;
}
else // Default just to silence the compiler. This will never occur.
{
Hi=Ref(H,-1);
Lo=Ref(L,-1);
Cl=Ref(C,-1);
}

Hi=TimeFrameGetPrice("H",Periodicity,-1);
Lo=TimeFrameGetPrice("L",Periodicity ,-1);
Cl=TimeFrameGetPrice("C",Periodicity ,-1);


p=(Hi+Lo+Cl)/3;
r1=p+((Hi-Lo)/2);
s1=p-((Hi-Lo)/2);
r2=p+(Hi-Lo);
s2=p-(Hi-Lo);

//Bands
s1b=((Hi-Lo)*0.618)-p;
s2b=((Hi-Lo)*1.382)-p;

r1b=((Hi-Lo)*0.618)+p;
r2b=((Hi-Lo)*1.382)+p;

extnd=0;
sty=styleNoLabel|styleStaircase|styleDots|styleNoRescale;
Plot(r1-extnd,"",HpzColor ,sty,Null,Null,extnd,1000);
//PlotOHLC(r1,r1,r1b,r1b,"",Col,sty|styleClipMinMax|styleCloud|styleNoLine,Null,Null,extnd,1000);<
 
#2
please correct the errors.........

_SECTION_BEGIN("Flower");
si=Param("Zoom/In Out",5,-50,100,1);
GraphXSpace=si;

r1 = Param( "ColorFast avg", 5, 2, 200, 1 );
r2 = Param( "ColorSlow avg", 10, 2, 200, 1 );
r3 = Param( "ColorSignal avg", 5, 2, 200, 1 );

m1=MACD(r1,r2);
s1=Signal(r1,r2,r3);
mycolor=IIf(m1<0 AND m1>s1, ColorRGB(155,155,155),IIf(m1>0 AND m1>s1,ColorRGB(0,125,0),IIf(m1>0 AND m1<s1,ColorRGB(180,30,160),ColorRGB(100,0,0))));

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);
barColor=IIf(Close>Open,ColorRGB(0,245,0),ColorRGB(255,0,0));

Ctmpl = E_TSKPCOLORTMPL(Open,High,Low,Close,Volume);
total = 0;
total = total + IIf(tskp_colortmplcnd0 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd1 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd2 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd3 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd4 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd5 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd6 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd7 > 0, 1, -1);
total = total + IIf(tskp_colortmplcnd8 > 0, 1, -1);


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

if( total >= 5 )
Color = colorLime;
else if( total <= -5 )
Color = colorRed;
else
Color = colorWhite;
}

Candle=ParamList("Candle","Modified Candlestick,Modified Heikin Ashi,Normal Candlestick",0);
if(Candle=="Modified Candlestick")
{
ColorHighliter = myColor;
SetBarFillColor( ColorHighliter );
Plot (Close,"- Modified Candlestick", Color,ParamStyle( "Style", styleCandle|styleLine | styleThick, maskAll));
}
if(Candle=="Modified Heikin Ashi")
{
ColorHighliter = myColor;
SetBarFillColor( ColorHighliter );
PlotOHLC( IIf(flowerOpen<flowerClose, flowerOpen, flowerClose),flowerHigh,flowerLow,IIf(flowerOpen<flowerClose, flowerClose, flowerOpen), "Modified Heikin Ashi", Color, styleCandle|styleLine);
}
if(Candle=="Normal Candlestick")
{
//ColorHighliter = myColor;
//SetBarFillColor( ColorHighliter );
PlotOHLC(O,H,L,C,"Normal Candlestick",barcolor,styleCandle|styleLine);
}


_SECTION_END();

_SECTION_BEGIN("Kpl System");
/* 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@...
no=Param( "Swing", 8, 1, 55 );
tsl_col=ParamColor( "Color", colorLightGrey );

res=HHV(H,no);
sup=LLV(L,no);
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);
Buy=Cover=Cross(C,tsl) ;
Sell=Short=Cross(tsl,C) ;


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

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorBrightGreen, 0,Low,-15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorRed, 0,High,-15);
PlotShapes(IIf(Cover, shapeHollowCircle, shapeNone),colorWhite, 0,Close,0);
PlotShapes(IIf(Short, shapeHollowCircle, shapeNone),colorYellow, 0,Close,0);



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)+"",""));
_SECTION_END();

_SECTION_BEGIN("Title");

DDayO = TimeFrameGetPrice("O", inDaily);
DHiDay = TimeFrameGetPrice("H", inDaily);
DLoDay = TimeFrameGetPrice("L", inDaily);
prvC = TimeFrameGetPrice("C", inDaily, -1);//close
Title =EncodeColor(colorYellow)+ Date()+EncodeColor(colorPink)+" "+Interval(format=2)+EncodeColor(colorOrange)+" "+Name()+EncodeColor(colorBrightGreen)+" Open:"+WriteVal(O,1.2)+EncodeColor(colorBrightGreen)+" High: "+WriteVal(H,1.2)+EncodeColor(colorWhite)+" Low: "+WriteVal(L,1.2)+EncodeColor(colorYellow)+" Close "+
WriteVal(C,1.2) +
" ~ Prev Close : " + EncodeColor(colorYellow) + prvC +EncodeColor(colorGold)+
"\n Day-Open : " +DDayO + " Day-High : " +DHiDay + " Day-Low : "+ DLoDay ;

_SECTION_END();


_SECTION_BEGIN("Background text");
SetChartBkColor(colorBlack);
strWeekday = StrMid("---sunday---Monday--TuesdayWednesday-Thursday--Friday--Saturday", SelectedValue(DayOfWeek())*9,9);
GraphXSpace=Param("GraphXSpace",0,-55,200,1);
C13=Param("fonts",30,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(transparent=1);
GfxSetOverlayMode(1);
GfxSelectFont("Candara", Status("pxheight")/C13 );
GfxSetTextAlign( 6 );
GfxSetTextColor( ColorRGB (217,217,213));
GfxTextOut( Name(), Status("pxwidth")/C14, Status("pxheight")/C15 );
GfxSelectFont("Tahoma", Status("pxheight")/C13*0.5 );
GfxSetTextColor( ColorRGB (103,103,103));
GfxTextOut( "By", Status("pxwidth")/C14, Status("pxheight")/C15*2.5 );
GfxSelectFont("Candara", Status("pxheight")/C13*0.5 );
GfxSetTextColor( ColorRGB (103,103,103));
GfxTextOut( "", Status("pxwidth")/C14, Status("pxheight")/C15*4 );
GfxSelectFont("MS Sans Serif", 10, 500, False, False, 0);
_SECTION_END();




/* HARMONIC PATTERN DETECTION


Automatic Detection of Harmonic Patterns - Gartley, Bat, Butterfly and Crab.

Zig Zag is not used in this AFL. It is based on fractals

Contact - [email protected]

*/



_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,colorYellow,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);

_SECTION_END( );

ppl = ParamToggle("","Off|On",1);
numbars = LastValue(Cum(Status("barvisible")));
fraction= IIf(StrRight(Name(),3) == "", 3.2, 3.2);
hts = -33.5;
_SECTION_BEGIN("Indicators");
RSI_Periods = Param("RSI Periods", 2, 1, 100, 1);
MA_Periods = Param("Periods for MAV", 50, 1, 200, 1);
Daily_Trend_MA_Pds = Param("Periods for Trend EMA", 6, 1, 100, 1);
MAV_Value = V/EMA(V, MA_Periods);
_SECTION_END();
// Check if previous day's close is above its 6-day EMA
DailyClose = TimeFrameCompress(Close, inDaily);
DailyEMA = EMA( DailyClose, Daily_Trend_MA_Pds);
DailyClose = TimeFrameExpand(DailyClose, inDaily, expandFirst);
DailyEma = TimeFrameExpand(DailyEMA, inDaily, expandFirst);
//Plot(DailyEma,"DailEma",colorCustom12,styleLine);

// Trend detection based on 6EMA for Daily
Daily_Trend_UP = DailyClose > DailyEMA;
Daily_Trend_DOWN = DailyClose < DailyEMA;
Trend_UP_Text = WriteIf(Daily_Trend_UP, "Daily Trend UP", "");
Trend_DOWN_Text = WriteIf(Daily_Trend_DOWN, "Daily Trend DOWN", "");
Trend_Neutral_Text = WriteIf(NOT Daily_Trend_DOWN AND NOT Daily_Trend_UP, "Neutral", "");
TrendCol = IIf(Daily_Trend_UP, colorGreen, IIf(Daily_Trend_DOWN, colorRed, colorLightGrey));
_SECTION_END();



_SECTION_BEGIN("Price");
pds = 20;
MAFAST = EMA( Close, 20 );
MASLOW = EMA( Close, 40 );

DonchianUpper = HHV( Ref( H, -1 ), pds ); // Highest high value of highs in last 20 periods
DonchianLower = LLV( Ref( L, -1 ), pds ); // Lowest low value of low in last 20 periods
DonchianMiddle = ( DonchianUpper + DonchianLower ) / 2;

UpTrend = C > ( LLV( L, 20 ) + 2 * ATR( 10 ) ) AND EMA( Close, 20 ) > EMA( Close, 40 );
DnTrend = C < ( HHV( H, 20 ) - 2 * ATR( 10 ) ) AND EMA( Close, 20 ) < EMA( Close, 40 );
Color = IIf( UpTrend, colorBlue, IIf( DnTrend, colorRed, colorYellow) );

// Plots a 20 period Donchian channel
Plot( C, "Price", Color, styleCandle | styleThick );
NewDay = IIf(Day() != Ref(Day(), -1) OR BarIndex() == LastValue(BarIndex()), 1, 0);
//Plot(NewDay, "", 47, 2 + 32768 + 4096, Minvalue = 0, Maxvalue = 1);
_SECTION_END();

_SECTION_BEGIN("PIVOT POINTS");

/* This code calculates the previous days high, low and close */
Hi1 = IIf(Day()!=Ref(Day(),-1),Ref(HighestSince(Day()!=Ref(Day(),-1),H,1),-1),0);
Hi = ValueWhen(Day()!=Ref(Day(),-1),Hi1,1);
Lo1 = IIf(Day()!=Ref(Day(),-1),Ref(LowestSince(Day()!=Ref(Day(),-1),L,1),-1),0);
Lo = ValueWhen(Day()!=Ref(Day(),-1),Lo1,1);
Cl1 = IIf(Day()!=Ref(Day(),-1),Ref(C,-1),0);
C1 = ValueWhen(Day()!=Ref(Day(),-1),Cl1,1);
wHi=TimeFrameGetPrice("H",inWeekly,-1);
wLo=TimeFrameGetPrice("L",inWeekly,-1);
wCl=TimeFrameGetPrice("C",inWeekly,-1);
mHi=TimeFrameGetPrice("H",inMonthly,-1);
mLo=TimeFrameGetPrice("L",inMonthly,-1);
mCl=TimeFrameGetPrice("C",inMonthly,-1);

//----------------------------------------------------------------------------------

/* This code calculates Daily Piovts */

rg = (Hi - Lo);
bp = (Hi + Lo + C1)/3; bpI = LastValue (bp,1);
r1 = (bp*2)-Lo; r1I = LastValue (r1,1);
s1 = (bp*2)-Hi; s1I = LastValue (s1,1);
r2 = bp + r1 - s1; r2I = LastValue (r2,1);
s2 = bp - r1 + s1; s2I = LastValue (s2,1);
r3 = bp + r2 - s1; r3I = LastValue (r3,1);
s3 = bp - r2 + s1; s3I = LastValue (s3,1);
r4 = bp + r2 - s2; r4I = LastValue (r4,1);
s4 = bp - r2 + s2; s4I = LastValue (s4,1);
wrg = (wHi - wLo);
wbp = (wHi + wLo + wCl)/3; wbpI = LastValue (wbp,1);
wr1 = (wbp*2)-wLo; wr1I = LastValue (wr1,1);
ws1 = (wbp*2)-wHi; ws1I = LastValue (ws1,1);
wr2 = wbp + wr1 - ws1; wr2I = LastValue (wr2,1);
ws2 = wbp - wr1 + ws1; ws2I = LastValue (ws2,1);
wr3 = wbp + wr2 - ws1; wr3I = LastValue (wr3,1);
ws3 = wbp - wr2 + ws1; ws3I = LastValue (ws3,1);
wr4 = wbp + wr2 - ws2; wr4I = LastValue (wr4,1);
ws4 = wbp - wr2 + ws2; ws4I = LastValue (ws4,1);
mrg = (mHi - mLo);
mobp = (mHi + mLo + mCl)/3; mobpI = LastValue (mobp,1);
mr1 = (mobp*2)-mLo; mr1I = LastValue (mr1,1);
ms1 = (mobp*2)-mHi; ms1I = LastValue (ms1,1);
mr2 = mobp + mr1 - ms1; mr2I = LastValue (mr2,1);
ms2 = mobp - mr1 + ms1; ms2I = LastValue (ms2,1);

if(ppl==1) {
Plot(bp,"",colorWhite,styleLine|styleLine|styleNoRescale);
Plot(s1,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s2,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s3,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(s4,"",colorBrightGreen,styleDashed|styleNoRescale);
Plot(r1,"",colorRed,styleDashed|styleNoRescale);
Plot(r2,"",colorRed,styleDashed|styleNoRescale);
Plot(r3,"",colorRed,styleDashed|styleNoRescale);
Plot(r4,"",colorRed,styleDashed|styleNoRescale);
Plot(wbp,"",colorTan,styleDashed|styleLine|styleNoRescale);
Plot(ws1,"",colorBlue,styleDashed|styleNoRescale);
Plot(ws2,"",colorBlue,styleDashed|styleNoRescale);
//Plot(ws3,"",colorPaleGreen,styleDashed|styleNoRescale);
//Plot(ws4,"",colorPaleGreen,styleDashed|styleNoRescale);
Plot(wr1,"",colorYellow,styleDashed|styleNoRescale);
Plot(wr2,"",colorYellow,styleDashed|styleNoRescale);
//Plot(wr3,"",colorPaleBlue,styleDashed|styleNoRescale);
//Plot(wr4,"",colorPaleBlue,styleDashed|styleNoRescale);
Plot(mobp,"",colorTan,styleDashed|styleLine|styleNoRescale);
Plot(ms1,"",colorPaleGreen,styleDashed|styleNoRescale);
Plot(mr1,"",colorDarkRed,styleDashed|styleNoRescale);
PlotText(" Pivot = " + WriteVal(bp,fraction), LastValue(BarIndex())-(numbars/Hts), bpI +0.05, colorWhite);
PlotText(" Resistance 1 = " + WriteVal(r1,fraction), LastValue(BarIndex())-(numbars/Hts), r1I +0.05, colorRed);
PlotText(" Support 1 = " + WriteVal(s1,fraction), LastValue(BarIndex())-(numbars/Hts), s1I +0.05, colorGreen);
PlotText(" Resistance 2 = " + WriteVal(r2,fraction), LastValue(BarIndex())-(numbars/Hts), r2I +0.05, colorRed);
PlotText(" Support 2 = " + WriteVal(s2,fraction), LastValue(BarIndex())-(numbars/Hts), s2I +0.05, colorBrightGreen);
PlotText(" Resistance 3 = " + WriteVal(r3,fraction), LastValue(BarIndex())-(numbars/Hts), r3I +0.05, colorRed);
PlotText(" Support 3 = " + WriteVal(s3,fraction), LastValue(BarIndex())-(numbars/Hts), s3I +0.05, colorBrightGreen);
PlotText(" Resistance 4 = " + WriteVal(r4,fraction), LastValue(BarIndex())-(numbars/Hts), r4I +0.05, colorRed);
PlotText(" Support 4 = " + WriteVal(s4,fraction), LastValue(BarIndex())-(numbars/Hts), s4I +0.05, colorBrightGreen);
PlotText(" W Pivot = " + WriteVal(wbp,fraction), LastValue(BarIndex())-(numbars/Hts), wbpI +0.05, colorTan);
PlotText(" W Resistance 1 = " + WriteVal(wr1,fraction), LastValue(BarIndex())-(numbars/Hts), wr1I +0.05, colorYellow);
PlotText(" W Support 1 = " + WriteVal(ws1,fraction), LastValue(BarIndex())-(numbars/Hts), ws1I +0.05, colorBlue);
PlotText(" W Resistance 2 = " + WriteVal(wr2,fraction), LastValue(BarIndex())-(numbars/Hts), wr2I +0.05, colorYellow);
PlotText(" W Support 2 = " + WriteVal(ws2,fraction), LastValue(BarIndex())-(numbars/Hts), ws2I +0.05, colorBlue);
//PlotText(" W Resistance 3 = " + WriteVal(wr3,fraction), LastValue(BarIndex())-(numbars/Hts), wr3I +0.05, colorPaleBlue);
//PlotText(" W Support 3 = " + WriteVal(ws3,fraction), LastValue(BarIndex())-(numbars/Hts), ws3I +0.05, colorPaleGreen);
//PlotText(" W Resistance 4 = " + WriteVal(wr4,fraction), LastValue(BarIndex())-(numbars/Hts), wr4I +0.05, colorPaleBlue);
//PlotText(" W Support 4 = " + WriteVal(ws4,fraction), LastValue(BarIndex())-(numbars/Hts), ws4I +0.05, colorPaleGreen);
PlotText(" M Pivot = " + WriteVal(mobp,fraction), LastValue(BarIndex())-(numbars/Hts), mobpI+0.05, colorTan);
PlotText(" M Resistance 1 = " + WriteVal(mr1,fraction), LastValue(BarIndex())-(numbars/Hts), mr1I+0.05, colorPaleBlue);
PlotText(" M Support 1 = " + WriteVal(ms1,fraction), LastValue(BarIndex())-(numbars/Hts), ms1I+0.05, colorPaleGreen);
}


_SECTION_END();


_SECTION_BEGIN("PIVOTS Hourly");
TimeFrameSet(inHourly);
HourlyH= LastValue(Ref(H,-1));
HourlyL= LastValue(Ref(L,-1));
HourlyC= LastValue(Ref(C,-1));
TimeFrameRestore();

//Daily
HPP = (HourlyL + HourlyH + HourlyC)/3;HPPI = LastValue (HPP,1);
HR1 = (2 * HPP) - HourlyL;HR1I = LastValue (HR1,1);
HS1 = (2 * HPP) - HourlyH;HS1I = LastValue (HS1,1);
HR2 = HPP + (HourlyH - HourlyL);HR2I = LastValue (HR2,1);
HS2 = HPP - (HourlyH - HourlyL);HS2I = LastValue (HS2,1);
HR3 = HourlyH + 2*(HPP - HourlyL);HR3I = LastValue (HR3,1);
HS3 = HourlyL - 2*(HourlyH - HPP);HS3I = LastValue (HS3,1);
SHOWDPIVOTS = ParamToggle("Daily Pivots", "No|Yes",0);
SHOW3 = ParamToggle("3rd Line", "No|Yes",0);

if (SHOWDPIVOTS & SHOW3)
{
Plot(HS3, "S3",ColorR);
Plot(HR3, "R3",ColorG);
PlotText(" H Resis 3 = " + WriteVal(HR3,fraction), LastValue(BarIndex())-(numbars/Hts), HR3I +0.05, colorGreen);
PlotText(" H Sup 3 = " + WriteVal(HS3,fraction), LastValue(BarIndex())-(numbars/Hts), HS3I +0.05, colorRed);

}



for (i=BarCount-2;i>(BarCount-13);i--)//set the last bars to the final PP value
{
HPP = HPP[BarCount-1];
HR1 = HR1[BarCount-1];
HR2 = HR2[BarCount-1];
HS1 = HS1[BarCount-1];
HS2 = HS2[BarCount-1];

ColorG = colorGreen;
ColorB = colorBlue;
ColorR = colorRed;
}

//
// Conceal all but the trailing portion of the line
//
for (i=0;i<BarCount-15;i++) //hide the line except most recent 15 bars
{
ColorR = ColorG = ColorB = colorBlack;
}


if (SHOWDPIVOTS) {
Plot(HR2, "R2",ColorG);
Plot(HR1, "R1",ColorG);
Plot(HPP, "PP",ColorB);
Plot(HS1, "S1",ColorR);
Plot(HS2, "S2",ColorR);
PlotText(" H Pivot = " + WriteVal(HPP,fraction), LastValue(BarIndex())-(numbars/Hts), HPPI +0.05, colorBlue);
PlotText(" H Resis 1 = " + WriteVal(HR1,fraction), LastValue(BarIndex())-(numbars/Hts), HR1I +0.05, colorGreen);
PlotText(" H Sup 1 = " + WriteVal(HS1,fraction), LastValue(BarIndex())-(numbars/Hts), HS1I +0.05, colorRed);
PlotText(" H Resis 2 = " + WriteVal(HR2,fraction), LastValue(BarIndex())-(numbars/Hts), HR2I +0.05, colorGreen);
PlotText(" H Sup 2 = " + WriteVal(HS2,fraction), LastValue(BarIndex())-(numbars/Hts), HS2I +0.05, colorRed);

}

if (SHOWDPIVOTS & SHOW3)
{
Plot(S3, "S3",ColorR);
Plot(R3, "R3",ColorG);
PlotText(" H Resis 3 = " + WriteVal(HR3,fraction), LastValue(BarIndex())-(numbars/Hts), HR3I +0.05, colorGreen);
PlotText(" H Sup 3 = " + WriteVal(HS3,fraction), LastValue(BarIndex())-(numbars/Hts), HS3I +0.05, colorRed);

}


_SECTION_END();

_SECTION_BEGIN("FIBONACCI HIGH PROBABILITY ZONES");

ShowFibHiProbZone=ParamToggle("Show FIb High-Probability Zone","No|Yes",1);
HpzColor = ParamColor("Line Color",colorWhite);
Periodicity = inDaily;

if(ShowFibHiProbZone AND Interval()<inHourly)
{
Periodicity = inDaily;
}
else if(ShowFibHiProbZone AND Interval()==inHourly)
{
Periodicity = inWeekly;
}
else if (ShowFibHiProbZone AND Interval()>=inDaily AND Interval()<inMonthly)
{
Periodicity = inMonthly;
}
else if(ShowFibHiProbZone AND Interval()>inWeekly AND Interval()<inYearly)
{
Periodicity = inYearly;
}
else // Default just to silence the compiler. This will never occur.
{
Hi=Ref(H,-1);
Lo=Ref(L,-1);
Cl=Ref(C,-1);
}

Hi=TimeFrameGetPrice("H",Periodicity,-1);
Lo=TimeFrameGetPrice("L",Periodicity ,-1);
Cl=TimeFrameGetPrice("C",Periodicity ,-1);


p=(Hi+Lo+Cl)/3;
r1=p+((Hi-Lo)/2);
s1=p-((Hi-Lo)/2);
r2=p+(Hi-Lo);
s2=p-(Hi-Lo);

//Bands
s1b=((Hi-Lo)*0.618)-p;
s2b=((Hi-Lo)*1.382)-p;

r1b=((Hi-Lo)*0.618)+p;
r2b=((Hi-Lo)*1.382)+p;

extnd=0;
sty=styleNoLabel|styleStaircase|styleDots|styleNoRescale;
Plot(r1-extnd,"",HpzColor ,sty,Null,Null,extnd,1000);
//PlotOHLC(r1,r1,r1b,r1b,"",Col,sty|styleClipMinMax|styleCloud|styleNoLine,Null,Null,extnd,1000);<





Just remove SPACE between every YELLOW ERROR u get..

Your problem would be solved.
 
#3
Pls corrct formula. Last line error


_N(SectionName = "AutoTrader_Basic_Flow_updated_Apr_13,_2009");
_N(Ver = "Ver1_0");

_SECTION_BEGIN(SectionName);
EnableTextOutput(False); // prevents incidental text from being displayed in the
interpretation
//Filename = StrLeft(_DEFAULT_NAME(),StrLen(_DEFAULT_NAME())-2) + " " + Ver; //
//the Name of the program AND is displayed on the Title line
// CAUTION: VarPfx is used to make the static variables unique tp prevent
//bizarre results if you use multiple versions of the trading program
//simultaneously.
//VarPfx = Filename + Ver + Name();

//_N(Title = Filename + StrFormat(" - {{DATE}} \nOpen %g, Hi %g, Lo %g, Close %g
//Vol %g " + " {{VALUES}}", O, H, L, C, V ));
//RequestTimedRefresh(1);
//SetChartOptions(0, chartShowDates);

//pAutoTrading = ParamToggle("AutoTrade", "Off|Running"); // turns auto
//trading on AND off
//Pause = ParamToggle("Pause trading", "Run|Pause"); // pause trading
//DebugOn = ParamToggle("DebugView","Off|Running",0); // Dumps trade data to
//an output window
//closetime = Param("Close time (hhmmss)", 230000, 0, 245959, 1500); // end
//trading at the time specified

// The chart period below must agree with the chart before AutoTrading will
//connect to TWS.
// the following lines define the acceptable periods that auto trading will work with.

// To add a period simply add the period to the existiung ParmList separated by a comma AND then add an Interval test to the if statement.

//ChartPeriod = ParamList("Chart Period", "1,3,5,7,10,15,20,30,Hour,Day", 0); //
//chart period must agree with this setting for auto trading to work
//if( ( Interval() == 60 AND ChartPeriod == "1" ) OR
//( Interval() == 60 * 3 AND ChartPeriod == "3" ) OR
//( Interval() == 60 * 5 AND ChartPeriod == "5" ) OR
//( Interval() == 60 * 7 AND ChartPeriod == "7" ) OR
//( Interval() == 60 * 10 AND ChartPeriod == "10" ) OR
//( Interval() == 60 * 15 AND ChartPeriod == "15" ) OR
//( Interval() == 60 * 20 AND ChartPeriod == "20" ) OR
//( Interval() == 60 * 30 AND ChartPeriod == "30" ) OR
//( Interval() == inHourly AND ChartPeriod == "Hour" ) OR
//( Interval() == inDaily AND ChartPeriod == "Day" ) ) IntervalOK = True;
//else IntervalOK = False;

//pContracts = Param("Contracts", 100, 1, 1000000, 1); // definethe default
//number of contracts to order
//OrderType = ParamList("Order type", "STP,LMT,MKT", 2); // select type of ofder to send

//tick = Param("Tick size", 0.01, 0.0, 10.0, 0.1); // amount from current
//price the stop order will be set
//tMult = Param("Tick multiplier", 100, 1, 1000, 1); // tick * multiplier is used in placeOrder

//tickMult = tick * tMult;

// The symbol on the chart must agree with the symbol selected from this list before AutoTrading will connect to TWS

// Note on modifyin this. The symbol must match exactly what is in the AB symbol directory.

// You can see below that ZG has spaces and the exact number of spaces is required.

// To add a new line just copy a line and replace the things between the "..."
//with the new symbol.
// The last line ends with "); and that is required so don't mess it up.
// To change the ticker list you may remove a line but refer to ParamList if you have trouble. The spacing has to be exactly what the AB database has.

// The ticker list is a string separated by commas. If you separate them so they fit on another line you must Close the string, add a + to indicate

// the string continues on the next line. The string must be closed with a " and the ParamList must be closed with a );


//sTicker = ParamList("Symbol to trade",
//"IBM,MSFT,IWM,QQQQ-SMART-STK,GLD-SMART-STK,FXP", 2);

//ManualBuy = ParamTrigger("Manual buy", "Buy"); // allows user to buy the default number of contracts

//ManualSell = ParamTrigger("Manual Sell", "Sell"); // allows user to sell the default number of contracts

//CancelAll = ParamTrigger("Cancel all pending orders", "Cancel all"); // user can cancel all orders that have NOT been filled

//CloseAll = ParamTrigger("Close all", "Close all"); // cancel all pending orders AND Close all Open positions


//Reset = ParamTrigger("Reset", "Reset"); // resets the auto trading variables


//StaticVarSet(VarPfx + "AutoTrading", pAutoTrading );

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ############### Initilization Initilization Initilization
//Initilization Initilization ########################################

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################

//sysTime = Now(4); // time offset from New York
//sysTimeStr = NumToStr(SysTime, 1.0, False);
//barTime = TimeNum();

// assign values to the following constants
// trigger states used by the program
//fNone = 0; // no orders are being processed
//mCancel = 1; // the user has manually selected cancel all open orders
//mClose = 2; // the user has manually selected close all trades
//mBuy = 3; // the user has manually placed a buy order
//mSell = 4; // theuser has manually placed a sell order
//pBuy = 5; // the users system has generated a buy order
//pSell = 6; // the users system has generated a sell order
//pShort = 7; // the users system has generated a short order
//pCover = 8; // the users system has generated a cover order

// order states set by the program
//ordNone = 20; // there are no open orders being processed
//ordCancelBuy = 21; // an open buy order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordCancelSell = 22; // an open sell order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordSell = 23; // an open sell order is being processed and is waiting for a ordBuy = 24;
//"Filled" Status from TWS
// an open buy order is being processed and is waiting for a ordCover = 25;
//"Filled" Status from TWS
// an open cover order is being processed and is waiting for a "Filled" Status from TWS

// an open short order is being processed and is waiting for a ordShort = 26;
//"Filled" Status from TWS ordCancelAll = 27;
// a cancel all order is being processed and is waiting for a "Cancelled" Status from TWS ordCloseAll = 28;


// a manual buy order is being processed and is waiting for a ordManBuy = 29;
//"Filled" Status from TWS
// a manual sell order is being processed and is waiting for a ordManSell = 30;
//"Filled" Status from TWS

// initializes the static variables when the program starts and when the user presses Reset.static vars when indicator starts

//if (Reset OR Nz(StaticVarGet(VarPfx + "SystemInitialized"), True)) // init


//StaticVarSet(VarPfx + "SystemInitialized", True);
// pause = True; // used to artifically pause the system on init.

// initialize auto trading vars
//StaticVarSet(VarPfx + "OrderState", OrdNone); // contains the order state being processed, normal is none

//StaticVarSetText(VarPfx + "ordID", ""); // an active order being processed,blank when no orders are active

//StaticVarSet(VarPfx + "GetStatus", False); // a flag informs the program that statis is being requested for an active order

//StaticVarSet(VarPfx + "WaitForConfirm", False); // waiting for the number of contracts to agree with the order that was placed

//StaticVarSetText(VarPfx + "EOD", ""); // used to control order processing at the Close of trading hours

// end of power up or reset initialize

// make variables available to the system and trading code
//OrderState = StaticVarGet(VarPfx + "OrderState"); // the current order state numPositions = Nz(StaticVarGet(VarPfx + "numPositions"));

// the number of positions currently held on TWS

//GetStatus = StaticVarGet(VarPfx + "GetStatus"); // the condition of the Status flag, True if waiting for Status from TWS ordID = StaticVarGetText(VarPfx + "ordID");

// ID of the order beign processed WaitForConfirm = StaticVarGet(VarPfx + "WaitForConfirm");

// flag used to tell the program to wait for TWS to update the number of positions LastC = LastValue(Close);

// this is the last tick that was received from the broker data feed errorMsg = "None";

// used to hold the TWS error message

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ################################ Functions Functions Functions
//Functions Functions Functions
//######################################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################


// converts the trade states to displayable text
//function fCvtState(s) // conberts the states to strings for file or trace

//temp = "";
// prog trigger states
//if(s==fNone) temp = "NoTrigger";
//else if(s==pBuy) temp = "ProgBuy";
//else if(s==pSell) temp = "ProgSell";
//else if(s==pShort) temp = "ProgShort";
//else if(s==pCover) temp = "ProgCover";
// order states
//else if(s==ordNone) temp = "OrdNone";
//else if(s==ordBuy) temp = "OrdBuy";
//else if(s==ordSell) temp = "OrdSell";
//else if(s==ordShort) temp = "OrdShort";
//else if(s==ordCover) temp = "OrdCover";
//else if(s==ordCancelBuy) temp = "OrdCancelBuy";
//else if(s==ordCancelSell) temp = "OrdCancelSell";
//else if(s==ordCancelAll) temp = "OrdCancelAll";
//else if(s==ordCloseAll) temp = "OrdCloseAll";
//else if(s==ordManBuy) temp = "ordManBuy";
//else if(s==ordManSell) temp = "OrdManSell";
// manual triggers
//else if(s==mCancel) temp = "Cancel";
//else if(s==mClose) temp = "CloseAll";
//else if(s==mBuy) temp = "ManBuy";
//else if(s==mSell) temp = "ManSell";
// error state

//temp = "Invalid state";
//if(DebugOn) _TRACE("#, Invalid state=" + NumToStr(s, 1.0));

//return temp;


// take hhmmss string and convert to hh:mm:ss
//function fFormatTime(time) tFmt = "";


//Len = StrLen(time);
//if(Len == 5) tFmt = StrLeft(time,1) + ":" + StrMid(time,1,2) + ":" +

//else tFmt = StrLeft(time,2) + ":" + StrMid(time,2,2) + ":" + StrRight(time, 2);

//return tFmt;


// this handles the errors returned on the GetStatus command.
//function fErrorProcessor(msg)

//msgid = "";
//if(StrLeft(msg, 2) == "ID")

//offset1 = StrFind(msg, "Error ");
//temp = StrMid(msg, offset1 + 5, offset1 + 5);
//Offset2 = StrFind(temp, ".");
//msgid = StrLeft(temp, Offset2 - 1);
//if(DebugOn) _TRACE("#, ErrorMessage = " + msgid);

//return msgid;



//if(DebugOn) _TRACE("#, Post Init A, Positions=" + NumToStr(StaticVarGet(VarPfx
//"numPositions"), 1.0) +
//", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +
//fCvtState(OrderState) + ", OrderID=" + ordID +
//", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0));

//_SECTION_END();

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ################### Trading system indicators Trading system
//indicators Trading system indicators #####################
// ################### This section of the code uses AB indicators to define
//the trade timing.
//#####################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
//_SECTION_BEGIN("System");

//
//##############################################################################################################################################################
// ################ System Parameters
//
//##############################################################################################################################################################
//Buy = Sell = Short = Cover = 0; // make sure all arrays are set empty

//
//##############################################################################################################################################################
// ################ Signal calculations - add your indicator and calculations here

//
//##############################################################################################################################################################

//pWMA1 = Param("WMA 1 period", 6, 1, 20, 1);
//pWMA2 = Param("WMA 2 period", 7, 1, 20, 1);
//fMA1 = WMA(C, pWMA1); // calculate MA 1
//fMA2 = WMA( (Open + Close)/2, pWMA2); // original


//Buy = fMA1 > fMA2;
//Short = fMA2 > fMA1;
//Sell = Short;
//Cover = Buy;

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ##################### PLOT INDICATORS PLOT INDICATORS PLOT
//INDICATORS Plot INDICATORS Plot INDICATORS
//##################################
// ##################### Change the following lines to display your system as you see fit.
//##################################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################

//Plot(C, "", colorBlack, ParamStyle( "Price Style", styleBar, maskPrice ) );
//Plot(fMA1, "\nMA1(" + NumToStr(pWMA1, 1.0) + ")", colorRed); // plot the MA lines

//Plot(fMA2, "\nMA2(" + NumToStr(pWMA2, 1.0) + ")", colorRed, styleDashed);
//Plot the MA lines

//PlotShapes(Buy * shapeUpArrow, colorGreen, 0, L, -5 );
//PlotShapes(Sell * shapeDownArrow, colorRed, 0, H, -5 );
//PlotShapes(Short * shapeHollowDownArrow, colorRed, 0, H, -20 );
//PlotShapes(Cover * shapeHollowUpArrow, colorGreen, 0, L, -20 );

//_SECTION_END();

//_SECTION_BEGIN(SectionName + "AT"); // Dont change anything in this section
//unless you know exactly what you are doing.


//##############################################################################################################################################################
// ################ DO NOT CHANGE THE NEXT 4 LINES -- last values changes the
//array Signal to a binary Signal to provide a trigger for the auto trade logic
//
//##############################################################################################################################################################

// displays the signal value in the interpretation window
//printf("\nBuy = " + NumToStr(Buy, 1.0) +
//" Sell = " + NumToStr(Sell, 1.0) +
//" Short = " + NumToStr(Short, 1.0) +
//" Cover = " + NumToStr(Cover, 1.0) + "\n");

//BuyInd = LastValue(Buy); // convert the buy signal to a pulse used by the trading logic

//ShortInd = LastValue(Short); // convert the short signal to a pulse used by trading logic

//SellInd = LastValue(Sell); // convert the sell signal to a pulse used by the the trading logic

//CoverInd = LastValue(Cover); // convert the cover signal to a pulse used by the trading logic


//if(DebugOn) _TRACE("#, Indicators 2, Static, BuyInd = " + NumToStr(BuyInd, 1.0)

//", SellInd = " + NumToStr(SellInd, 1.0) +
//", ShortInd = " + NumToStr(ShortInd, 1.0) +
//", CoverInd = " + NumToStr(CoverInd, 1.0) );

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ###################################### MANUAL BUY MANUAL BUY
//MANUAL Buy MANUAL Buy MANUAL Buy
//###################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fManBuyPositions(ib, oState, OID, positions)

//if(DebugOn) _TRACE("#, ManBuy top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1));
//newState = oState;
// this function closes all open trades
//orderID = ";
//orderID = ib.PlaceOrder(sTicker, "Buy", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManBuy";
//newState = ordManBuy;
//StaticVarSet(VarPfx + "TargetPositions", positions + pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID );
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True);
//if(DebugOn) _TRACE("#, ManBuy " + ordType + ", " + fFormatTime(sysTimeStr) +
//", OrderID" + orderID + ", OrderState=" + fCvtState(newState) +
//", Close=" + NumToStr(LastValue(Close), 1.2));

//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# MANUAL SELL MANUAL SELL MANUAL
//Sell MANUAL Sell MANUAL Sell
//###################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fManSellPositions(ib, oState, OID, positions) // we are neither long or Short


//if(DebugOn) _TRACE("#, ManSel1 top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1));
//newState = oState;
//orderID = "";
//orderID = ib.PlaceOrder(sTicker, "SELL", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManSell";
//newState = ordManSell;
//StaticVarSet(VarPfx + "TargetPositions", positions - pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID);
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True);
//if(DebugOn) _TRACE("#, ManSel1, " + ordType + ", Time=" +
//fFormatTime(sysTimeStr) + ", OrderID=" + orderID +
//", OrderState=" + fCvtState(newState) + ", Close=" +
//NumToStr(LastValue(Close), 1.2));

//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ###################################### CANCEL CANCEL CANCEL
//CANCEL CANCEL CANCEL ######################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fCancelPositions(ib, oState, OID, positions) // we are neither long or Short

// trigger - trg defines the type of order

//newState = oState;
// this if statement prevents making multiple orders - subsequent orders are ignored

//if( oState == ordSell OR oState == ordShort)

//if(OID != "") // used to cancel a sell order that has not been filled

//newState = ordCancelSell;
//ordType = "CancelSell";
//ib.CancelOrder(OID);
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 1, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState =" + fCvtState(newState) + ", OrderID=" + OID);




//else if(oState == ordBuy OR oState == ordCover)

//if(OID != "") // used to cancel a buy order that has not been filled

//newState = ordCancelBuy;
//ordType = "CancelBuy";
//ib.CancelOrder(OID);
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 2, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + OID);




//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ###################################### BUY BUY BUY BUY
//Buy Buy Buy
//###################################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fBuyPositions(ib, oState, OID, positions) // we are neither long or Short

// trigger - trg defines the type of order

//wState = oState;
//ice = LastC;
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", " + NumToStr(OrderType == "MKT", 1));

// this if statement prevents making multiple orders - subsequent orders are ignored

//( oState == ordNone AND OID == "") // program trade and no open positions or pending order sent orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "BUY", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "BUY",
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "BUY",
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", OID=" + ORderID );

//(orderID != "")

//dType = "ProgBuy";
//wState = ordBuy;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Buy, " + ordType + ", Time" + fFormatTime(sysTimeStr)+ ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(LastC, 1.2));




//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# SHORT SHORT SHORT SHORT Short
//######################################################################
//
//############################################################################################################################################################
//
//############################################################################################################################################################

//nction fShortPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState;
//ice = LastC;
//(DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + OID + ", "+ NumToStr(OrderType == "MKT", 1));

//( oState == ordNone AND OID == "") // no sell order sent and no positionAND no current order orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "SELL", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + ORderID ); if(orderID != "")



//dType = "ProgShort";
//wState = ordShort;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Short, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(price, 1.2));




//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# SELL SELL SELL SELL SELLSell Sell
//#######################################################
//##############################################################################################################################################################
//##############################################################################################################################################################
//nction fSellPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState;
//( oState == ordNone ) // close a long position

// exit the current position with a market order orderID = "";

//derID = ib.PlaceOrder(sTicker, "SELL", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "ProgSell";
//wState = ordSell;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Sell, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2));



//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################ COVER COVER COVER COVER Cover Cover Cover
//############################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//nction fCoverPositions(ib, oState, OID, positions) // we are neither long orShort


//wState = oState;
//( oState == ordNone ) // program cover and go flat

//derID = "";
//derID = ib.PlaceOrder(sTicker, "BUY", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "progCover";
//wState = ordCover;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Cover, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2));



//turn newState; // return the type of order that was made



//##############################################################################################################################################################
//##############################################################################################################################################################
// ############ Order Precessing Loop Order Precessing Loop Order Precessing
//op Order Precessing Loop Order Precessing Loop #######################
//##############################################################################################################################################################
//##############################################################################################################################################################

//( StaticVarGet(VarPfx + "AutoTrading") == True AND // auto trading parameter is set on IntervalOK AND // chart is the same interval as the Chart period selected sTicker == Name() ) // the chart symbol is the same as the ticker parameter ibc = GetTradingInterface("IB");





//(ibc)ConnectedStatus = ibc.IsConnected(); // get the connection status, 2 is OK

// the foloowing code closes trades at the end of the day.
// it does this in steps. 1) cancels all open orders. 2) Closes all positions.3) resets the control var EOD EodVar = StaticVarGetText(VarPfx + "EOD"); i//sysTime == closeTime + 1 AND EodVar == "") // this is the close time r + 1 seconds paramete ibc.CancelAllPendingOrders(sTicker);






//aticVarSetText(VarPfx + "EOD", "Cancel");
//RACE("#, ##### CancelAll end of day #####");


//(sysTime == closeTime + 5 AND EodVar == "Cancel") // this is the close time parameter + 5 seconds ibc.CloseAllOpenPositions(sTicker);



//aticVarSetText(VarPfx + "EOD", "Close");
//RACE("#, ##### CloseAll end of day #####");


//(sysTime == closeTime + 8 AND EodVar == "Close") // this is the close time parameter + 8 seconds


//c.CloseAllOpenPositions(sTicker);
//aticVarSetText(VarPfx + "EOD", "");
//RACE("#, ***** Reset EOD static var *****");

// end of close trades at ene of day

// this is where the trade processing is done
//( sysTime < closeTime AND (ConnectedStatus == 2 OR ConnectedStatus == 3) )
// connected to TWS with no error messages

//(StaticVarGet(VarPfx + "SystemInitialized") == True)

//aticVarSet(VarPfx + "SystemInitialized", False);
//c.CancelAllPendingOrders(); // cancel any open orders on start or reset


// retrieve static variables
//mPositions = ibc.GetPositionSize(sTicker);
//aticVarSet(VarPfx + "numPositions", numPositions);

//(DebugOn) _TRACE("#, SysLoop 0, Positions=" + NumToStr(StaticVarGet(VarPfx+ "numPositions"), 1.0) + ", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0) + "\n" );





// GetStaus = false indicates TWS has completed processing the order
// Wait for the trade to be confirmed by a change in the number of positions before resetting the order state AND waitforconfirm flag

// this is used to prevent placing an order if the signal is still active after a filled Status from TWS

//(WaitForConfirm AND !GetStatus)

//(DebugOn) _TRACE("#, WaitForConfirm, OrderState = " +fCvtState(OrderState) + "\n");

// note: WaitForConfirm set false if order cancelled, see GetStatus Cancelled logic

//( (OrderState == OrdBuy AND numPositions > 0) OR
//rderState == OrdShort AND numPositions < 0) OR
//rderState == OrdCover AND numPositions == 0) OR
//rderState == OrdSell AND numPositions == 0) )

//(DebugOn) _TRACE("#, Program trade WaitForConfirm complete");
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);

// user made a manual order so wait for the number of positions to indicate the purchase before resetting order state AND waitforconfirm flags else if(OrderState == ordManBuy OR OrderState == ordManSell



//(DebugOn) _TRACE("#, Manual trade processed, target positions=" + NumToStr(StaticVarGet(VarPfx + "TargetPositions"), 1.0));

//( numPositions == StaticVarGet(VarPfx + "TargetPositions"))

//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//aticVarSet(VarPfx + "WaitForConfirm", False);
//aticVarSet(VarPfx + "TargetPositions", 0);


// user requested close all positions so wait for the number of positions to indicate all positions are closed before resetting

// order state AND waitforconfirm flags else if(OrderState == ordCloseAll )


//(numPositions == 0)

//(DebugOn) _TRACE("#, Close all processed");
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
//aticVarSet(VarPfx + "GetStatus", False);
//aticVarSet(VarPfx + "WaitForConfirm", False);

// end close all


//##############################################################################################################################################################
// ################### Trigger Control Trigger Control Trigger ontrol Trigger Control Trigger Control Trigger Control
//####################
// ################### This section takes the indicator timing andconverts it to one shot triggers required for orders.
//####################
//##############################################################################################################################################################

// waitforconfirm and getstatus flags are used to prevent multiple orderswhile a current order is being processed

// orders are onluy allowed if the waitforconfirm and getstatus flags are False


//yTrigger = SellTrigger = ShortTrigger = CoverTrigger = False;
//(DebugOn) _TRACE("#, AllowInd 0, Indicator, Buy=" + NumToStr(BuyInd, 1.0) + ", Sell=" + NumToStr(SellInd, 1.0) + ", Short=" + NumToStr(ShortInd, 1.0) + ", Cover=" + NumToStr(CoverInd, 1.0));



//(!WaitForConfirm AND !GetStatus ) // allow indicators to pass unless a trade to being processed {


// This is sequence sensitive. cover and sell should close positions before
//w positions are taken.
// ********** CAUTION *****************
// but note that if your system does not generate the sell and cover signals
//e order process can hang AND NOT allow trades
// Pause parameter blocks all programmed trading
//( numPositions > 0 AND SellInd AND !Pause) // sell is only allowed when there are a positive number of positions


//llTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 1 Sell trigger");

//se if( numPositions < 0 AND CoverInd AND !Pause) // cover is only allowed when there are a negative number of positions


//verTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 2 Cover trigger");

//se if( !Pause AND numPositions == 0 ) // buy and short is only allowed when there are no positions


//(BuyInd )

//yTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 3, Buy trigger");

//se if(ShortInd )

//ortTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 4, Short trigger");


// end allowIndicators

// signal reversal and we have open an order and the trend changes direction
//se if ( WaitForConfirm AND numPositions == 0) // Reversal signal with an Open order


//(DebugOn) _TRACE("#, Reversal Cancel 0");
//( (OrderState == ordBuy OR OrderState == ordCover ) AND SellInd)

//llTrigger = True;
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);
//(DebugOn) _TRACE("#, Reversal Cancel 1, SellTrigger=" + NumToStr(SellTrigger, 1.0));


//se if( (OrderState == ordShort OR OrderState == ordSell ) AND CoverInd )

//verTrigger = True;
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);
//(DebugOn) _TRACE("#, Reversal Cancel 2, CoverTrigger=" +NumToStr(CoverTrigger, 1.0));



//(DebugOn) _TRACE("#, AllowInd End, Buy=" + NumToStr(BuyTrigger, 1.0) + ",

// Short=" + NumToStr(ShortTrigger, 1.0) + ", Cover=" + Sell=" + NumToStr(SellTrigger, 1.0) + NumToStr(CoverTrigger, 1.0));


//#################################################################################################################################################
// ######## Stateless processes Stateless processes Statelessprocesses Stateless processes Stateless processes ############
//#################################################################################################################################################
//(CancelAll)

//c.CancelAllPendingOrders(sTicker);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dType = "CancelAll";
//aticVarSet(VarPfx + "WaitForConfirm", False);
//aticVarSet(VarPfx + "GetStatus", False);
//(DebugOn) _TRACE("#, Trigger CancelAll, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID);

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");

//se if(CloseAll )

// close all positions
//c.CancelAllPendingOrders(sTicker);
//c.CloseAllOpenPositions(sTicker);
//derState = ordCloseAll; StaticVarSet(VarPfx + "OrderState", OrderState );
//dType = "CloseAll";
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, ***** Trigger CloseAll " + ordID + ", OrderState="+ fCvtState(OrderState) + ", SysTime =" + NumToStr(SysTime, 1.0, False) + " ****");



//se if(!GetStatus AND ManualBuy) // manual buy the number of contractsdefined in pContracts

//ate = fManBuyPositions(ibc, OrderState, ordID, numPositions);
//aticVarSet(VarPfx + "OrderState", state);

//se if(!GetStatus AND ManualSell) // manual sell number of contracts definedin pContracts

//ate = fManSellPositions(ibc, OrderState, ordID, numPositions);
//aticVarSet(VarPfx + "OrderState", state);


//#################################################################################################################################################
//#################################################################################################################################################
// ########## Program Trading Program Trading ProgramTrading Program Trading Program Trading #################
// ########## Note that the order is sequence sensitive as sell andCover should be processed before Buy AND Short. #################
//#################################################################################################################################################
//#################################################################################################################################################
//se if(!WaitForConfirm ) // not waiting for a trade to settle

//( SellTrigger AND numPositions > 0) // sell to go flat

//ate = fSellPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordSell, OrderState=" + fCvtState(state));


//se if( CoverTrigger AND numPositions < 0) // buy to go flat

//ate = fCoverPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordCover, OrderState=" + fCvtState(state));


//se if( BuyTrigger )

//ate = OrderState;
//(numPositions == 0) // buy n contracts
//ate = fBuyPositions(ibc, OrderState, ordID, numPositions);
//se if(numPositions < 0) // close short position first then go long after flled state = fCoverPositions(ibc, OrderState, ordID, numPositions);


//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordBuy, OrderState=" + fCvtState(state));

//se if( ShortTrigger )

//ate = OrderState;
//(numPositions == 0) // sell n contracts state = fShortPositions(ibc, OrderState, ordID, numPositions);

//se if(numPositions > 0) // close long first then go short after filled state = fSellPositions(ibc, OrderState, ordID, numPositions);

//erState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordShort, OrderState=" + fCvtState(state));




//#################################################################################################################################################
//#################################################################################################################################################
// ########## Order Status Processing Order Status Processing Order Status Processing Order Status Processing #################
//#################################################################################################################################################
// ### order states ordNone = 20; ordCancelBuy = 21; ordCancelSell = 22; rdSell = 23; ordBuy = 24; ordCover = 25; ordShort = 26;
// ### ordCancelAll = 27; ordCloseAll = 28; ordManBuy = 29; ordManSell = 30;

//#################################################################################################################################################
//#################################################################################################################################################
//dID = StaticVarGet(VarPfx + "ordID");
//(DebugOn) _TRACE("#, OrdState 0, GetStatus=" + NumToStr(GetStatus, 1.0) +", Positions=" + NumToStr(numPositions, 1.0) + ", OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID + ", Time=" + fFormatTime(sysTimeStr));



// process the status messages after an order has been sent or cancelled tempStatus = "None";

//(GetStatus)

//mpStatus = ibc.GetStatus( ordID, True ); // get order status
//(tempStatus == "Filled")

// make sure the numPositions is true for the operation being conducted
// this prevents another order as soon as this one is filled
//aticVarSet(VarPfx + "GetStatus", False);
//( OrderState == ordCancelSell OR OrderState == ordCancelBuy )

//derState = ordNone;
//aticVarSet(VarPfx + "OrderState", OrderState );

//(DebugOn) _TRACE("#, OrdState 1 Filled, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID);

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
// end filled
//se if(tempStatus == "PreSubmitted" OR
//mpStatus == "PendingSubmit" OR
//mpStatus == "Pending" OR
//mpStatus == "ApiPending" OR
//mpStatus == "Submitted" )

//( numPositions != 0 AND (OrderState == ordCancelSell OR OrderState ==
//dCancelBuy ))

//derState = ordNone;
//aticVarSet(VarPfx + "OrderState", OrderState );
//aticVarSet(VarPfx + "GetStatus", False);

//(CoverTrigger AND (OrderState == ordShort OR OrderState == ordSell))

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, OrdState 2a, CancelSell, OrderState=" + fCvtState(state));


//se if(SellTrigger AND (OrderState == ordBuy OR OrderState == ordCover))

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, OrdState 2c, CancelBuy , OrderState=" + end Status preSubmitted OR Pending


//se if(tempStatus == "Cancelled")

//aticVarSet(VarPfx + "GetStatus", False);
//aticVarSet(VarPfx + "WaitForConfirm", False);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//(DebugOn) _TRACE("#, OrdState 3 Cancel, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", Positions=" + NumToStr(numPositions , 1.0) +"\n"); ordID = ""; StaticVarSetText(VarPfx + "ordID", "");





//se if(tempStatus == "Error")

//g = ibc.GetLastError(0);
//ror = fErrorProcessor(msg);
//(DebugOn) _TRACE("#, OrdState 4, Error code=" + Error );
//aticVarSet(VarPfx + "SetErrorState", True);
// NOTE: For error not listed below look at the message notes at the end of the program to see how OR if they were handled.trading hours

//(Error == "135" OR Error == "2106" OR Error == "2109") // out of normal


//aticVarSet(VarPfx + "GetStatus", False);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//dID = ""; StaticVarSetText(VarPfx + "ordID", "");

//se if(Error == "201")

//(OrderState == ordShort OR OrderState == ordSell)

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);

//se if(OrderState == ordBuy OR OrderState == ordCover)

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);




//(DebugOn) _TRACE("#, OrdState 10 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID);



// end status errorelse


//(DebugOn) _TRACE("#, OrdState 11 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID);



// end get status

//( StaticVarGet(VarPfx + "SetErrorState") == True)

//rorMsg = ibc.GetLastError(ordID);
//(errorMsg == "None" OR errorMsg == "")
//aticVarSet(VarPfx + "SetErrorState", False); else


//tChartBkColor( colorTan);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//structions = "\n Determine what the error is. Use trace if necessary.\n
//ncel OR Close all orders on TWS.\n Press Reset to continue.";
//otText( "Error " + errorMsg + instructions, BarCount - VisibleBars / 2,
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);

//(DebugOn) _TRACE("#, Unexpected error msg=" + errorMsg + ", OrderState="+ fCvtState(OrderState) + ", OrdID=" + OrdID);




//se if (Pause )

//tChartBkColor( colorLightGrey);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "######\nTrading\nPaused\n######", BarCount - VisibleBars / 2,
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);


//(ConnectedStatus == 2) stat = "Connected."; else if(ConnectedStatus == 3)stat = "Connected with warnings.";

//(StaticVarGet(VarPfx + "ConnectOK") == False)
//aticVarSet(VarPfx + "ConnectOK", True);
//intf("\nStatus:" +
//n Symbol = " + sTicker +
//n TWS " + stat +
//n Last TWS message = " + errorMsg +
//n Order ID = " + WriteIf(ordID != "", OrdId, "None") +
//n OrderState = " + fCvtState(OrderState) +
//n Order Status = " + tempStatus +
//n Positions = " + NumToStr(Nz(numPositions), 1.0, False) );
// end is connected
//se if( ConnectedStatus == 0 OR ConnectedStatus == 1) // lost connection

// handle commection errors
//(ConnectedStatus == 0) stat = "Not Connected."; else if(ConnectedStatus ==
// stat = "Lost Connection.";
//tChartBkColor( colorYellow);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "TWS not connected. Some reasons are:\nTWS error message: " +errorMsg + "\nIncoming connection has not been accepted.", BarCount -VisibleBars / 2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack); printf("\nTWS Status: " + stat + "\n");



// end connection error
//se if (sysTime > closeTime)

//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "###########\nMarket closed\n###########", BarCount - VisibleBars /2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack);


// end if ibc
// end order processing loop

//#################################################################################################################################################
//#################################################################################################################################################
// ########## Commentary Commentary Commentary Commentary Commentary Commentary Commentary Commentary ################
//#################################################################################################################################################
//#################################################################################################################################################

//se // autotrade is off due to an error or trading is turned off

// if error state, display state in title bar
// feedback key info into title bar
//tChartBkColor( colorPink);
//xt = "\nStatus: \nAutoTrading is off. Some of the reasons are:\n" + " 1. Autotrading is turned off\n" + " 2. TWS has not been started or isn't functioning.\n" + " 3. Set chart to " + sTicker + ".\n" + " 4. Chart period mismatch.\n";



// end text

//intf(text);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText(text, BarCount - VisibleBars / 2, LastValue(HHV(H, VisibleBars)),
//lorWhite, colorBlack);


//ECTION_END();

//#################################################################################################################################################
//#################################################################################################################################################
// ########## Setup and WARNINGS Setup and WARNINGS Setup andWARNINGS Setup AND WARNINGS ##############
//#################################################################################################################################################
//#################################################################################################################################################

// Before Auto trading will trade orders and have them filled automatically you must register your copy of IB Controller. See File>Enter unlock code.

// if it is NOT registered the order will be sent but a T will appear on TWS andthe order will NOT be transmitted to the market.

// Once IBC is registered AND the code is entered orders will be processed automatically.BrokerIB.exe ( IB Controller) of 1.2.1 OR above.


// This release level requires TWS 888.3 or above, IB.DLL of 1.8.2 or above, and

// These are required to handle after hours trading and back filling. Thisprogram will NOT work correctly unless these releases are installed.
// TWS may also require an update to JAVA. Check their site for recommendations.
 
#4
_N(SectionName = "AutoTrader_Basic_Flow_updated_Apr_13,_2009");
_N(Ver = "Ver1_0");

_SECTION_BEGIN(SectionName);
EnableTextOutput(False); // prevents incidental text from being displayed in the
interpretation
//Filename = StrLeft(_DEFAULT_NAME(),StrLen(_DEFAULT_NAME())-2) + " " + Ver; //
//the Name of the program AND is displayed on the Title line
// CAUTION: VarPfx is used to make the static variables unique tp prevent
//bizarre results if you use multiple versions of the trading program
//simultaneously.
//VarPfx = Filename + Ver + Name();

//_N(Title = Filename + StrFormat(" - {{DATE}} \nOpen %g, Hi %g, Lo %g, Close %g
//Vol %g " + " {{VALUES}}", O, H, L, C, V ));
//RequestTimedRefresh(1);
//SetChartOptions(0, chartShowDates);

//pAutoTrading = ParamToggle("AutoTrade", "Off|Running"); // turns auto
//trading on AND off
//Pause = ParamToggle("Pause trading", "Run|Pause"); // pause trading
//DebugOn = ParamToggle("DebugView","Off|Running",0); // Dumps trade data to
//an output window
//closetime = Param("Close time (hhmmss)", 230000, 0, 245959, 1500); // end
//trading at the time specified

// The chart period below must agree with the chart before AutoTrading will
//connect to TWS.
// the following lines define the acceptable periods that auto trading will work with.

// To add a period simply add the period to the existiung ParmList separated by a comma AND then add an Interval test to the if statement.

//ChartPeriod = ParamList("Chart Period", "1,3,5,7,10,15,20,30,Hour,Day", 0); //
//chart period must agree with this setting for auto trading to work
//if( ( Interval() == 60 AND ChartPeriod == "1" ) OR
//( Interval() == 60 * 3 AND ChartPeriod == "3" ) OR
//( Interval() == 60 * 5 AND ChartPeriod == "5" ) OR
//( Interval() == 60 * 7 AND ChartPeriod == "7" ) OR
//( Interval() == 60 * 10 AND ChartPeriod == "10" ) OR
//( Interval() == 60 * 15 AND ChartPeriod == "15" ) OR
//( Interval() == 60 * 20 AND ChartPeriod == "20" ) OR
//( Interval() == 60 * 30 AND ChartPeriod == "30" ) OR
//( Interval() == inHourly AND ChartPeriod == "Hour" ) OR
//( Interval() == inDaily AND ChartPeriod == "Day" ) ) IntervalOK = True;
//else IntervalOK = False;

//pContracts = Param("Contracts", 100, 1, 1000000, 1); // definethe default
//number of contracts to order
//OrderType = ParamList("Order type", "STP,LMT,MKT", 2); // select type of ofder to send

//tick = Param("Tick size", 0.01, 0.0, 10.0, 0.1); // amount from current
//price the stop order will be set
//tMult = Param("Tick multiplier", 100, 1, 1000, 1); // tick * multiplier is used in placeOrder

//tickMult = tick * tMult;

// The symbol on the chart must agree with the symbol selected from this list before AutoTrading will connect to TWS

// Note on modifyin this. The symbol must match exactly what is in the AB symbol directory.

// You can see below that ZG has spaces and the exact number of spaces is required.

// To add a new line just copy a line and replace the things between the "..."
//with the new symbol.
// The last line ends with "); and that is required so don't mess it up.
// To change the ticker list you may remove a line but refer to ParamList if you have trouble. The spacing has to be exactly what the AB database has.

// The ticker list is a string separated by commas. If you separate them so they fit on another line you must Close the string, add a + to indicate

// the string continues on the next line. The string must be closed with a " and the ParamList must be closed with a );


//sTicker = ParamList("Symbol to trade",
//"IBM,MSFT,IWM,QQQQ-SMART-STK,GLD-SMART-STK,FXP", 2);

//ManualBuy = ParamTrigger("Manual buy", "Buy"); // allows user to buy the default number of contracts

//ManualSell = ParamTrigger("Manual Sell", "Sell"); // allows user to sell the default number of contracts

//CancelAll = ParamTrigger("Cancel all pending orders", "Cancel all"); // user can cancel all orders that have NOT been filled

//CloseAll = ParamTrigger("Close all", "Close all"); // cancel all pending orders AND Close all Open positions


//Reset = ParamTrigger("Reset", "Reset"); // resets the auto trading variables


//StaticVarSet(VarPfx + "AutoTrading", pAutoTrading );

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ############### Initilization Initilization Initilization
//Initilization Initilization ########################################

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################

//sysTime = Now(4); // time offset from New York
//sysTimeStr = NumToStr(SysTime, 1.0, False);
//barTime = TimeNum();

// assign values to the following constants
// trigger states used by the program
//fNone = 0; // no orders are being processed
//mCancel = 1; // the user has manually selected cancel all open orders
//mClose = 2; // the user has manually selected close all trades
//mBuy = 3; // the user has manually placed a buy order
//mSell = 4; // theuser has manually placed a sell order
//pBuy = 5; // the users system has generated a buy order
//pSell = 6; // the users system has generated a sell order
//pShort = 7; // the users system has generated a short order
//pCover = 8; // the users system has generated a cover order

// order states set by the program
//ordNone = 20; // there are no open orders being processed
//ordCancelBuy = 21; // an open buy order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordCancelSell = 22; // an open sell order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordSell = 23; // an open sell order is being processed and is waiting for a ordBuy = 24;
//"Filled" Status from TWS
// an open buy order is being processed and is waiting for a ordCover = 25;
//"Filled" Status from TWS
// an open cover order is being processed and is waiting for a "Filled" Status from TWS

// an open short order is being processed and is waiting for a ordShort = 26;
//"Filled" Status from TWS ordCancelAll = 27;
// a cancel all order is being processed and is waiting for a "Cancelled" Status from TWS ordCloseAll = 28;


// a manual buy order is being processed and is waiting for a ordManBuy = 29;
//"Filled" Status from TWS
// a manual sell order is being processed and is waiting for a ordManSell = 30;
//"Filled" Status from TWS

// initializes the static variables when the program starts and when the user presses Reset.static vars when indicator starts

//if (Reset OR Nz(StaticVarGet(VarPfx + "SystemInitialized"), True)) // init


//StaticVarSet(VarPfx + "SystemInitialized", True);
// pause = True; // used to artifically pause the system on init.

// initialize auto trading vars
//StaticVarSet(VarPfx + "OrderState", OrdNone); // contains the order state being processed, normal is none

//StaticVarSetText(VarPfx + "ordID", ""); // an active order being processed,blank when no orders are active

//StaticVarSet(VarPfx + "GetStatus", False); // a flag informs the program that statis is being requested for an active order

//StaticVarSet(VarPfx + "WaitForConfirm", False); // waiting for the number of contracts to agree with the order that was placed

//StaticVarSetText(VarPfx + "EOD", ""); // used to control order processing at the Close of trading hours

// end of power up or reset initialize

// make variables available to the system and trading code
//OrderState = StaticVarGet(VarPfx + "OrderState"); // the current order state numPositions = Nz(StaticVarGet(VarPfx + "numPositions"));

// the number of positions currently held on TWS

//GetStatus = StaticVarGet(VarPfx + "GetStatus"); // the condition of the Status flag, True if waiting for Status from TWS ordID = StaticVarGetText(VarPfx + "ordID");

// ID of the order beign processed WaitForConfirm = StaticVarGet(VarPfx + "WaitForConfirm");

// flag used to tell the program to wait for TWS to update the number of positions LastC = LastValue(Close);

// this is the last tick that was received from the broker data feed errorMsg = "None";

// used to hold the TWS error message

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ################################ Functions Functions Functions
//Functions Functions Functions
//######################################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################


// converts the trade states to displayable text
//function fCvtState(s) // conberts the states to strings for file or trace

//temp = "";
// prog trigger states
//if(s==fNone) temp = "NoTrigger";
//else if(s==pBuy) temp = "ProgBuy";
//else if(s==pSell) temp = "ProgSell";
//else if(s==pShort) temp = "ProgShort";
//else if(s==pCover) temp = "ProgCover";
// order states
//else if(s==ordNone) temp = "OrdNone";
//else if(s==ordBuy) temp = "OrdBuy";
//else if(s==ordSell) temp = "OrdSell";
//else if(s==ordShort) temp = "OrdShort";
//else if(s==ordCover) temp = "OrdCover";
//else if(s==ordCancelBuy) temp = "OrdCancelBuy";
//else if(s==ordCancelSell) temp = "OrdCancelSell";
//else if(s==ordCancelAll) temp = "OrdCancelAll";
//else if(s==ordCloseAll) temp = "OrdCloseAll";
//else if(s==ordManBuy) temp = "ordManBuy";
//else if(s==ordManSell) temp = "OrdManSell";
// manual triggers
//else if(s==mCancel) temp = "Cancel";
//else if(s==mClose) temp = "CloseAll";
//else if(s==mBuy) temp = "ManBuy";
//else if(s==mSell) temp = "ManSell";
// error state

//temp = "Invalid state";
//if(DebugOn) _TRACE("#, Invalid state=" + NumToStr(s, 1.0));

//return temp;


// take hhmmss string and convert to hh:mm:ss
//function fFormatTime(time) tFmt = "";


//Len = StrLen(time);
//if(Len == 5) tFmt = StrLeft(time,1) + ":" + StrMid(time,1,2) + ":" +

//else tFmt = StrLeft(time,2) + ":" + StrMid(time,2,2) + ":" + StrRight(time, 2);

//return tFmt;


// this handles the errors returned on the GetStatus command.
//function fErrorProcessor(msg)

//msgid = "";
//if(StrLeft(msg, 2) == "ID")

//offset1 = StrFind(msg, "Error ");
//temp = StrMid(msg, offset1 + 5, offset1 + 5);
//Offset2 = StrFind(temp, ".");
//msgid = StrLeft(temp, Offset2 - 1);
//if(DebugOn) _TRACE("#, ErrorMessage = " + msgid);

//return msgid;



//if(DebugOn) _TRACE("#, Post Init A, Positions=" + NumToStr(StaticVarGet(VarPfx
//"numPositions"), 1.0) +
//", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +
//fCvtState(OrderState) + ", OrderID=" + ordID +
//", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0));

//_SECTION_END();

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ################### Trading system indicators Trading system
//indicators Trading system indicators #####################
// ################### This section of the code uses AB indicators to define
//the trade timing.
//#####################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
//_SECTION_BEGIN("System");

//
//##############################################################################################################################################################
// ################ System Parameters
//
//##############################################################################################################################################################
//Buy = Sell = Short = Cover = 0; // make sure all arrays are set empty

//
//##############################################################################################################################################################
// ################ Signal calculations - add your indicator and calculations here

//
//##############################################################################################################################################################

//pWMA1 = Param("WMA 1 period", 6, 1, 20, 1);
//pWMA2 = Param("WMA 2 period", 7, 1, 20, 1);
//fMA1 = WMA(C, pWMA1); // calculate MA 1
//fMA2 = WMA( (Open + Close)/2, pWMA2); // original


//Buy = fMA1 > fMA2;
//Short = fMA2 > fMA1;
//Sell = Short;
//Cover = Buy;

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ##################### PLOT INDICATORS PLOT INDICATORS PLOT
//INDICATORS Plot INDICATORS Plot INDICATORS
//##################################
// ##################### Change the following lines to display your system as you see fit.
//##################################
//
//##############################################################################################################################################################
//
//##############################################################################################################################################################

//Plot(C, "", colorBlack, ParamStyle( "Price Style", styleBar, maskPrice ) );
//Plot(fMA1, "\nMA1(" + NumToStr(pWMA1, 1.0) + ")", colorRed); // plot the MA lines

//Plot(fMA2, "\nMA2(" + NumToStr(pWMA2, 1.0) + ")", colorRed, styleDashed);
//Plot the MA lines

//PlotShapes(Buy * shapeUpArrow, colorGreen, 0, L, -5 );
//PlotShapes(Sell * shapeDownArrow, colorRed, 0, H, -5 );
//PlotShapes(Short * shapeHollowDownArrow, colorRed, 0, H, -20 );
//PlotShapes(Cover * shapeHollowUpArrow, colorGreen, 0, L, -20 );

//_SECTION_END();

//_SECTION_BEGIN(SectionName + "AT"); // Dont change anything in this section
//unless you know exactly what you are doing.


//##############################################################################################################################################################
// ################ DO NOT CHANGE THE NEXT 4 LINES -- last values changes the
//array Signal to a binary Signal to provide a trigger for the auto trade logic
//
//##############################################################################################################################################################

// displays the signal value in the interpretation window
//printf("\nBuy = " + NumToStr(Buy, 1.0) +
//" Sell = " + NumToStr(Sell, 1.0) +
//" Short = " + NumToStr(Short, 1.0) +
//" Cover = " + NumToStr(Cover, 1.0) + "\n");

//BuyInd = LastValue(Buy); // convert the buy signal to a pulse used by the trading logic

//ShortInd = LastValue(Short); // convert the short signal to a pulse used by trading logic

//SellInd = LastValue(Sell); // convert the sell signal to a pulse used by the the trading logic

//CoverInd = LastValue(Cover); // convert the cover signal to a pulse used by the trading logic


//if(DebugOn) _TRACE("#, Indicators 2, Static, BuyInd = " + NumToStr(BuyInd, 1.0)

//", SellInd = " + NumToStr(SellInd, 1.0) +
//", ShortInd = " + NumToStr(ShortInd, 1.0) +
//", CoverInd = " + NumToStr(CoverInd, 1.0) );

//
//##############################################################################################################################################################
//
//##############################################################################################################################################################
// ###################################### MANUAL BUY MANUAL BUY
//MANUAL Buy MANUAL Buy MANUAL Buy
//###################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fManBuyPositions(ib, oState, OID, positions)

//if(DebugOn) _TRACE("#, ManBuy top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1));
//newState = oState;
// this function closes all open trades
//orderID = ";
//orderID = ib.PlaceOrder(sTicker, "Buy", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManBuy";
//newState = ordManBuy;
//StaticVarSet(VarPfx + "TargetPositions", positions + pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID );
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True);
//if(DebugOn) _TRACE("#, ManBuy " + ordType + ", " + fFormatTime(sysTimeStr) +
//", OrderID" + orderID + ", OrderState=" + fCvtState(newState) +
//", Close=" + NumToStr(LastValue(Close), 1.2));

//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# MANUAL SELL MANUAL SELL MANUAL
//Sell MANUAL Sell MANUAL Sell
//###################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fManSellPositions(ib, oState, OID, positions) // we are neither long or Short


//if(DebugOn) _TRACE("#, ManSel1 top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1));
//newState = oState;
//orderID = "";
//orderID = ib.PlaceOrder(sTicker, "SELL", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManSell";
//newState = ordManSell;
//StaticVarSet(VarPfx + "TargetPositions", positions - pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID);
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True);
//if(DebugOn) _TRACE("#, ManSel1, " + ordType + ", Time=" +
//fFormatTime(sysTimeStr) + ", OrderID=" + orderID +
//", OrderState=" + fCvtState(newState) + ", Close=" +
//NumToStr(LastValue(Close), 1.2));

//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ###################################### CANCEL CANCEL CANCEL
//CANCEL CANCEL CANCEL ######################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fCancelPositions(ib, oState, OID, positions) // we are neither long or Short

// trigger - trg defines the type of order

//newState = oState;
// this if statement prevents making multiple orders - subsequent orders are ignored

//if( oState == ordSell OR oState == ordShort)

//if(OID != "") // used to cancel a sell order that has not been filled

//newState = ordCancelSell;
//ordType = "CancelSell";
//ib.CancelOrder(OID);
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 1, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState =" + fCvtState(newState) + ", OrderID=" + OID);




//else if(oState == ordBuy OR oState == ordCover)

//if(OID != "") // used to cancel a buy order that has not been filled

//newState = ordCancelBuy;
//ordType = "CancelBuy";
//ib.CancelOrder(OID);
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 2, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + OID);




//return newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ###################################### BUY BUY BUY BUY
//Buy Buy Buy
//###################################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//function fBuyPositions(ib, oState, OID, positions) // we are neither long or Short

// trigger - trg defines the type of order

//wState = oState;
//ice = LastC;
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", " + NumToStr(OrderType == "MKT", 1));

// this if statement prevents making multiple orders - subsequent orders are ignored

//( oState == ordNone AND OID == "") // program trade and no open positions or pending order sent orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "BUY", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "BUY",
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "BUY",
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", OID=" + ORderID );

//(orderID != "")

//dType = "ProgBuy";
//wState = ordBuy;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Buy, " + ordType + ", Time" + fFormatTime(sysTimeStr)+ ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(LastC, 1.2));




//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# SHORT SHORT SHORT SHORT Short
//######################################################################
//
//############################################################################################################################################################
//
//############################################################################################################################################################

//nction fShortPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState;
//ice = LastC;
//(DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + OID + ", "+ NumToStr(OrderType == "MKT", 1));

//( oState == ordNone AND OID == "") // no sell order sent and no positionAND no current order orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "SELL", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + ORderID ); if(orderID != "")



//dType = "ProgShort";
//wState = ordShort;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Short, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(price, 1.2));




//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################# SELL SELL SELL SELL SELLSell Sell
//#######################################################
//##############################################################################################################################################################
//##############################################################################################################################################################
//nction fSellPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState;
//( oState == ordNone ) // close a long position

// exit the current position with a market order orderID = "";

//derID = ib.PlaceOrder(sTicker, "SELL", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "ProgSell";
//wState = ordSell;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Sell, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2));



//turn newState; // return the type of order that was made


//##############################################################################################################################################################
//##############################################################################################################################################################
// ################################ COVER COVER COVER COVER Cover Cover Cover
//############################################
//##############################################################################################################################################################
//##############################################################################################################################################################

//nction fCoverPositions(ib, oState, OID, positions) // we are neither long orShort


//wState = oState;
//( oState == ordNone ) // program cover and go flat

//derID = "";
//derID = ib.PlaceOrder(sTicker, "BUY", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "progCover";
//wState = ordCover;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, Cover, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2));



//turn newState; // return the type of order that was made



//##############################################################################################################################################################
//##############################################################################################################################################################
// ############ Order Precessing Loop Order Precessing Loop Order Precessing
//op Order Precessing Loop Order Precessing Loop #######################
//##############################################################################################################################################################
//##############################################################################################################################################################

//( StaticVarGet(VarPfx + "AutoTrading") == True AND // auto trading parameter is set on IntervalOK AND // chart is the same interval as the Chart period selected sTicker == Name() ) // the chart symbol is the same as the ticker parameter ibc = GetTradingInterface("IB");





//(ibc)ConnectedStatus = ibc.IsConnected(); // get the connection status, 2 is OK

// the foloowing code closes trades at the end of the day.
// it does this in steps. 1) cancels all open orders. 2) Closes all positions.3) resets the control var EOD EodVar = StaticVarGetText(VarPfx + "EOD"); i//sysTime == closeTime + 1 AND EodVar == "") // this is the close time r + 1 seconds paramete ibc.CancelAllPendingOrders(sTicker);






//aticVarSetText(VarPfx + "EOD", "Cancel");
//RACE("#, ##### CancelAll end of day #####");


//(sysTime == closeTime + 5 AND EodVar == "Cancel") // this is the close time parameter + 5 seconds ibc.CloseAllOpenPositions(sTicker);



//aticVarSetText(VarPfx + "EOD", "Close");
//RACE("#, ##### CloseAll end of day #####");


//(sysTime == closeTime + 8 AND EodVar == "Close") // this is the close time parameter + 8 seconds


//c.CloseAllOpenPositions(sTicker);
//aticVarSetText(VarPfx + "EOD", "");
//RACE("#, ***** Reset EOD static var *****");

// end of close trades at ene of day

// this is where the trade processing is done
//( sysTime < closeTime AND (ConnectedStatus == 2 OR ConnectedStatus == 3) )
// connected to TWS with no error messages

//(StaticVarGet(VarPfx + "SystemInitialized") == True)

//aticVarSet(VarPfx + "SystemInitialized", False);
//c.CancelAllPendingOrders(); // cancel any open orders on start or reset


// retrieve static variables
//mPositions = ibc.GetPositionSize(sTicker);
//aticVarSet(VarPfx + "numPositions", numPositions);

//(DebugOn) _TRACE("#, SysLoop 0, Positions=" + NumToStr(StaticVarGet(VarPfx+ "numPositions"), 1.0) + ", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0) + "\n" );





// GetStaus = false indicates TWS has completed processing the order
// Wait for the trade to be confirmed by a change in the number of positions before resetting the order state AND waitforconfirm flag

// this is used to prevent placing an order if the signal is still active after a filled Status from TWS

//(WaitForConfirm AND !GetStatus)

//(DebugOn) _TRACE("#, WaitForConfirm, OrderState = " +fCvtState(OrderState) + "\n");

// note: WaitForConfirm set false if order cancelled, see GetStatus Cancelled logic

//( (OrderState == OrdBuy AND numPositions > 0) OR
//rderState == OrdShort AND numPositions < 0) OR
//rderState == OrdCover AND numPositions == 0) OR
//rderState == OrdSell AND numPositions == 0) )

//(DebugOn) _TRACE("#, Program trade WaitForConfirm complete");
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);

// user made a manual order so wait for the number of positions to indicate the purchase before resetting order state AND waitforconfirm flags else if(OrderState == ordManBuy OR OrderState == ordManSell



//(DebugOn) _TRACE("#, Manual trade processed, target positions=" + NumToStr(StaticVarGet(VarPfx + "TargetPositions"), 1.0));

//( numPositions == StaticVarGet(VarPfx + "TargetPositions"))

//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//aticVarSet(VarPfx + "WaitForConfirm", False);
//aticVarSet(VarPfx + "TargetPositions", 0);


// user requested close all positions so wait for the number of positions to indicate all positions are closed before resetting

// order state AND waitforconfirm flags else if(OrderState == ordCloseAll )


//(numPositions == 0)

//(DebugOn) _TRACE("#, Close all processed");
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
//aticVarSet(VarPfx + "GetStatus", False);
//aticVarSet(VarPfx + "WaitForConfirm", False);

// end close all


//##############################################################################################################################################################
// ################### Trigger Control Trigger Control Trigger ontrol Trigger Control Trigger Control Trigger Control
//####################
// ################### This section takes the indicator timing andconverts it to one shot triggers required for orders.
//####################
//##############################################################################################################################################################

// waitforconfirm and getstatus flags are used to prevent multiple orderswhile a current order is being processed

// orders are onluy allowed if the waitforconfirm and getstatus flags are False


//yTrigger = SellTrigger = ShortTrigger = CoverTrigger = False;
//(DebugOn) _TRACE("#, AllowInd 0, Indicator, Buy=" + NumToStr(BuyInd, 1.0) + ", Sell=" + NumToStr(SellInd, 1.0) + ", Short=" + NumToStr(ShortInd, 1.0) + ", Cover=" + NumToStr(CoverInd, 1.0));



//(!WaitForConfirm AND !GetStatus ) // allow indicators to pass unless a trade to being processed {


// This is sequence sensitive. cover and sell should close positions before
//w positions are taken.
// ********** CAUTION *****************
// but note that if your system does not generate the sell and cover signals
//e order process can hang AND NOT allow trades
// Pause parameter blocks all programmed trading
//( numPositions > 0 AND SellInd AND !Pause) // sell is only allowed when there are a positive number of positions


//llTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 1 Sell trigger");

//se if( numPositions < 0 AND CoverInd AND !Pause) // cover is only allowed when there are a negative number of positions


//verTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 2 Cover trigger");

//se if( !Pause AND numPositions == 0 ) // buy and short is only allowed when there are no positions


//(BuyInd )

//yTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 3, Buy trigger");

//se if(ShortInd )

//ortTrigger = True;
//(DebugOn) _TRACE("#, AllowInd 4, Short trigger");


// end allowIndicators

// signal reversal and we have open an order and the trend changes direction
//se if ( WaitForConfirm AND numPositions == 0) // Reversal signal with an Open order


//(DebugOn) _TRACE("#, Reversal Cancel 0");
//( (OrderState == ordBuy OR OrderState == ordCover ) AND SellInd)

//llTrigger = True;
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);
//(DebugOn) _TRACE("#, Reversal Cancel 1, SellTrigger=" + NumToStr(SellTrigger, 1.0));


//se if( (OrderState == ordShort OR OrderState == ordSell ) AND CoverInd )

//verTrigger = True;
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False);
//(DebugOn) _TRACE("#, Reversal Cancel 2, CoverTrigger=" +NumToStr(CoverTrigger, 1.0));



//(DebugOn) _TRACE("#, AllowInd End, Buy=" + NumToStr(BuyTrigger, 1.0) + ",

// Short=" + NumToStr(ShortTrigger, 1.0) + ", Cover=" + Sell=" + NumToStr(SellTrigger, 1.0) + NumToStr(CoverTrigger, 1.0));


//#################################################################################################################################################
// ######## Stateless processes Stateless processes Statelessprocesses Stateless processes Stateless processes ############
//#################################################################################################################################################
//(CancelAll)

//c.CancelAllPendingOrders(sTicker);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dType = "CancelAll";
//aticVarSet(VarPfx + "WaitForConfirm", False);
//aticVarSet(VarPfx + "GetStatus", False);
//(DebugOn) _TRACE("#, Trigger CancelAll, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID);

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");

//se if(CloseAll )

// close all positions
//c.CancelAllPendingOrders(sTicker);
//c.CloseAllOpenPositions(sTicker);
//derState = ordCloseAll; StaticVarSet(VarPfx + "OrderState", OrderState );
//dType = "CloseAll";
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True);
//(DebugOn) _TRACE("#, ***** Trigger CloseAll " + ordID + ", OrderState="+ fCvtState(OrderState) + ", SysTime =" + NumToStr(SysTime, 1.0, False) + " ****");



//se if(!GetStatus AND ManualBuy) // manual buy the number of contractsdefined in pContracts

//ate = fManBuyPositions(ibc, OrderState, ordID, numPositions);
//aticVarSet(VarPfx + "OrderState", state);

//se if(!GetStatus AND ManualSell) // manual sell number of contracts definedin pContracts

//ate = fManSellPositions(ibc, OrderState, ordID, numPositions);
//aticVarSet(VarPfx + "OrderState", state);


//#################################################################################################################################################
//#################################################################################################################################################
// ########## Program Trading Program Trading ProgramTrading Program Trading Program Trading #################
// ########## Note that the order is sequence sensitive as sell andCover should be processed before Buy AND Short. #################
//#################################################################################################################################################
//#################################################################################################################################################
//se if(!WaitForConfirm ) // not waiting for a trade to settle

//( SellTrigger AND numPositions > 0) // sell to go flat

//ate = fSellPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordSell, OrderState=" + fCvtState(state));


//se if( CoverTrigger AND numPositions < 0) // buy to go flat

//ate = fCoverPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordCover, OrderState=" + fCvtState(state));


//se if( BuyTrigger )

//ate = OrderState;
//(numPositions == 0) // buy n contracts
//ate = fBuyPositions(ibc, OrderState, ordID, numPositions);
//se if(numPositions < 0) // close short position first then go long after flled state = fCoverPositions(ibc, OrderState, ordID, numPositions);


//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordBuy, OrderState=" + fCvtState(state));

//se if( ShortTrigger )

//ate = OrderState;
//(numPositions == 0) // sell n contracts state = fShortPositions(ibc, OrderState, ordID, numPositions);

//se if(numPositions > 0) // close long first then go short after filled state = fSellPositions(ibc, OrderState, ordID, numPositions);

//erState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, Trigger ordShort, OrderState=" + fCvtState(state));




//#################################################################################################################################################
//#################################################################################################################################################
// ########## Order Status Processing Order Status Processing Order Status Processing Order Status Processing #################
//#################################################################################################################################################
// ### order states ordNone = 20; ordCancelBuy = 21; ordCancelSell = 22; rdSell = 23; ordBuy = 24; ordCover = 25; ordShort = 26;
// ### ordCancelAll = 27; ordCloseAll = 28; ordManBuy = 29; ordManSell = 30;

//#################################################################################################################################################
//#################################################################################################################################################
//dID = StaticVarGet(VarPfx + "ordID");
//(DebugOn) _TRACE("#, OrdState 0, GetStatus=" + NumToStr(GetStatus, 1.0) +", Positions=" + NumToStr(numPositions, 1.0) + ", OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID + ", Time=" + fFormatTime(sysTimeStr));



// process the status messages after an order has been sent or cancelled tempStatus = "None";

//(GetStatus)

//mpStatus = ibc.GetStatus( ordID, True ); // get order status
//(tempStatus == "Filled")

// make sure the numPositions is true for the operation being conducted
// this prevents another order as soon as this one is filled
//aticVarSet(VarPfx + "GetStatus", False);
//( OrderState == ordCancelSell OR OrderState == ordCancelBuy )

//derState = ordNone;
//aticVarSet(VarPfx + "OrderState", OrderState );

//(DebugOn) _TRACE("#, OrdState 1 Filled, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID);

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
// end filled
//se if(tempStatus == "PreSubmitted" OR
//mpStatus == "PendingSubmit" OR
//mpStatus == "Pending" OR
//mpStatus == "ApiPending" OR
//mpStatus == "Submitted" )

//( numPositions != 0 AND (OrderState == ordCancelSell OR OrderState ==
//dCancelBuy ))

//derState = ordNone;
//aticVarSet(VarPfx + "OrderState", OrderState );
//aticVarSet(VarPfx + "GetStatus", False);

//(CoverTrigger AND (OrderState == ordShort OR OrderState == ordSell))

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, OrdState 2a, CancelSell, OrderState=" + fCvtState(state));


//se if(SellTrigger AND (OrderState == ordBuy OR OrderState == ordCover))

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);
//(DebugOn) _TRACE("#, OrdState 2c, CancelBuy , OrderState=" + end Status preSubmitted OR Pending


//se if(tempStatus == "Cancelled")

//aticVarSet(VarPfx + "GetStatus", False);
//aticVarSet(VarPfx + "WaitForConfirm", False);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//(DebugOn) _TRACE("#, OrdState 3 Cancel, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", Positions=" + NumToStr(numPositions , 1.0) +"\n"); ordID = ""; StaticVarSetText(VarPfx + "ordID", "");





//se if(tempStatus == "Error")

//g = ibc.GetLastError(0);
//ror = fErrorProcessor(msg);
//(DebugOn) _TRACE("#, OrdState 4, Error code=" + Error );
//aticVarSet(VarPfx + "SetErrorState", True);
// NOTE: For error not listed below look at the message notes at the end of the program to see how OR if they were handled.trading hours

//(Error == "135" OR Error == "2106" OR Error == "2109") // out of normal


//aticVarSet(VarPfx + "GetStatus", False);
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//dID = ""; StaticVarSetText(VarPfx + "ordID", "");

//se if(Error == "201")

//(OrderState == ordShort OR OrderState == ordSell)

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);

//se if(OrderState == ordBuy OR OrderState == ordCover)

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions);
//derState = state; StaticVarSet(VarPfx + "OrderState", state);




//(DebugOn) _TRACE("#, OrdState 10 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID);



// end status errorelse


//(DebugOn) _TRACE("#, OrdState 11 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID);



// end get status

//( StaticVarGet(VarPfx + "SetErrorState") == True)

//rorMsg = ibc.GetLastError(ordID);
//(errorMsg == "None" OR errorMsg == "")
//aticVarSet(VarPfx + "SetErrorState", False); else


//tChartBkColor( colorTan);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//structions = "\n Determine what the error is. Use trace if necessary.\n
//ncel OR Close all orders on TWS.\n Press Reset to continue.";
//otText( "Error " + errorMsg + instructions, BarCount - VisibleBars / 2,
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);

//(DebugOn) _TRACE("#, Unexpected error msg=" + errorMsg + ", OrderState="+ fCvtState(OrderState) + ", OrdID=" + OrdID);




//se if (Pause )

//tChartBkColor( colorLightGrey);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "######\nTrading\nPaused\n######", BarCount - VisibleBars / 2,
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);


//(ConnectedStatus == 2) stat = "Connected."; else if(ConnectedStatus == 3)stat = "Connected with warnings.";

//(StaticVarGet(VarPfx + "ConnectOK") == False)
//aticVarSet(VarPfx + "ConnectOK", True);
//intf("\nStatus:" +
//n Symbol = " + sTicker +
//n TWS " + stat +
//n Last TWS message = " + errorMsg +
//n Order ID = " + WriteIf(ordID != "", OrdId, "None") +
//n OrderState = " + fCvtState(OrderState) +
//n Order Status = " + tempStatus +
//n Positions = " + NumToStr(Nz(numPositions), 1.0, False) );
// end is connected
//se if( ConnectedStatus == 0 OR ConnectedStatus == 1) // lost connection

// handle commection errors
//(ConnectedStatus == 0) stat = "Not Connected."; else if(ConnectedStatus ==
// stat = "Lost Connection.";
//tChartBkColor( colorYellow);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "TWS not connected. Some reasons are:\nTWS error message: " +errorMsg + "\nIncoming connection has not been accepted.", BarCount -VisibleBars / 2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack); printf("\nTWS Status: " + stat + "\n");



// end connection error
//se if (sysTime > closeTime)

//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText( "###########\nMarket closed\n###########", BarCount - VisibleBars /2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack);


// end if ibc
// end order processing loop

//#################################################################################################################################################
//#################################################################################################################################################
// ########## Commentary Commentary Commentary Commentary Commentary Commentary Commentary Commentary ################
//#################################################################################################################################################
//#################################################################################################################################################

//se // autotrade is off due to an error or trading is turned off

// if error state, display state in title bar
// feedback key info into title bar
//tChartBkColor( colorPink);
//xt = "\nStatus: \nAutoTrading is off. Some of the reasons are:\n" + " 1. Autotrading is turned off\n" + " 2. TWS has not been started or isn't functioning.\n" + " 3. Set chart to " + sTicker + ".\n" + " 4. Chart period mismatch.\n";



// end text

//intf(text);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );
//otText(text, BarCount - VisibleBars / 2, LastValue(HHV(H, VisibleBars)),
//lorWhite, colorBlack);


//ECTION_END();

//#################################################################################################################################################
//#################################################################################################################################################
// ########## Setup and WARNINGS Setup and WARNINGS Setup andWARNINGS Setup AND WARNINGS ##############
//#################################################################################################################################################
//#################################################################################################################################################

// Before Auto trading will trade orders and have them filled automatically you must register your copy of IB Controller. See File>Enter unlock code.

// if it is NOT registered the order will be sent but a T will appear on TWS andthe order will NOT be transmitted to the market.

// Once IBC is registered AND the code is entered orders will be processed automatically.BrokerIB.exe ( IB Controller) of 1.2.1 OR above.


// This release level requires TWS 888.3 or above, IB.DLL of 1.8.2 or above, and

// These are required to handle after hours trading and back filling. Thisprogram will NOT work correctly unless these releases are installed.
// [COLOR="rgb(72, 209, 204)"[COLOR="Yellow"]][COLOR="[COLOR="Black"]yellow"]TWS may also require an update to JAVA. Check their site for recommendations.
[/COLOR][/COLOR][/COLOR][/COLOR]
 

KelvinHand

Well-Known Member
#6
Not working pls check once more
The code no errors now.

PHP:
_N(SectionName = "AutoTrader_Basic_Flow_updated_Apr_13,_2009");
_N(Ver = "Ver1_0"); 

_SECTION_BEGIN(SectionName); 
EnableTextOutput(False); // prevents incidental text from being displayed in the 
//interpretation
//Filename = StrLeft(_DEFAULT_NAME(),StrLen(_DEFAULT_NAME())-2) + " " + Ver; //
//the Name of the program AND is displayed on the Title line
// CAUTION: VarPfx is used to make the static variables unique tp prevent
//bizarre results if you use multiple versions of the trading program
//simultaneously. 
//VarPfx = Filename + Ver + Name(); 

//_N(Title = Filename + StrFormat(" - {{DATE}} \nOpen %g, Hi %g, Lo %g, Close %g
//Vol %g " + " {{VALUES}}", O, H, L, C, V ));
//RequestTimedRefresh(1);
//SetChartOptions(0, chartShowDates); 

//pAutoTrading = ParamToggle("AutoTrade", "Off|Running");	// turns auto
//trading on AND off
//Pause	= ParamToggle("Pause trading", "Run|Pause");	// pause trading
//DebugOn = ParamToggle("DebugView","Off|Running",0); // Dumps trade data to
//an output window
//closetime	= Param("Close time (hhmmss)", 230000, 0, 245959, 1500); // end
//trading at the time specified

// The chart period below must agree with the chart before AutoTrading will
//connect to TWS.
// the following lines define the acceptable periods that auto trading will work with.

// To add a period simply add the period to the existiung ParmList separated by a comma AND then add an Interval test to the if statement.

//ChartPeriod	= ParamList("Chart Period", "1,3,5,7,10,15,20,30,Hour,Day", 0);	//
//chart period must agree with this setting for auto trading to work
//if( ( Interval() == 60 AND ChartPeriod == "1" ) OR 
//( Interval() == 60 * 3 AND ChartPeriod == "3" ) OR
//( Interval() == 60 * 5 AND ChartPeriod == "5" ) OR
//( Interval() == 60 * 7 AND ChartPeriod == "7" ) OR
//( Interval() == 60 * 10	AND ChartPeriod == "10" ) OR 
//( Interval() == 60 * 15 AND ChartPeriod == "15" ) OR
//( Interval() == 60 * 20 AND ChartPeriod == "20" ) OR
//( Interval() == 60 * 30 AND ChartPeriod == "30" ) OR
//( Interval() == inHourly AND ChartPeriod == "Hour" ) OR 
//( Interval() == inDaily	AND ChartPeriod == "Day" ) ) IntervalOK = True; 
//else IntervalOK = False;

//pContracts	= Param("Contracts", 100, 1, 1000000, 1);	// definethe default
//number of contracts to order
//OrderType	= ParamList("Order type", "STP,LMT,MKT", 2);	// select type of ofder to send

//tick = Param("Tick size", 0.01, 0.0, 10.0, 0.1);	// amount from current
//price the stop order will be set
//tMult	= Param("Tick multiplier", 100, 1, 1000, 1);	// tick * multiplier is used in placeOrder

//tickMult	= tick * tMult;

// The symbol on the chart must agree with the symbol selected from this list before AutoTrading will connect to TWS

// Note on modifyin this. The symbol must match exactly what is in the AB symbol directory. 

// You can see below that ZG has spaces and the exact number of spaces is required.

// To add a new line just copy a line and replace the things between the "..."
//with the new symbol.
// The last line ends with "); and that is required so don't mess it up.
// To change the ticker list you may remove a line but refer to ParamList if you have trouble. The spacing has to be exactly what the AB database has.

// The ticker list is a string separated by commas. If you separate them so they fit on another line you must Close the string, add a + to indicate

// the string continues on the next line. The string must be closed with a " and the ParamList must be closed with a );


//sTicker	= ParamList("Symbol to trade",
//"IBM,MSFT,IWM,QQQQ-SMART-STK,GLD-SMART-STK,FXP", 2);

//ManualBuy	= ParamTrigger("Manual buy", "Buy");	// allows user to buy the default number of contracts

//ManualSell	= ParamTrigger("Manual Sell", "Sell");	// allows user to sell the default number of contracts

//CancelAll = ParamTrigger("Cancel all pending orders", "Cancel all");	// user can cancel all orders that have NOT been filled

//CloseAll = ParamTrigger("Close all", "Close all");	// cancel all pending orders AND Close all Open positions


//Reset = ParamTrigger("Reset", "Reset");	// resets the auto trading variables 


//StaticVarSet(VarPfx + "AutoTrading", pAutoTrading );

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
// ############### Initilization Initilization Initilization 
//Initilization Initilization ########################################

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########

//sysTime = Now(4);	// time offset from New York
//sysTimeStr = NumToStr(SysTime, 1.0, False);
//barTime = TimeNum();

// assign values to the following constants
// trigger states used by the program
//fNone = 0; // no orders are being processed
//mCancel = 1; // the user has manually selected cancel all open orders
//mClose = 2; // the user has manually selected close all trades
//mBuy = 3; // the user has manually placed a buy order
//mSell = 4; // theuser has manually placed a sell order
//pBuy = 5; // the users system has generated a buy order 
//pSell = 6; // the users system has generated a sell order 
//pShort = 7; // the users system has generated a short order 
//pCover = 8; // the users system has generated a cover order

// order states set by the program
//ordNone = 20; // there are no open orders being processed
//ordCancelBuy = 21;	// an open buy order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordCancelSell	= 22;	// an open sell order is being cancelled and is waiting for a "Cancelled" Status from TWS

//ordSell = 23;	// an open sell order is being processed and is waiting for a ordBuy = 24;
//"Filled" Status from TWS 
// an open buy order is being processed and is waiting for a ordCover = 25;
//"Filled" Status from TWS 
// an open cover order is being processed and is waiting for a "Filled" Status from TWS

// an open short order is being processed and is waiting for a ordShort = 26;	
//"Filled" Status from TWS ordCancelAll = 27; 
// a cancel all order is being processed and is waiting for a "Cancelled" Status from TWS ordCloseAll = 28; 


// a manual buy order is being processed and is waiting for a ordManBuy = 29;
//"Filled" Status from TWS 
// a manual sell order is being processed and is waiting for a ordManSell = 30;
//"Filled" Status from TWS 

// initializes the static variables when the program starts and when the user presses Reset.static vars when indicator starts

//if (Reset OR Nz(StaticVarGet(VarPfx + "SystemInitialized"), True)) // init


//StaticVarSet(VarPfx + "SystemInitialized", True);
//	pause = True;	// used to artifically pause the system on init. 

// initialize auto trading vars
//StaticVarSet(VarPfx + "OrderState", OrdNone); // contains the order state being processed, normal is none

//StaticVarSetText(VarPfx + "ordID", "");	// an active order being processed,blank when no orders are active

//StaticVarSet(VarPfx + "GetStatus", False);	// a flag informs the program that statis is being requested for an active order

//StaticVarSet(VarPfx + "WaitForConfirm", False);	// waiting for the number of contracts to agree with the order that was placed 

//StaticVarSetText(VarPfx + "EOD", ""); // used to control order processing at the Close of trading hours

// end of power up or reset initialize

// make variables available to the system and trading code
//OrderState = StaticVarGet(VarPfx + "OrderState"); // the current order state numPositions = Nz(StaticVarGet(VarPfx + "numPositions"));

// the number of positions currently held on TWS

//GetStatus = StaticVarGet(VarPfx + "GetStatus");	// the condition of the Status flag, True if waiting for Status from TWS ordID = StaticVarGetText(VarPfx + "ordID");	

// ID of the order beign processed WaitForConfirm = StaticVarGet(VarPfx + "WaitForConfirm");

// flag used to tell the program to wait for TWS to update the number of positions LastC = LastValue(Close); 

// this is the last tick that was received from the broker data feed errorMsg = "None";

// used to hold the TWS error message

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
// ################################ Functions Functions Functions 
//Functions Functions Functions 
//######################################
//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########


// converts the trade states to displayable text
//function fCvtState(s) // conberts the states to strings for file or trace

//temp = "";
// prog trigger states 
//if(s==fNone) temp = "NoTrigger"; 
//else if(s==pBuy) temp = "ProgBuy"; 
//else if(s==pSell) temp = "ProgSell"; 
//else if(s==pShort) temp = "ProgShort"; 
//else if(s==pCover) temp = "ProgCover"; 
// order states
//else if(s==ordNone) temp = "OrdNone"; 
//else if(s==ordBuy) temp = "OrdBuy"; 
//else if(s==ordSell) temp = "OrdSell"; 
//else if(s==ordShort) temp = "OrdShort"; 
//else if(s==ordCover) temp = "OrdCover"; 
//else if(s==ordCancelBuy) temp = "OrdCancelBuy"; 
//else if(s==ordCancelSell) temp = "OrdCancelSell"; 
//else if(s==ordCancelAll) temp = "OrdCancelAll"; 
//else if(s==ordCloseAll) temp = "OrdCloseAll"; 
//else if(s==ordManBuy) temp = "ordManBuy";
//else if(s==ordManSell) temp = "OrdManSell"; 
// manual triggers
//else if(s==mCancel) temp = "Cancel"; 
//else if(s==mClose) temp = "CloseAll"; 
//else if(s==mBuy) temp = "ManBuy"; 
//else if(s==mSell) temp = "ManSell"; 
// error state

//temp = "Invalid state"; 
//if(DebugOn) _TRACE("#, Invalid state=" + NumToStr(s, 1.0)); 

//return temp;


// take hhmmss string and convert to hh:mm:ss
//function fFormatTime(time) tFmt = "";


//Len = StrLen(time);
//if(Len == 5) tFmt = StrLeft(time,1) + ":" + StrMid(time,1,2) + ":" +

//else tFmt = StrLeft(time,2) + ":" + StrMid(time,2,2) + ":" + StrRight(time, 2);

//return tFmt;


// this handles the errors returned on the GetStatus command. 
//function fErrorProcessor(msg)

//msgid = "";
//if(StrLeft(msg, 2) == "ID")

//offset1 = StrFind(msg, "Error ");
//temp = StrMid(msg, offset1 + 5, offset1 + 5);
//Offset2 = StrFind(temp, ".");
//msgid = StrLeft(temp, Offset2 - 1); 
//if(DebugOn) _TRACE("#, ErrorMessage = " + msgid);

//return msgid;



//if(DebugOn) _TRACE("#, Post Init A, Positions=" + NumToStr(StaticVarGet(VarPfx
//"numPositions"), 1.0) + 
//", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +
//fCvtState(OrderState) + ", OrderID=" + ordID + 
//", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0)); 

//_SECTION_END(); 

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
// ################### Trading system indicators Trading system
//indicators Trading system indicators #####################
// ################### This section of the code uses AB indicators to define
//the trade timing. 
//#####################
//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
//_SECTION_BEGIN("System"); 

//
//################################################## ################################################## ################################################## ########
// ################ System Parameters
//
//################################################## ################################################## ################################################## ########
//Buy = Sell = Short = Cover = 0; // make sure all arrays are set empty

//
//################################################## ################################################## ################################################## ########
// ################ Signal calculations - add your indicator and calculations here

//
//################################################## ################################################## ################################################## ########

//pWMA1 = Param("WMA 1 period", 6, 1, 20, 1);
//pWMA2 = Param("WMA 2 period", 7, 1, 20, 1);
//fMA1 = WMA(C, pWMA1);	// calculate MA 1
//fMA2 = WMA( (Open + Close)/2, pWMA2);	// original


//Buy	= fMA1 > fMA2; 
//Short	= fMA2 > fMA1; 
//Sell	= Short;
//Cover = Buy; 

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
// ##################### PLOT INDICATORS PLOT INDICATORS PLOT
//INDICATORS Plot INDICATORS Plot INDICATORS 
//##################################
// ##################### Change the following lines to display your system as you see fit.
//##################################
//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########

//Plot(C, "", colorBlack, ParamStyle( "Price Style", styleBar, maskPrice ) );
//Plot(fMA1, "\nMA1(" + NumToStr(pWMA1, 1.0) + ")", colorRed);	// plot the MA lines

//Plot(fMA2, "\nMA2(" + NumToStr(pWMA2, 1.0) + ")", colorRed, styleDashed);	
//Plot the MA lines

//PlotShapes(Buy * shapeUpArrow, colorGreen, 0, L, -5 );
//PlotShapes(Sell * shapeDownArrow, colorRed, 0, H, -5 );
//PlotShapes(Short * shapeHollowDownArrow,	colorRed, 0, H, -20 );
//PlotShapes(Cover * shapeHollowUpArrow, colorGreen, 0, L, -20 );

//_SECTION_END(); 

//_SECTION_BEGIN(SectionName + "AT"); // Dont change anything in this section
//unless you know exactly what you are doing.


//################################################## ################################################## ################################################## ########
// ################ DO NOT CHANGE THE NEXT 4 LINES -- last values changes the
//array Signal to a binary Signal to provide a trigger for the auto trade logic
//
//################################################## ################################################## ################################################## ########

// displays the signal value in the interpretation window
//printf("\nBuy = " + NumToStr(Buy, 1.0) + 
//" Sell = " + NumToStr(Sell, 1.0) + 
//" Short = " + NumToStr(Short, 1.0) + 
//" Cover = " + NumToStr(Cover, 1.0) + "\n");

//BuyInd = LastValue(Buy);	// convert the buy signal to a pulse used by the trading logic

//ShortInd = LastValue(Short);	// convert the short signal to a pulse used by trading logic	

//SellInd = LastValue(Sell);	// convert the sell signal to a pulse used by the the trading logic

//CoverInd	= LastValue(Cover);	// convert the cover signal to a pulse used by the trading logic


//if(DebugOn) _TRACE("#, Indicators 2, Static, BuyInd = " + NumToStr(BuyInd, 1.0)

//", SellInd = " + NumToStr(SellInd, 1.0) + 
//", ShortInd = " + NumToStr(ShortInd, 1.0) + 
//", CoverInd = " + NumToStr(CoverInd, 1.0) );

//
//################################################## ################################################## ################################################## ########
//
//################################################## ################################################## ################################################## ########
// ###################################### MANUAL BUY MANUAL BUY 
//MANUAL Buy MANUAL Buy MANUAL Buy 
//###################################
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//function fManBuyPositions(ib, oState, OID, positions)	

//if(DebugOn) _TRACE("#, ManBuy top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1)); 
//newState = oState; 
// this function closes all open trades
//orderID = ";
//orderID = ib.PlaceOrder(sTicker, "Buy", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManBuy";
//newState = ordManBuy; 
//StaticVarSet(VarPfx + "TargetPositions", positions + pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID );
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True); 
//if(DebugOn) _TRACE("#, ManBuy " + ordType + ", " + fFormatTime(sysTimeStr) +
//", OrderID" + orderID + ", OrderState=" + fCvtState(newState) + 
//", Close=" + NumToStr(LastValue(Close), 1.2)); 

//return newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ################################# MANUAL SELL MANUAL SELL MANUAL
//Sell MANUAL Sell MANUAL Sell 
//###################################
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//function fManSellPositions(ib, oState, OID, positions) // we are neither long or Short


//if(DebugOn) _TRACE("#, ManSel1 top, positions=" + NumToStr(positions, 1) + ",
//contracts=" + NumToStr(pContracts, 1)); 
//newState = oState; 
//orderID = "";
//orderID = ib.PlaceOrder(sTicker, "SELL", pContracts, "MKT", 0, 0, "GTC", True,
//tickMult, "outsideRTH");
//if(orderID != "")

//ordType = "ManSell";
//newState = ordManSell; 
//StaticVarSet(VarPfx + "TargetPositions", positions - pContracts);
//StaticVarSetText(VarPfx + "ordID", orderID);
//StaticVarSet(VarPfx + "GetStatus", True);
//StaticVarSet(VarPfx + "WaitForConfirm", True); 
//if(DebugOn) _TRACE("#, ManSel1, " + ordType + ", Time=" +
//fFormatTime(sysTimeStr) + ", OrderID=" + orderID + 
//", OrderState=" + fCvtState(newState) + ", Close=" +
//NumToStr(LastValue(Close), 1.2)); 

//return newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ###################################### CANCEL CANCEL CANCEL 
//CANCEL CANCEL CANCEL ######################################
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//function fCancelPositions(ib, oState, OID, positions)	// we are neither long or Short

// trigger - trg defines the type of order

//newState = oState; 
// this if statement prevents making multiple orders - subsequent orders are ignored 

//if( oState == ordSell OR oState == ordShort)

//if(OID != "") // used to cancel a sell order that has not been filled 

//newState = ordCancelSell;
//ordType = "CancelSell";
//ib.CancelOrder(OID); 
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 1, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState =" + fCvtState(newState) + ", OrderID=" + OID); 




//else if(oState == ordBuy OR oState == ordCover)

//if(OID != "") // used to cancel a buy order that has not been filled

//newState = ordCancelBuy;
//ordType = "CancelBuy";
//ib.CancelOrder(OID); 
//StaticVarSet(VarPfx + "GetStatus", True);
//if(DebugOn) _TRACE("#, Cancel 2, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + OID); 




//return newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ###################################### BUY BUY BUY BUY 
//Buy Buy Buy 
//################################################## #
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//function fBuyPositions(ib, oState, OID, positions)	// we are neither long or Short

// trigger - trg defines the type of order

//wState = oState; 
//ice = LastC;
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", " + NumToStr(OrderType == "MKT", 1)); 

// this if statement prevents making multiple orders - subsequent orders are ignored

//( oState == ordNone AND OID == "")	// program trade and no open positions or pending order sent orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "BUY", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "BUY", 
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "BUY", 
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//(DebugOn) _TRACE("#, Buy, OrderType= " + OrderType + ", OID=" + ORderID );

//(orderID != "")

//dType = "ProgBuy";
//wState = ordBuy;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True); 
//(DebugOn) _TRACE("#, Buy, " + ordType + ", Time" + fFormatTime(sysTimeStr)+ ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(LastC, 1.2)); 




//turn newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ################################# SHORT SHORT SHORT SHORT Short 
//################################################## ####################
//
//################################################## ################################################## ################################################## ######
//
//################################################## ################################################## ################################################## ######

//nction fShortPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState; 
//ice = LastC;
//(DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + OID + ", "+ NumToStr(OrderType == "MKT", 1)); 

//( oState == ordNone AND OID == "") // no sell order sent and no positionAND no current order orderID = "";



//(OrderType == "MKT") orderID = ib.PlaceOrder(sTicker, "SELL", pContracts,"MKT", 0, 0, "GTC", True, tickMult, "outsideRTH");

//se if(OrderType == "STP") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "STP", 0, price, "GTC", True, tickMult, "outsideRTH");
//se if(OrderType == "LMT") orderID = ib.PlaceOrder(sTicker, "SELL",
//ontracts, "LMT", price, 0, "GTC", True, tickMult, "outsideRTH");
//DebugOn) _TRACE("#, Short, OrderType= " + OrderType + ", OID=" + ORderID ); if(orderID != "")



//dType = "ProgShort";
//wState = ordShort;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True); 
//(DebugOn) _TRACE("#, Short, " + ordType + ", Time=" + fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Price=" + NumToStr(price, 1.2)); 




//turn newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ################################# SELL SELL SELL SELL SELLSell Sell 
//################################################## #####
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
//nction fSellPositions(ib, oState, OID, positions) // we are neither long or Short


//wState = oState; 
//( oState == ordNone ) // close a long position

// exit the current position with a market order orderID = "";

//derID = ib.PlaceOrder(sTicker, "SELL", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "ProgSell";
//wState = ordSell;
//aticVarSetText(VarPfx + "ordID", orderID);
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True); 
//(DebugOn) _TRACE("#, Sell, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2)); 



//turn newState; // return the type of order that was made


//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ################################ COVER COVER COVER COVER Cover Cover Cover 
//############################################
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//nction fCoverPositions(ib, oState, OID, positions)	// we are neither long orShort


//wState = oState; 
//( oState == ordNone ) // program cover and go flat

//derID = "";
//derID = ib.PlaceOrder(sTicker, "BUY", abs(positions), "MKT", 0, 0, "GTC",True, tickMult, "outsideRTH");

//dType = "progCover";
//wState = ordCover;
//aticVarSetText(VarPfx + "ordID", orderID); 
//aticVarSet(VarPfx + "GetStatus", True);
//aticVarSet(VarPfx + "WaitForConfirm", True); 
//(DebugOn) _TRACE("#, Cover, " + ordType + ", Time=" +fFormatTime(sysTimeStr) + ", OrderState=" + fCvtState(newState) + ", OrderID=" + orderID + ", Close=" + NumToStr(LastValue(Close), 1.2)); 



//turn newState; // return the type of order that was made



//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########
// ############	Order Precessing Loop	Order Precessing Loop	Order Precessing
//op	Order Precessing Loop	Order Precessing Loop #######################
//################################################## ################################################## ################################################## ########
//################################################## ################################################## ################################################## ########

//( StaticVarGet(VarPfx + "AutoTrading") == True AND // auto trading parameter is set on IntervalOK AND // chart is the same interval as the Chart period selected sTicker == Name() ) // the chart symbol is the same as the ticker parameter ibc = GetTradingInterface("IB");





//(ibc)ConnectedStatus = ibc.IsConnected();	// get the connection status, 2 is OK

// the foloowing code closes trades at the end of the day.
// it does this in steps. 1) cancels all open orders. 2) Closes all positions.3) resets the control var EOD EodVar = StaticVarGetText(VarPfx + "EOD"); i//sysTime == closeTime + 1 AND EodVar == "") // this is the close time r + 1 seconds paramete ibc.CancelAllPendingOrders(sTicker);






//aticVarSetText(VarPfx + "EOD", "Cancel");
//RACE("#, ##### CancelAll end of day #####"); 


//(sysTime == closeTime + 5 AND EodVar == "Cancel") // this is the close time parameter + 5 seconds ibc.CloseAllOpenPositions(sTicker);



//aticVarSetText(VarPfx + "EOD", "Close");
//RACE("#, ##### CloseAll end of day #####"); 


//(sysTime == closeTime + 8 AND EodVar == "Close") // this is the close time parameter + 8 seconds 


//c.CloseAllOpenPositions(sTicker);
//aticVarSetText(VarPfx + "EOD", "");
//RACE("#, ***** Reset EOD static var *****"); 

// end of close trades at ene of day

// this is where the trade processing is done
//( sysTime < closeTime AND (ConnectedStatus == 2 OR ConnectedStatus == 3) )
// connected to TWS with no error messages

//(StaticVarGet(VarPfx + "SystemInitialized") == True)

//aticVarSet(VarPfx + "SystemInitialized", False); 
//c.CancelAllPendingOrders(); // cancel any open orders on start or reset


// retrieve static variables
//mPositions = ibc.GetPositionSize(sTicker); 
//aticVarSet(VarPfx + "numPositions", numPositions);

//(DebugOn) _TRACE("#, SysLoop 0, Positions=" + NumToStr(StaticVarGet(VarPfx+ "numPositions"), 1.0) + ", GetStatus=" + NumToStr(GetStatus, 1.0) + ", OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", WaitForConfirm=" + NumToStr(WaitForConfirm, 1.0) + "\n" ); 





// GetStaus = false indicates TWS has completed processing the order
// Wait for the trade to be confirmed by a change in the number of positions before resetting the order state AND waitforconfirm flag

// this is used to prevent placing an order if the signal is still active after a filled Status from TWS

//(WaitForConfirm AND !GetStatus)

//(DebugOn) _TRACE("#, WaitForConfirm, OrderState = " +fCvtState(OrderState) + "\n");

// note: WaitForConfirm set false if order cancelled, see GetStatus Cancelled logic

//(	(OrderState == OrdBuy AND numPositions > 0) OR 
//rderState == OrdShort AND numPositions < 0) OR
//rderState == OrdCover AND numPositions == 0) OR 
//rderState == OrdSell AND numPositions == 0) )

//(DebugOn) _TRACE("#, Program trade WaitForConfirm complete"); 
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False); 

// user made a manual order so wait for the number of positions to indicate the purchase before resetting order state AND waitforconfirm flags else if(OrderState == ordManBuy OR OrderState == ordManSell



//(DebugOn) _TRACE("#, Manual trade processed, target positions=" + NumToStr(StaticVarGet(VarPfx + "TargetPositions"), 1.0));

//( numPositions == StaticVarGet(VarPfx + "TargetPositions"))	

//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//aticVarSet(VarPfx + "WaitForConfirm", False); 
//aticVarSet(VarPfx + "TargetPositions", 0);


// user requested close all positions so wait for the number of positions to indicate all positions are closed before resetting

// order state AND waitforconfirm flags else if(OrderState == ordCloseAll ) 


//(numPositions == 0) 

//(DebugOn) _TRACE("#, Close all processed"); 
//derState	= ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
//aticVarSet(VarPfx + "GetStatus", False); 
//aticVarSet(VarPfx + "WaitForConfirm", False); 

// end close all


//################################################## ################################################## ################################################## ########
// ################### Trigger Control Trigger Control Trigger ontrol Trigger Control Trigger Control Trigger Control 
//####################
// ################### This section takes the indicator timing andconverts it to one shot triggers required for orders. 
//####################
//################################################## ################################################## ################################################## ########

// waitforconfirm and getstatus flags are used to prevent multiple orderswhile a current order is being processed

// orders are onluy allowed if the waitforconfirm and getstatus flags are False


//yTrigger = SellTrigger = ShortTrigger = CoverTrigger = False;
//(DebugOn) _TRACE("#, AllowInd 0, Indicator, Buy=" + NumToStr(BuyInd, 1.0) + ", Sell=" + NumToStr(SellInd, 1.0) + ", Short=" + NumToStr(ShortInd, 1.0) + ", Cover=" + NumToStr(CoverInd,	1.0));	



//(!WaitForConfirm AND !GetStatus ) // allow indicators to pass unless a trade to being processed {


// This is sequence sensitive. cover and sell should close positions before
//w positions are taken.
// ********** CAUTION *****************
// but note that if your system does not generate the sell and cover signals
//e order process can hang AND NOT allow trades
// Pause parameter blocks all programmed trading 
//( numPositions > 0 AND SellInd AND !Pause) // sell is only allowed when there are a positive number of positions


//llTrigger = True; 
//(DebugOn) _TRACE("#, AllowInd 1 Sell trigger"); 

//se if( numPositions < 0 AND CoverInd AND !Pause) // cover is only allowed when there are a negative number of positions


//verTrigger = True; 
//(DebugOn) _TRACE("#, AllowInd 2 Cover trigger"); 

//se if( !Pause AND numPositions == 0 ) // buy and short is only allowed when there are no positions


//(BuyInd ) 

//yTrigger = True; 
//(DebugOn) _TRACE("#, AllowInd 3, Buy trigger"); 

//se if(ShortInd ) 

//ortTrigger = True; 
//(DebugOn) _TRACE("#, AllowInd 4, Short trigger"); 


// end allowIndicators 

// signal reversal and we have open an order and the trend changes direction
//se if ( WaitForConfirm AND numPositions == 0) // Reversal signal with an Open order


//(DebugOn) _TRACE("#, Reversal Cancel 0");
//( (OrderState == ordBuy OR OrderState == ordCover ) AND SellInd) 

//llTrigger = True; 
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone); 
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False); 
//(DebugOn) _TRACE("#, Reversal Cancel 1, SellTrigger=" + NumToStr(SellTrigger, 1.0));


//se if( (OrderState == ordShort OR OrderState == ordSell ) AND CoverInd ) 

//verTrigger = True; 
//derState == OrdNone; StaticVarSet(VarPfx + "OrderState", OrdNone); 
//itForConfirm = False; StaticVarSet(VarPfx + "WaitForConfirm", False); 
//(DebugOn) _TRACE("#, Reversal Cancel 2, CoverTrigger=" +NumToStr(CoverTrigger, 1.0));



//(DebugOn) _TRACE("#, AllowInd End, Buy=" + NumToStr(BuyTrigger, 1.0) + ",

// Short=" + NumToStr(ShortTrigger, 1.0) + ", Cover=" + Sell=" + NumToStr(SellTrigger, 1.0) + NumToStr(CoverTrigger, 1.0));


//################################################## ################################################## #############################################
// ######## Stateless processes Stateless processes Statelessprocesses Stateless processes Stateless processes ############
//################################################## ################################################## #############################################
//(CancelAll)

//c.CancelAllPendingOrders(sTicker); 
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", OrderState);
//dType = "CancelAll";
//aticVarSet(VarPfx + "WaitForConfirm", False); 
//aticVarSet(VarPfx + "GetStatus", False); 
//(DebugOn) _TRACE("#, Trigger CancelAll, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID); 

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");

//se if(CloseAll )

// close all positions
//c.CancelAllPendingOrders(sTicker); 
//c.CloseAllOpenPositions(sTicker);
//derState = ordCloseAll; StaticVarSet(VarPfx + "OrderState", OrderState );
//dType = "CloseAll";
//aticVarSet(VarPfx + "GetStatus", True); 
//aticVarSet(VarPfx + "WaitForConfirm", True); 
//(DebugOn) _TRACE("#, ***** Trigger CloseAll " + ordID + ", OrderState="+ fCvtState(OrderState) + ", SysTime =" + NumToStr(SysTime, 1.0, False) + " ****"); 



//se if(!GetStatus AND ManualBuy)	// manual buy the number of contractsdefined in pContracts	

//ate = fManBuyPositions(ibc, OrderState, ordID, numPositions); 
//aticVarSet(VarPfx + "OrderState", state); 

//se if(!GetStatus AND ManualSell)	// manual sell number of contracts definedin pContracts

//ate = fManSellPositions(ibc, OrderState, ordID, numPositions); 
//aticVarSet(VarPfx + "OrderState", state); 


//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
// ########## Program Trading Program Trading ProgramTrading Program Trading Program Trading #################
// ########## Note that the order is sequence sensitive as sell andCover should be processed before Buy AND Short. #################
//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
//se if(!WaitForConfirm ) // not waiting for a trade to settle

//( SellTrigger AND numPositions > 0) // sell to go flat

//ate = fSellPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, Trigger ordSell, OrderState=" + fCvtState(state));


//se if( CoverTrigger AND numPositions < 0) // buy to go flat

//ate = fCoverPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, Trigger ordCover, OrderState=" + fCvtState(state));


//se if( BuyTrigger )

//ate = OrderState;
//(numPositions == 0)	// buy n contracts
//ate = fBuyPositions(ibc, OrderState, ordID, numPositions); 
//se if(numPositions < 0) // close short position first then go long after flled state = fCoverPositions(ibc, OrderState, ordID, numPositions); 


//derState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, Trigger ordBuy, OrderState=" + fCvtState(state)); 

//se if( ShortTrigger )

//ate = OrderState;
//(numPositions == 0)	// sell n contracts state = fShortPositions(ibc, OrderState, ordID, numPositions); 

//se if(numPositions > 0) // close long first then go short after filled state = fSellPositions(ibc, OrderState, ordID, numPositions);

//erState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, Trigger ordShort, OrderState=" + fCvtState(state));




//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
// ########## Order Status Processing Order Status Processing Order Status Processing Order Status Processing #################
//################################################## ################################################## #############################################
// ### order states ordNone = 20; ordCancelBuy = 21; ordCancelSell = 22; rdSell = 23; ordBuy = 24; ordCover = 25; ordShort = 26; 
// ### ordCancelAll = 27; ordCloseAll = 28; ordManBuy = 29; ordManSell = 30;

//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
//dID = StaticVarGet(VarPfx + "ordID");
//(DebugOn) _TRACE("#, OrdState 0, GetStatus=" + NumToStr(GetStatus, 1.0) +", Positions=" + NumToStr(numPositions, 1.0) + ", OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID + ", Time=" +	fFormatTime(sysTimeStr));	



// process the status messages after an order has been sent or cancelled tempStatus = "None";

//(GetStatus)

//mpStatus = ibc.GetStatus( ordID, True ); // get order status 
//(tempStatus == "Filled")

// make sure the numPositions is true for the operation being conducted
// this prevents another order as soon as this one is filled
//aticVarSet(VarPfx + "GetStatus", False); 
//( OrderState == ordCancelSell OR OrderState == ordCancelBuy )

//derState = ordNone; 
//aticVarSet(VarPfx + "OrderState", OrderState ); 

//(DebugOn) _TRACE("#, OrdState 1 Filled, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID);

//dID = ""; StaticVarSetText(VarPfx + "ordID", "");
// end filled
//se if(tempStatus == "PreSubmitted" OR 
//mpStatus == "PendingSubmit" OR 
//mpStatus == "Pending" OR 
//mpStatus == "ApiPending" OR 
//mpStatus == "Submitted"	)

//( numPositions != 0 AND (OrderState == ordCancelSell OR OrderState ==
//dCancelBuy ))

//derState = ordNone; 
//aticVarSet(VarPfx + "OrderState", OrderState ); 
//aticVarSet(VarPfx + "GetStatus", False); 

//(CoverTrigger AND (OrderState == ordShort OR OrderState == ordSell))

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, OrdState 2a, CancelSell, OrderState=" + fCvtState(state)); 


//se if(SellTrigger AND (OrderState == ordBuy OR OrderState == ordCover))

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 
//(DebugOn) _TRACE("#, OrdState 2c, CancelBuy , OrderState=" + end Status preSubmitted OR Pending


//se if(tempStatus == "Cancelled")

//aticVarSet(VarPfx + "GetStatus", False); 
//aticVarSet(VarPfx + "WaitForConfirm", False); 
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//(DebugOn) _TRACE("#, OrdState 3 Cancel, OrderState=" +fCvtState(OrderState) + ", OrderID=" + ordID + ", Positions=" + NumToStr(numPositions , 1.0) +"\n");	ordID = ""; StaticVarSetText(VarPfx + "ordID", ""); 





//se if(tempStatus == "Error")

//g = ibc.GetLastError(0); 
//ror = fErrorProcessor(msg); 
//(DebugOn) _TRACE("#, OrdState 4, Error code=" + Error ); 
//aticVarSet(VarPfx + "SetErrorState", True);	
// NOTE: For error not listed below look at the message notes at the end of the program to see how OR if they were handled.trading hours

//(Error == "135" OR Error == "2106" OR Error == "2109") // out of normal


//aticVarSet(VarPfx + "GetStatus", False); 
//derState = ordNone; StaticVarSet(VarPfx + "OrderState", ordNone);
//dID = ""; StaticVarSetText(VarPfx + "ordID", ""); 

//se if(Error == "201")

//(OrderState == ordShort OR OrderState == ordSell)

// call Cancel to cancel the sell order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 

//se if(OrderState == ordBuy OR OrderState == ordCover)

// call Cancel to cancel the buy order and set up to reverse
//ate = fCancelPositions(ibc, OrderState, ordID, numPositions); 
//derState = state; StaticVarSet(VarPfx + "OrderState", state); 




//(DebugOn) _TRACE("#, OrdState 10 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID); 



// end status errorelse 


//(DebugOn) _TRACE("#, OrdState 11 Unexpected status=" + tempstatus + ",OrderState=" + fCvtState(OrderState) + ", OrderID=" + ordID); 



// end get status	

//(	StaticVarGet(VarPfx + "SetErrorState") == True) 

//rorMsg = ibc.GetLastError(ordID); 
//(errorMsg == "None" OR errorMsg == "")
//aticVarSet(VarPfx + "SetErrorState", False); else


//tChartBkColor( colorTan); 
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );	
//structions = "\n Determine what the error is. Use trace if necessary.\n 
//ncel OR Close all orders on TWS.\n Press Reset to continue.";	
//otText( "Error " + errorMsg + instructions, BarCount - VisibleBars / 2, 
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);

//(DebugOn) _TRACE("#, Unexpected error msg=" + errorMsg + ", OrderState="+ fCvtState(OrderState) + ", OrdID=" + OrdID);




//se if (Pause )

//tChartBkColor( colorLightGrey); 
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );	
//otText( "######\nTrading\nPaused\n######", BarCount - VisibleBars / 2, 
//stValue( ( HHV(H, VisibleBars) + LLV(L, VisibleBars)) / 2), colorWhite,colorBlack);


//(ConnectedStatus == 2) stat = "Connected."; else if(ConnectedStatus == 3)stat = "Connected with warnings.";

//(StaticVarGet(VarPfx + "ConnectOK") == False) 
//aticVarSet(VarPfx + "ConnectOK", True); 
//intf("\nStatus:" + 
//n Symbol = " + sTicker + 
//n TWS " + stat + 
//n Last TWS message = " + errorMsg + 
//n Order ID = " + WriteIf(ordID != "", OrdId, "None") + 
//n OrderState = " + fCvtState(OrderState) + 
//n Order Status = " + tempStatus +
//n Positions = " + NumToStr(Nz(numPositions), 1.0, False) );
// end is connected
//se if( ConnectedStatus == 0 OR ConnectedStatus == 1) // lost connection

// handle commection errors 
//(ConnectedStatus == 0) stat = "Not Connected."; else if(ConnectedStatus ==
// stat = "Lost Connection.";
//tChartBkColor( colorYellow);	
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );	
//otText( "TWS not connected. Some reasons are:\nTWS error message: " +errorMsg + "\nIncoming connection has not been accepted.", BarCount -VisibleBars / 2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack);	printf("\nTWS Status: " + stat + "\n");



// end connection error	
//se if (sysTime > closeTime)

//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );	
//otText( "###########\nMarket closed\n###########", BarCount - VisibleBars /2, LastValue(HHV(H, VisibleBars)), colorWhite, colorBlack);


// end if ibc
// end order processing loop

//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
// ########## Commentary	Commentary	Commentary	Commentary	Commentary	Commentary	Commentary	Commentary ################
//################################################## ################################################## #############################################
//################################################## ################################################## #############################################

//se // autotrade is off due to an error or trading is turned off

// if error state, display state in title bar
// feedback key info into title bar
//tChartBkColor( colorPink);
//xt = "\nStatus: \nAutoTrading is off. Some of the reasons are:\n" +	" 1. Autotrading is turned off\n" +	" 2. TWS has not been started or isn't functioning.\n" + " 3. Set chart to " + sTicker + ".\n" + " 4. Chart period mismatch.\n";



// end text

//intf(text);
//sibleBars = Status( "LastVisibleBar" ) - Status( "FirstVisibleBar" );	
//otText(text, BarCount - VisibleBars / 2, LastValue(HHV(H, VisibleBars)),
//lorWhite, colorBlack);


//ECTION_END(); 

//################################################## ################################################## #############################################
//################################################## ################################################## #############################################
// ########## Setup and WARNINGS Setup and WARNINGS Setup andWARNINGS Setup AND WARNINGS ##############
//################################################## ################################################## #############################################
//################################################## ################################################## #############################################

// Before Auto trading will trade orders and have them filled automatically you must register your copy of IB Controller. See File>Enter unlock code.

// if it is NOT registered the order will be sent but a T will appear on TWS andthe order will NOT be transmitted to the market. 

// Once IBC is registered AND the code is entered orders will be processed automatically.BrokerIB.exe ( IB Controller) of 1.2.1 OR above.


// This release level requires TWS 888.3 or above, IB.DLL of 1.8.2 or above, and

// These are required to handle after hours trading and back filling. Thisprogram will NOT work correctly unless these releases are installed.
// TWS may also require an update to JAVA. Check their site for recommendations.
 
Last edited:
#9
Code:
//=================================
// Show diem ho^~ tro. va` khang' cu. ko?
//=================================

plotFractals = ParamToggle("Plot Fractals","Off|On",1);
if(PlotFractals)
{
PlotShapes(shapeSmallCircle*P1,colorYellow,0,H,10) ;
PlotShapes(shapeSmallCircle*V1,colorBlue,0,L,-10);
}
Hi, in reference to the harmonic pattern alf code. there is a YELLOW and BLUE dot that appears which is the PEAK and SUPPORT...

How can I use that to scan what stock hits those dots?

Thanks