// Downloaded From https://www.WiseStockTrader.com
/* 
NAME:Profit_Alligator.afl
   
   Trading Chaos
   New Trading dimension
   Trading Chaos 2 edition
Edit:nEw
Date:14/09/2016
*/

/*Money Management*/
// Initial Capital 
SetOption("InitialEquity", 50000 );
// Commission is set to 0.1%
SetOption("CommissionMode",1);
SetOption("CommissionAmount",0.1); 


// Maximum position sizes 
MaxPos = 30;/*amout stock at buy per signal */
SetOption("MaxOpenPositions", MaxPos);

// Buy/Sell at ATO one day after the signals are triggered

SetTradeDelays(1,1,0,0);  
RoundLotSize = 100;

BuyPrice =  Open;
SellPrice =Open;    


_SECTION_BEGIN("Price");
Plot(C,"Close",ParamColor("Color",colorBlack),styleBar|ParamStyle("Style")|GetPriceStyle());
_N(Title = StrFormat("Profitunity:{{NAME}} - {{INTERVAL}} {{DATE}} O %g,h %g,L %g,C %g (%.1f%%) "+" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
_SECTION_END();

//1.Alligator
_SECTION_BEGIN("Alligator");

// Define Value
P= ParamList("Price", "Close|(H+L)/2|(H+C+L)/3",1);
 
if (P=="Close")
   A = C;
    
else
if (P=="(H+C+L)/3")
   A = (H+C+L)/3;
else
  A = (H+L)/2;

/*Line Alligator*/
AlligatorBlue=Ref(Wilders(A,13),-8);
AlligatorRed=Ref(Wilders(A,8),-5);
AlligatorGreen=Ref(Wilders(A,5),-3);
/*plot 3 alligators*/
PlotAlligator=ParamToggle("Plot Alligator?","NO|YES",1);
if(PlotAlligator)
{
Plot(AlligatorBlue,"Jaw",colorBlue,styleLine|styleThick);
Plot(AlligatorRed,"Teeth",colorRed,styleLine|styleThick);
Plot(AlligatorGreen,"Lips",colorGreen,styleLine|styleThick);
//require entry ws3 : open>AlligatorRed
AlligatorEntry=0>AlligatorRed;
}
_SECTION_END();

//2.fractals
_SECTION_BEGIN("Fractal");
UpFractal=ValueWhen(
    (Ref(H,-2) > Ref(H,-4)) AND
    (Ref(H,-2) > Ref(H,-3)) AND
    (Ref(H,-2) > Ref(H,-1)) AND
    (Ref(H,-2) > H),Ref(H,-2));

DownFractal=ValueWhen(
    (Ref(L,-2) <= Ref(L,-4)) AND
    (Ref(L,-2) <= Ref(L,-3)) AND
    (Ref(L,-2) <= Ref(L,-1)) AND
    (Ref(L,-2) <= L),Ref(L,-2));
/*plot alligator Fractal Up and Fractal Down*/
PlotFractalUp=ParamToggle("Plot Fractal Up?","NO|YES",1);
if (PlotFractalUp)
{
Plot(UpFractal,"UF",ParamColor("Up Fractal Color",colorBlue),ParamStyle("Up Fractal Style",styleThick|styleDashed));
}
PlotFractalDown=ParamToggle("Plot Fractal Down?","NO|YES",1);
if (PlotFractalDown)
{
Plot(DownFractal,"DF",ParamColor("Down Fractal Color",colorRed),ParamStyle("Up Fractal Style",styleThick|styleDashed));
}
UF=UpFractal;
DF=DownFractal;
_SECTION_END();


_SECTION_BEGIN("Tick");
/* Tick rules specifically for*/
Tick=IIf(C<=200,1,
          IIf(C>200 AND C<=500,5,
          IIf(C>200 AND C<=500,5,
          IIf(C>500 AND C<=2000,10,
          IIf(C>2000 AND C<=5000,25,
          IIf(C>5000,50,0))))));

nTick=Param("Buy Tick",1,1,2,1)*Tick;
ZoneTick=Param("Zone Tick",2,1,4,1)*Tick;
_SECTION_END();

// Liquidity is larger than 10 MB per day (on average)
Liquid = MA(C*V,60) > 10e6;
// The market is in a good condition trade
SetForeign("SET",True);
    SETBuyCon =  RSI()>EMA(RSI(),20) ;        
RestorePriceArrays();

//4.AO
//Calculate AO
AO = MA(A, 5) - MA(A, 34);

// Determine AO UpBar and DownBar
AOUpbar=AO>Ref(AO,-1);
AODownBar=AO<Ref(AO,-1);

//Determine AO Sourcer Buy and Sell
SoucerUp = Ref(AO ,-2) > Ref(AO ,-1) AND Ref(AO ,-1) < AO ;
SoucerDown = Ref(AO ,-2) < Ref(AO ,-1) AND Ref(AO ,-1) > AO ;

AOSoucerBuy = SoucerUp AND (AO  > 0 AND Ref(AO ,-1) > 0 AND Ref(AO ,-2) > 0);
AOSoucerSell = SoucerDown AND (AO  < 0 AND Ref(AO ,-1) < 0 AND Ref(AO ,-2) < 0);

 
 //Signal AO Cross Buy and Sell
AOCrossBuy = AO  > 0 AND Ref(AO ,-1) < 0;
AOCrossSell = AO  < 0 AND Ref(AO ,-1) > 0;
 
BuyAO = AOSoucerBuy OR AOCrossBuy;
SellAO = AOSoucerSell OR AOCrossSell;

//Determine TwinPeaksBuy 
LatestLowPeak = IIf(AO < 0, Ref(LowestSince(AOCrossSell, AO, 1), -1), 0);
TwinPeaksBuy = AO < 0 AND Ref(AODownBar, -1) AND AOUpBar AND Ref(AO,-1) > LatestLowPeak;
 
//Move latest lowest peak to the new one created now:
LatestLowPeak = IIf(TwinPeaksBuy, Ref(AO,-1), LatestLowPeak); 
 
 
//PlotShapes( IIf(TwinPeaksBuy ,shapeDigit3,0) ,colorBlue, 0, 0,12);
 
//Determine TwinPeaksSell  
LatestHighPeak = IIf(AO > 0, Ref(HighestSince(AOCrossBuy,AO, 1), -1), 0);
TwinPeaksSell = AO > 0 AND Ref(AOUpBar, -1) AND AODownBar AND Ref(AO,-1) < LatestHighPeak ;

//Move latest highest peak to the new one created now: 
LatestHighPeak = IIf(TwinPeaksSell, Ref(AO,-1), LatestHighPeak ); 
 
//PlotShapes( IIf(TwinPeaksSell ,shapeDigit3,0) ,colorOrange, 0, 0,-12);


//Determine Super AO(ws2) Buy and Sell
SuperAOBuy=Ref(AODownBar,-3) AND Ref(AOUpBar,-2) AND Ref(AOUpBar,-1) AND AOUpBar;
SuperAOSell=Ref(AODownBar,-3) AND Ref(AODownBar,-2) AND Ref(AODownBar,-1) AND AODownBar;
BuyWS2=SuperAOBuy;
SellWS2=SuperAOSell;

//Determine signal single /Multi entry for WS2
PlotWS2E=ParamToggle("Plot Signal WS2 Single entry?","NO|YES",1);
if(PlotWS2E)
{
BuyWS2=ExRem(BuyWS2,SellWS2);
}

// Signal single Entry for WS2
SellWS2=ExRem(SellWS2,BuyWS2);

//Display Signal Buy and Sell WS2 --> triangle empty
PlotWS2=ParamToggle("Plot WS2?","NO|YES",1);
if(PlotWS2)
{
PlotShapes(IIf(SellWS2,shapeHollowSmallDownTriangle,0),colorOrange,0,H,-12);
PlotShapes(IIf(BuyWS2,shapeHollowSmallUpTriangle,0),colorBlue,0,L,-12);
}

//Requirement Buy WS3
BuyWS3=0<=UF AND C>UF AND H>=(UF+nTick) AND Ref(H,-1)<=UF AND AlligatorEntry AND Liquid;

//signal Sell WS3 between DownFractal and AlligatorRed,choose that more bearish
AlRed=AlligatorRed;
TS=IIf(((DF-nTick)<AlRed),AlRed,(DF-ntick));

SellWS3=C<=TS;
SellPrice=TS;

//Determine signal single /Multi entry for WS3
PlotWS3E=ParamToggle("Plot Signal WS3 Single entry?","NO|YES",1);
if(PlotWS3E)
{
BuyWS3=ExRem(BuyWS3,SellWS3);
}

//Signal Single Entry for WS3
SellWS3=ExRem(SellWS3,BuyWS3);

//Display Signal Buy and Sell WS3 --> triangle 
PlotWS3=ParamToggle("Plot WS3?","NO|YES",1);
if(PlotWS3)
{
PlotShapes(IIf(BuyWS3,shapeSmallUpTriangle,Null),colorBlue,0,L,-24);
PlotShapes(IIf(SellWS3,shapeSmallDownTriangle,Null),colorRed,0,H,-24);
}

//comment that appear of Window Interpretation
WriteIf(BuyWs2,"(WS2-Super AO Buy)- Place Buy Stop to buy 1 unit if price rises to"+WriteVal(H+Tick,1.0)+" or higher."," ");
WriteIf(SellWs2,"(WS2-Super AO Sell)- Place Sell Stop to sell 1 unit if price falls to"+WriteVal(L-Tick,1.0)+" or lower."," ");
WriteIf(BuyWs3,"(WS3-Fractal Breakout Buy)- Place Buy Stop to buy 1 unit if price rises to"+WriteVal(H+Tick,1.0)+" or higher."," ");
WriteIf(SellWs3,"(WS3-Fractal Down OR Alligator Red -Sell)- Place Sell Stop to Sell 1 unit if price falls to"+WriteVal(L-Tick,1.0)+" OR lower."," ");

//4.AC

AC=MA(AO-MA(AO,5),5);
 
ACUpbar = AC > Ref(AC,-1);
ACDownBar = AC < Ref(AC,-1);
 

  
//3 bars buy when in positive territory:
AllAbove0 = Ref(AC,-3) > 0 AND Ref(AC,-2) > 0 AND Ref(AC,-1) > 0;
SellA = Ref(ACUpbar,-3) AND Ref(ACDownBar,-2) AND Ref(ACDownBar,-1) AND ACDownBar AND AllAbove0;
 
//2 bars sell. If in negative territory or crossed below 0:
AllBelow0 = Ref(AC,-3) < 0 AND Ref(AC,-2) < 0 AND Ref(AC,-1) > 0;
CrossBelow0 = (Ref(AC,-2) > 0 AND Ref(AC,-1) < 0) OR (Ref(AC,-1) > 0 AND AC < 0);
SellB = Ref(ACUpbar,-2) AND Ref(ACDownBar,-1) AND ACDownBar AND (AllBelow0  OR CrossBelow0);
 
CrossAbove0 = (Ref(AC,-2) < 0 AND Ref(AC,-1) > 0) OR (Ref(AC,-1) < 0 AND AC > 0);
//3 bars buy when in negative territory:
BuyA = Ref(ACDownBar,-3) AND Ref(ACUpbar,-2) AND Ref(ACUpbar,-1) AND ACUpbar AND AllBelow0;
//2 bars buy. If in positive territory or crossed above 0:
BuyB = Ref(ACDownBar,-2) AND Ref(ACUpbar,-1) AND ACUpbar AND (AllAbove0 OR CrossAbove0);
 
BuyCrossAC=BuyA OR BuyB OR TwinPeaksBuy;
SellCrossAC=SellA OR SellB OR TwinPeaksSell;
 
//PlotShapes( IIf(Buy ,shapeUpArrow,0) ,colorGreen, 0, IIf(AC < 0, AC, 0),-12);
//PlotShapes( IIf(Sell ,shapeDownArrow,0) ,colorRed, 0, IIf(AC < 0, AC, 0),12);
 
//Commentary
//WriteIf(Buy, "Place Buy Stop to buy 1 unit if price rises to " + WriteVal(H+0.01)+" or higher. (AC+)",
//WriteIf(Sell, "Place Sell Stop to sell 1 unit if price falls to " + WriteVal(L-0.01)+" or lower. (AC-)",""));

//5.MFI
//----------------- MFI Definition -------------------------------
_SECTION_BEGIN("MFI");
D0 = (High-Low)/Volume>= Ref((High-Low)/Volume,-1) AND Volume >= Ref( Volume, -1 );// Green
D1 = (High-Low)/Volume< Ref((High-Low)/Volume,-1) AND Volume <Ref( Volume, -1 );// Red
D2 = (High-Low)/Volume>= Ref((High-Low)/Volume,-1) AND Volume < Ref( Volume, -1 );// Blue
D3 = (High-Low)/Volume< Ref((High-Low)/Volume,-1) AND Volume >= Ref( Volume, -1 );// Pink
 
dynamic_color = IIf( D0, colorBrightGreen, IIf( D3, colorPink, IIf( D1, colorRed, colorBlue)));
 
AlligatorMFI=IIf(D0,1,IIf(D1,2,IIf(D2,3,IIf(D3,4,0))));
 
Plot (4, "MFI", dynamic_color, styleOwnScale|styleArea|styleNoLabel|styleNoTitle, -0.5, 100  ); 

_SECTION_END();

_SECTION_BEGIN("Explore");
//buy=AlligatorEntry and BuyWS2 and BuyWs3 and BuyCrossAC and SETBuyCon and Liquid andBuyAO or TwinPeaksBuy;
//sell=SellWs2 or SellWs3 or  SellCCrossAC or SellAO TwinPeaksSell;
Buy=Liquid AND AlligatorEntry AND SETBuyCon OR BuyWS2 OR BuyWs3 AND BuyCrossAC AND BuyAO;
Sell=SellWs2 OR SellWs3 OR  SellCrossAC OR SellAO;
//BuyPrice = Open;
//SellPrice =Open;


VP = Param("Period for Avg Vol" , 10, 50, 240, 1);	// sets the period for the average volume calculation


Filter = Cross(C,(Ref(HHV(H,20),-1)))
//AND Bull

AND (MA((V*C),20)>1000000)
AND ((ROC(C,20)- ROC(Foreign("SET", "Close"),20))>0)
AND ((ROC(C,60)- ROC(Foreign("SET", "Close"),60))>0)
AND ((ROC(C,130)- ROC(Foreign("SET", "Close"),130))>0)
AND V > Ref(V,-1) AND V > Ref(V,-2) AND V > Ref(V,-3) AND V > Ref(V,-4) 
AND V > Ref(V,-5) AND V > Ref(V,-6) AND V > Ref(V,-7) AND V > Ref(V,-8)
AND V > Ref(V,-9) AND V > Ref(V,-10) ;




/**Add column of data scan in table*/
Action = WriteIf(Buy, "BUY", WriteIf(Sell, "SELL", "   "));
Result = WriteIf(Buy,"Buy",WriteIf(Sell,"Sell"," "));
AddTextColumn( WriteIf(Buy, "Buy" , "Sell" ) ,   "TRADE" ,  5 ,   IIf(Buy,colorYellow, colorWhite), IIf(Buy, colorDarkGreen, colorRed) );
AddTextColumn(IndustryID(1) ,"Industry Sector  ", 25.0, colorWhite, colorBlue, 125);     // adds a column for the industry sector 
AddColumn(C, "Close", 3.2,  colorBlue, colorYellow, 55); 										// adds a column for today's close
AddColumn(Ref(Close,-1),"Y-Close",1.2, IIf( ROC(Ref(C,-1),1)>=0,colorDarkGreen, colorRed ),50 );
AddColumn( ROC( Close, 1 ), "ROC(1)", 1.2, IIf( ROC(C, 1 ) >= 0,colorDarkGreen, colorRed));					
//AddColumn(BuyPrice, "BuyPrice" ,3.1, colorWhite,colorDarkGreen); 
//AddColumn(SellPrice, "SellPrice",3.1, colorYellow, colorDarkBlue, 75);								// adds a column for the close as a % from the prior close
AddColumn(V, "VOLUME",8.0, colorYellow, colorDarkGreen, 75);									// adds a column for today's volume									
//AddColumn( Ref(MA(V,VP),-1), WriteVal(VP, 2.0)+ " dMA", 8.0, colorWhite, colorBlue, 75);	// adds a column for the average volume

// Remove extra buy / sell signals
Buy = ExRem ( Buy, Sell );
Sell = ExRem ( Sell, Buy );

/**PLOT Arrow signal to BUY&SELL**/

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);



_SECTION_END();

_SECTION_BEGIN("Position");


/********  Position Size and Position Score ****/
 
// Invest equally in each stock
PositionSize = -100/MaxPos;  
 
// If there are more than one buy signals at a given time,
// the priority of the Buy is based on the ranking from
// position score. Here, our criterion is the ratio of 
// today's value with respect to the average past value
PositionScore = C*V/MA(C*V,60) ;
 
 
// Stop Loss ***************************************
// Exit next day if the loss is larger than 10 %
ApplyStop(stopTypeLoss,stopModePercent,10,2);
/* max loss stop optimization */
//ApplyStop(stopTypeLoss, stopModePercent, Optimize( "max. loss stop level", 10, 2, 30, 1 ),True ); 

/**-----------------END CODE-------------------------------------**/