// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("Auto Tread V.1");
// Parameter Setting //
StoLength = Param("STOLength",14,1,20,1);
SmoothK   = Param("SmoothK",3,1,7,1);
SmoothD   = Param("SmoothD",3,1,7,1);
Overbought = 80 ;
Oversold =20 ;
Center = 50 ;
FastPeriod = Param("FastMA",12,3,20,1);
SlowPeriod = Param("SlowMA",26,20,40,1);
PctChange = 0.1;

// Slow Stochastic  
upper=HHV(High,StoLength);
lower=LLV(Low,StoLength);
oscillator=(Close-lower)/(upper-lower)*100; 
K = MA(oscillator,SmoothK);
D = MA(K,SmoothD);

//MA
FastMA = MA(Close,FastPeriod);
SlowMA = MA(Close,SlowPeriod);



// Buy Condition //
PrebuyCon1 = K < 50;
PrebuyCon2 = Cross(K,D);
PrebuyCon3 = FastMA < SlowMA ;
buysignal =  PrebuyCon1 AND PrebuyCon2 AND PrebuyCon3 ;

//BuyPreCond = Trough(C,PctChange,1) > Trough(C,PctChange,2);
//BuyTrigger = C > Peak(C,PctChange,1);
//buysignal = BuyPreCond AND BuyTrigger;
//buysignal = Cross(FastMA,SlowMA);



// Sell Condition
//sellsignal = ApplyStop(stopTypeLoss,stopModePercent,4);
//cutloss = Close < buysignal;
//sellsignal = IIf(cutloss,Close,Cross(SlowMA,FastMA));
sellsignal = Cross(SlowMA,FastMA);

//SellPreCond = Peak(C,PctChange,1) < Peak(C,PctChange,2);
//SellTrigger = C < Trough(C,PctChange,1);
//sellsignal = SellPreCond AND SellTrigger;
//sellsignal = SellPreCond;

/*
a = Cross(D,K);
b = Cross(ma26,ma12);
SellSignal = IIf( K >Overbought,a,IIf(K < Overbought AND K > OverSold,b,IIf(K < OverSold,a,b)));
*/
//PreSellCon1 = Cross(ema26,ema12);
//PreSellCon2 = K < D;
//SellSignal = PreSellCon1 AND PreSellCon2;
//SellSignal = Cross(D,K);

// Buy and Sell
Buy = ExRem(buysignal,sellsignal);
Sell = ExRem(sellsignal,buysignal);
Bullish = BarsSince(Buy) < BarsSince(Sell);
Bearish = BarsSince(Sell) < BarsSince(Buy);


// Plots //
Plot(FastMA,"FastPeriod",colorGreen,styleLine);
Plot(SlowMA,"SlowPeriod",colorRed,styleLine);
BarColor = IIf(Bullish,colorGreen,IIf(Bearish,colorRed,colorDefault));
PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low,-20);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High,-20);
Plot(Close,"Price",BarColor,GetPriceStyle());


ZigZagLine = Zig(C,PctChange);
Plot(ZigZagLine,"Zig Zag",colorBlack,styleLine);
//PlotShapes(ExRem(Trough(Low,PctChange,1),buysignal)*shapeHollowUpTriangle,colorBrown,0,Low,-20);
//PlotShapes(cutloss*shapeUpTriangle,colorBlueGrey,0,Low,-20);



/*
Plot(K,"%K",colorBlue,styleLine);
Plot(D,"%D",colorRed,styleLine);
Plot(Overbought, "",colorRed,styleDashed) ;
Plot(Oversold, "",colorGreen,styleDashed) ;
Plot(Center, "",colorBlueGrey, styleDashed) ;
*/

// System Test //
MaxPosition = 50;
SetPositionSize(100/MaxPosition,spsPercentOfEquity);
SetOption("MaxOpenPositions",MaxPosition);


_SECTION_END();