//+------------------------------------------------------------------+
//|                  |
//|                http://KiloPip.Com
//|                                                                  |
//|  In no event will author be liable for any damages whatsoever.   |
//|                      Use at your own risk.                       |
//|                                                                  |
//+------------------- DO NOT REMOVE THIS HEADER --------------------+

#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Expert Advisor Builder"
#property link      "http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/"

extern double ShiChannelUserValue = 300;
extern bool UseMM = False;
extern double NoTradeATR = 100;
extern double E_GANN = 10;
extern double CMA =10;
extern double SAR1 = 0.02;
extern double SAR2 = 0.2;
extern int MagicNumber = 3300;
extern int LockPipsAfter = 350;
extern int lockprofit = 30;
extern bool SignalMail = True;
extern bool EachTickMode = False;
extern double Lots = 0.1;
extern int Slippage = 30;
extern bool UseStopLoss = False;
extern int StopLoss = 75;
extern bool UseTakeProfit =  False;
extern int TakeProfit = 200;
extern bool UseTrailingStop = False;
extern int TrailingStop = 50;

int p=1,lots;
double Pointz;

int BarCount;
int Current;
bool TickCheck = False;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;
   Pointz = Point;
   if (EachTickMode) Current = 0; else Current = 1;
   if (Digits == 5 || Digits == 3) p = 10; 
   Slippage = Slippage*p;
   TakeProfit = TakeProfit * p; 
   StopLoss = StopLoss * p;
   LockPipsAfter = LockPipsAfter * p;
   Pointz = Point * p;
   GlobalVariableSet(Symbol() + "GANN0",0);
   GlobalVariableSet(Symbol() + "LockPipsAfter",0);
  //if(NoTradeATR < 0) NoTradeATR = 0;
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {

GlobalVariableDel(Symbol() + "GANN0");
GlobalVariableDel(Symbol() + "LockPipsAfter");
  return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() {
   int Order = SIGNAL_NONE;
   int CloseCross = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;

   if (EachTickMode && Bars != BarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+

string indi = "Gann Hi-lo Activator SSL";
//string indi = "___Gann_HiLo_Activator_v2___";


//double ShiChannel = iCustom(NULL,0,"SHI_Channel_true",240,0,0,0);

double GANN0 = iCustom(NULL, 0, indi, E_GANN, 0, 0);
double GANN1HR = iCustom(NULL, 60, indi, E_GANN, 0, 0);
double MA0 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_MEDIAN, 0);
double GANS = iCustom(NULL, 0, indi, 1, 0, Current + 0);
double GANF = iCustom(NULL, 0, indi, E_GANN, 0, Current + 0);
double GANF2 = iCustom(NULL, 0, indi, E_GANN, 0, Current + 2);
double GANS2 = iCustom(NULL, 0, indi, E_GANN, 0, Current +2);

double GANNO1 = iCustom(NULL, 0, indi, E_GANN, 0, Current + 0);
double MA1 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_MEDIAN, Current + 0);
double GANN02 = iCustom(NULL, 0, indi, 10, 0, Current + 1);
double MA2 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_MEDIAN, Current + 1);
double QQE = iCustom(NULL,0,"QQE_Alert_MTF",5,0,0);

double QQE1 = iCustom(NULL,0,"QQE_Alert_MTF",5,0,0,0);
double QQE2= iCustom(NULL,0,"QQE_Alert_MTF",5,0,1,0);
double QQE3 = iCustom(NULL,0,"QQE_Alert_MTF",5,0,2,0);    

double SAR = iSAR(NULL, 0, SAR1,SAR2, 0);
double SAR1H = iSAR(NULL, 60, SAR1,SAR2, 0);

