//+------------------------------------------------------------------+
//|                                                       xpMaEA.mq4 |
//|                                                     Coders' Guru |
//|                                            http://www.xpworx.com |
//+------------------------------------------------------------------+

#property copyright "Coders' Guru"
#property link      "http://www.xpworx.com"

#define MODE_DEMA    4
#define MODE_TEMA    5
#define MODE_T3MA    6
#define MODE_JMA     7
#define MODE_HMA     8
#define MODE_DECEMA  9
#define MODE_SALT    10

//---- Trades limits
extern   double    Lots = 1;
extern   double    TakeProfit = 100;
extern   double    TrailingStop = 50; 
extern   double    StopLoss = 50;
extern   int       Slippage = 5;
extern   double    MaximumRisk        = 0.1;

//--- xpMA Indicators settings
extern   int      TimeFrame               = 0;
extern   int      MA_Period               = 24;
extern   int      MA_Type                 = MODE_TEMA;
extern   int      MA_Applied              = PRICE_CLOSE;
extern   double   T3MA_VolumeFactor       = 0.8;
extern   double   JMA_Phase               = 0;
extern   int      Step_Period             = 4;


//--- Global variables
int      MagicNumber = 101050;
string   ExpertComment = "xpMaEA";
int      NumberOfTries = 5;

//+------------------------------------------------------------------
int init()
{
   return(0);
}

int deinit() 
{
   return(0);
}
//+------------------------------------------------------------------

bool isNewSymbol(string current_symbol)
  {
   //loop through all the opened order and compare the symbols
   int total  = OrdersTotal();
   for(int cnt = 0 ; cnt < total ; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      string selected_symbol = OrderSymbol();
      if (current_symbol == selected_symbol && OrderMagicNumber()==MagicNumber)
      return (False);
    }
    return (True);
}

//+------------------------------------------------------------------+
int start()
  {
   
   int cnt, ticket, total,n;
   double signal;
   
   if(Bars<50) {Print("bars less than 50"); return(0);}

   //Symbo settings:
   RefreshRates();
   Slippage = MarketInfo(Symbol(),MODE_SPREAD);
   
   signal = iCustom(NULL,0,"xpMA",TimeFrame,MA_Period,MA_Type,MA_Applied,T3MA_VolumeFactor,JMA_Phase,Step_Period,false,3,0);
   //Print(signal);
   //--- Trading conditions
   bool BuyCondition = false , SellCondition = false , CloseBuyCondition = false , CloseSellCondition = false ; 
   
   if (signal==1)
       BuyCondition = true;
       
   if (signal==-1)
      SellCondition = true;
   
   if (BuyCondition)
      CloseSellCondition = true;
   
   if (SellCondition)
      CloseBuyCondition = true;
      
      
   
   total  = OrdersTotal();
   
   Lots=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
   
      
   if(total < 1 || isNewSymbol(Symbol())) 
     {
       if(BuyCondition) //<-- BUY condition
         {
           ticket = OpenOrder(OP_BUY); //<-- Open BUY order
            return(0);
         }
         if(SellCondition) //<-- SELL condition
         {
            ticket = OpenOrder(OP_SELL); //<-- Open SELL order
            return(0);
         }
         return(0);
     }
     
      for(cnt=0;cnt<total;cnt++) 
      {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

         if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
         {
            if(OrderType()==OP_BUY)   //<-- Long position is opened
            {
                  if(CloseBuyCondition) //<-- Close the order and exit! 
                  {
                     CloseOrder(OrderType()); 
                  } 
               
               TrailOrder(OrderType()); //<-- Trailling the order
            }
            if(OrderType()==OP_SELL) //<-- Go to short position
            {
                 if(CloseSellCondition) //<-- Close the order and exit! 
                  {
                     CloseOrder(OP_SELL);
                  } 
               TrailOrder(OrderType()); //<-- Trailling the order
            }
         }
      }

   return(0);
  }
//+------------------------------------------------------------------+

int OpenOrder(int type)
{
   int ticket=0;
   int err=0;
   int c = 0;
   
   if(type==OP_BUY)
   {
      for(c = 0 ; c < NumberOfTries ; c++)
      {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-StopLoss*Point,Ask+TakeProfit*Point,ExpertComment,MagicNumber,0,Green);
         err=GetLastError();
         if(err==0)
         { 
            break;
         }
         else
         {
            if(err==4 || err==137 ||err==146 || err==136) //Busy errors
            {
               Sleep(5000);
               continue;
            }
            else //normal error
            {
               break;
            }  
         }
      }   
   }
   if(type==OP_SELL)
   {   
      for(c = 0 ; c < NumberOfTries ; c++)
      {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+StopLoss*Point,Bid-TakeProfit*Point,ExpertComment,MagicNumber,0,Red);
         err=GetLastError();
         if(err==0)
         { 
            break;
         }
         else
         {
            if(err==4 || err==137 ||err==146 || err==136) //Busy errors
            {
               Sleep(5000);
               continue;
            }
            else //normal error
            {
               break;
            }  
         }
      }   
   }  
   return(ticket);
}

bool CloseOrder(int type)
{
   if(OrderMagicNumber() == MagicNumber)
   {
      if(type==OP_BUY)
         return (OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet));
      if(type==OP_SELL)   
         return (OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet));
   }
}
void TrailOrder(int type)
{
   if(TrailingStop>0)
   {
      if(OrderMagicNumber() == MagicNumber)
      {
         if(type==OP_BUY)
         {
            if(Bid-OrderOpenPrice()>Point*TrailingStop)
            {
               if(OrderStopLoss()<Bid-Point*TrailingStop)
               {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
               }
            }
         }
         if(type==OP_SELL)
         {
            if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
            {
               if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
               {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
               }
            }
         }
      }
   }
}