// double BBH=iBands(NULL, 0, BB, 2, 0, PRICE_CLOSE, 1, 0);
// double BBL=iBands(NULL, 0, BB, 2, 0, PRICE_CLOSE,3, 0);
 double MAFILTER = iMA(NULL, 0, 25, 0,MODE_SMMA , PRICE_MEDIAN, 0);
  double MAHLC = iMA(NULL,0,0,0,MODE_SMMA ,PRICE_WEIGHTED,0); 

   
   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol()) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+
                 double CloseBuy1_1 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_MEDIAN, Current + 0);
                double CloseBuy1_2 = iMA(NULL, 0, CMA, 0, MODE_SMA, PRICE_MEDIAN, Current + 0);
            
        if (CloseBuy1_1<GANN1HR) Order= SIGNAL_CLOSEBUY;
                if (GlobalVariableGet(Symbol() + "LockPipsAfter") == 0) {
                     if((Close[0] - OrderOpenPrice())/Point > LockPipsAfter) {
                     GlobalVariableSet("LockPipsAfterBuy", OrderOpenPrice() + lockprofit * Pointz);
                    OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + lockprofit * Pointz, OrderTakeProfit(), 0, MediumSeaGreen);
  
                    }
              } else {
                    if (Close[0] <= GlobalVariableGet(Symbol() + "LockPipsAfter")) 
                    Order = SIGNAL_CLOSEBUY;                
                 }
                 
              
               
              //  if ((Close[0] - OrderOpenPrice()) < 0)  //Only do the following if we are in negative
             //         if (GANN0 > MA0  && GANNO1 < MA1) CloseReverse(); 

              
                

            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount))) && OrderMagicNumber() == MagicNumber) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               GlobalVariableSet(Symbol() + "LockPipsAfter",0);
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) { 
               if(Bid - OrderOpenPrice() > Pointz * TrailingStop) {
                  if(OrderStopLoss() < Bid - Pointz * TrailingStop) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Pointz * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
                     if (!EachTickMode) BarCount = Bars;
                     GlobalVariableSet(Symbol() + "LockPipsAfter",Ask + Pointz * TrailingStop + Pointz * 3);  
                     continue;
                  }
               }
            }
            
         } else {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+
                 double CloseSell1_1 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_MEDIAN, Current + 0);
                double CloseSell1_2 = iMA(NULL, 0, CMA, 0, MODE_SMA, PRICE_MEDIAN, Current + 0);
           
        if (CloseSell1_1>GANN1HR) Order= SIGNAL_CLOSESELL;
          //need to fix the move pips to break even
          
                if (GlobalVariableGet(Symbol() + "LockPipsAfter") == 0) {
                     if((OrderOpenPrice() - Close[0])/Point > LockPipsAfter) {
                     GlobalVariableSet("LockPipsAfterSell",OrderOpenPrice() - lockprofit * Pointz);
                     OrderModify(OrderTicket(), OrderOpenPrice(),OrderOpenPrice() - lockprofit * Pointz, OrderTakeProfit(), 0, DarkOrange);
                   }
                 } else {
                    if (Close[0] <= GlobalVariableGet(Symbol() + "LockPipsAfter")) 
                    Order = SIGNAL_CLOSESELL;
                 }
            
                  
         //       if (GANNO1 < MA1 && GANN02 > MA2) Order = SIGNAL_CLOSESELL; //CloseReverse();
             

                 

            //+------------------------------------------------------------------+
            //| Signal End(Exit Sell)                                            |
            //+------------------------------------------------------------------+

           if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))&& OrderMagicNumber() == MagicNumber) {
               OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               GlobalVariableSet(Symbol() + "LockPipsAfter",0);
             
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {  
               if((OrderOpenPrice() - Ask) > (Pointz * TrailingStop)) {
                  if((OrderStopLoss() > (Ask + Pointz * TrailingStop)) || (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Pointz * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
                     if (!EachTickMode) BarCount = Bars;
                     GlobalVariableSet(Symbol() + "LockPipsAfter",Ask + Pointz * TrailingStop + Pointz * 3);    
                    
                  }
               }
            }
         }
      }
   }


   
//+------------------------------------------------------------------+
//| Signal Begin(Entry) |
//+------------------------------------------------------------------+
//Jado added this condition for trading using the SHI_Channel_true vlaue
//jado removed shi filter
//if(ShiChannel < ShiChannelUserValue) return(0); //no trade
// jado removed ATR filter
// Before doing anything lets check the ATR. If the Candle[0] % ATR > 100% no trading
//if (atr() > NoTradeATR) return(0); // No trade

if (CheckAlert()) { // Chek if time limit is up. Wait 2 bars before checking conditions
if (GANNO1 < MA1&&GANF>GANS&& GANN02 < MA2&&MAHLC<GANNO1/*&&MAFILTER<MA1*/ && QQE1>QQE3&&SAR<MA1&&   Order == SIGNAL_NONE && MACDTest(1)==1)  {
Order = SIGNAL_BUY;
GlobalVariableSet(Symbol() + "GANN0",Time[0]);
}

if (GANNO1 < MA1 &&GANF<GANS&& GANN02 < MA2 &&MAHLC<GANNO1&& QQE3<QQE1&&/* MAFILTER>MA1 &&*/SAR>MA1  &&  Order == SIGNAL_NONE  && MACDTest(1)==1){
Order = SIGNAL_SELL;
GlobalVariableSet(Symbol() + "GANN0",Time[0]);
}
}
//+------------------------------------------------------------------+
//| Signal End |
//+------------------------------------------------------------------+


 //Check to see if we use Jado's MM.  Lots size = Account/10000 
    if (MM()) { Comment("Lots(MM:true): ", Lots); }
   //Buy
   if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (10000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Ask - StopLoss * Pointz; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Pointz; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("BUY order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
			} else {
				Print("Error opening BUY order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Bid + StopLoss * Pointz; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Pointz; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("SELL order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) BarCount = Bars;

   return(0);
}

  bool CheckAlert() {
   double EntryAlert_time0	= GlobalVariableGet(Symbol() + "GANN0");
   if ((Time[0] - EntryAlert_time0)/60*Period() > 2) {
      GlobalVariableSet(Symbol() + "GANN0",0);
      return(true);
   }
   return(false); 
  }
  
 /* 
  double atr () {  // Return Candle[1] vs ATR percentage

   double high = iHigh(Symbol(),0,1);
   double low = iLow(Symbol(),0,1);
   double range = (high - low)* MathPow(10,Digits);
   double ATR = (iATR(Symbol(),0,20,0))* MathPow(10,Digits);
   double PercentAtr = NormalizeDouble((range/ATR),2) * 100;
   if (Period() > 60) PercentAtr = 0;
   return(PercentAtr);
  
  }
*/  
  bool MM () {
   int precision = 1;
   if (!UseMM) return(false); 
   if (MarketInfo(Symbol(),MODE_MINLOT) == 0.01) precision = 2;
  // double UserMM = (AccountBalance()/10000)/MarketInfo(Symbol(),MODE_TICKVALUE);
   Lots = NormalizeDouble((AccountBalance()/1000)/MarketInfo(Symbol(),MODE_TICKVALUE),precision);

   //Test for mimimums
   if (MarketInfo(Symbol(),MODE_MINLOT) == 0.01) {
   if (Lots < 0.01) Lots = MarketInfo(Symbol(),MODE_MINLOT); 
   } else {
   if (Lots < 0.1) Lots = MarketInfo(Symbol(),MODE_MINLOT);
   }
   
   return(true);
  }
  
   
//MACD BUY/SELL Test -----------------------------
// For BUYS - If(MACDTest(0)==1){....}
// For SELLS - If(MACDTest(0)==2){....}
// Above example tests current Bar - MUCH BETTER to Use MACDTest(1) for 1st Closed Bar 
int MACDTest(int xshift)
{ 
int flag=-1;
double macdm=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,xshift);
double macds=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,xshift);
//----------------
if((macdm>0&&macdm>macds)||(macdm<0 &&macdm>macds)){flag=1;} //BUY Signal
if((macdm<0&&macdm<macds)||(macdm>0 &&macdm<macds)){flag=2;} //SELL Signal 
return(flag); 
} 
//-------------------------------------------
  /*
  
bool CloseReverse() {
    int ticketx=0;
    double closeprice,StopLossLevel, TakeProfitLevel;
    bool boolx; 

     for(int cnt=OrdersTotal()-1;cnt>=0;cnt--) {
         boolx=OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         ticketx=OrderTicket();
         RefreshRates(); // GET Latest Rates
  
     if (OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber) {
                  
          boolx=false;
                
          while(boolx==false && IsTradeContextBusy()==false) {
          closeprice=MarketInfo(OrderSymbol(),MODE_BID); 
          boolx = OrderClose(OrderTicket(), OrderLots(), closeprice, Slippage, MediumSeaGreen);
          Sleep(100);
          } //NEXT REVERSE..
          
          MM();         
          ticketx=-1; 
          if (UseStopLoss) StopLossLevel = Bid + StopLoss * Pointz; else StopLossLevel = 0.0;
          if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Pointz; else TakeProfitLevel = 0.0;
          while(ticketx<0 && IsTradeContextBusy()==false){
          ticketx = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
          Sleep(250);
          GlobalVariableSet(Symbol() + "GANN0",Time[0]);
          }
     }
                        
      if (OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber() == MagicNumber) {
                   
           boolx=false;

           while(boolx==false && IsTradeContextBusy()==false){
           closeprice=MarketInfo(OrderSymbol(),MODE_ASK);
           boolx =  OrderClose(OrderTicket(), OrderLots(), closeprice, Slippage, MediumSeaGreen);
           Sleep(100);
           } //NEXT REVERSE..
            
           MM();                    
           ticketx=-1;
           if (UseStopLoss) StopLossLevel = Ask - StopLoss * Pointz; else StopLossLevel = 0.0;
           if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Pointz; else TakeProfitLevel = 0.0;
           while(ticketx<0 && IsTradeContextBusy()==false){
           ticketx = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
           Sleep(250);
            GlobalVariableSet(Symbol() + "GANN0",Time[0]);
            }
            
      }

   }//END of For...
   
return(0);  
}         



  */
  
//+------------------------------------------------------------------+