//+------------------------------------------------------------------+
//|                                                       |
//+------------------------------------------------------------------+

extern int expertId = 1;

extern int TakeProfit=300;
extern int StopLoss=70;  
extern int TrailingStop = 0;  

extern double Lots = 0.1;

extern int HMA_Period=20;

extern int    slippage=2;   	//slippage for market order processing
extern int    shift=1;			//shift to current bar, 

extern int    OrderTriesNumber=2; //to repeate sending orders when got some error

extern string    EAName="hma"; 

bool buysig,sellsig,closebuy,closesell; int lastsig,tries,x,y,co;
double spr,hh,ll;


void start()  {


   //---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;

   CheckForSignals();
   co=CalculateCurrentOrders();
   if (co>0) CheckForClose();
   co=CalculateCurrentOrders();
   CheckForOpen();
   
   TrailStop();
        
}


//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders()
  {
   int ord;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==expertId) ord++;
     }
//---- return orders volume
   return(ord);
}

//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForSignals() {

      buysig=false;
      sellsig=false;
      closebuy=false;
      closesell=false;

      //indicators variables

      double hma11 = iCustom(NULL,0,"hma-calling-code",HMA_Period,0,shift);
      double hma12 = iCustom(NULL,0,"hma-calling-code",HMA_Period,0,shift+1);
      double hma13 = iCustom(NULL,0,"hma-calling-code",HMA_Period,0,shift+2);
      double hma21 = iCustom(NULL,0,"hma-calling-code",HMA_Period,2,shift);
      double hma22 = iCustom(NULL,0,"hma-calling-code",HMA_Period,2,shift+1);
      double hma23 = iCustom(NULL,0,"hma-calling-code",HMA_Period,2,shift+2);

   
	   if (hma21<10000 && hma22<10000 && hma23>10000) sellsig=true;
	   if (hma11<10000 && hma12<10000 && hma13>10000 && !(hma21<10000 && hma22<10000)) buysig=true;

      closebuy=sellsig;
      closesell=buysig;
}

void CheckForOpen() {
   int    res,tr;
//---- sell conditions
   if(sellsig)  {
	   if (co==0 && lastsig!=Time[0]) {
	     res = OpenAtMarket(OP_SELL,Lots);
	     lastsig=Time[0];
	   }
      return;
   }
//---- buy conditions
   if(buysig)  {
	   if (co==0 && lastsig!=Time[0]) {
	     res = OpenAtMarket(OP_BUY,Lots);
	     lastsig=Time[0];
	   }
      return;
   }
}
  
  
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()  {
   bool bres; int tr;
   for(int i=0;i<OrdersTotal();i++)  {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)  break;
      if(OrderMagicNumber()!=expertId || OrderSymbol()!=Symbol()) continue;
      //---- check order type 
      if(OrderType()==OP_BUY)
         if (closebuy) {
            bres=CloseAtMarket(OrderTicket(),OrderLots());
            break;
         }
      if(OrderType()==OP_SELL) 
         if (closesell) {
            bres=CloseAtMarket(OrderTicket(),OrderLots());
            break;
         }
   }
}



int OpenAtMarket(int mode,double lot) {
   int    res,tr,col;
   double openprice,sl,tp;
   tries=0;
   while (res<=0 && tries<OrderTriesNumber) {
      tr=0; while (tr<5 && !IsTradeAllowed()) { tr++; Sleep(2000); }
      RefreshRates();
      if (mode==OP_SELL) {
         openprice=Bid; 
         sl=openprice+StopLoss*Point;
         tp=openprice-TakeProfit*Point;
         col=Red;
      } else {
         openprice=Ask;
         sl=openprice-StopLoss*Point;
         tp=openprice+TakeProfit*Point;
         col=Blue;
      }
      res=OrderSend(Symbol(),mode,lot,openprice,slippage,sl,tp,EAName+"_"+expertId,expertId,0,col);
      tries++;
   }
   return(res);
}


bool CloseAtMarket(int ticket,double lot) {
   bool bres=false; int tr;
   tries=0;
   while (!bres && tries<OrderTriesNumber) {
      tr=0; while (tr<5 && !IsTradeAllowed()) { tr++; Sleep(2000); }
      RefreshRates();
      bres=OrderClose(ticket,lot,OrderClosePrice(),slippage,White);
      if (!bres) Print("Error closing order : ",ErrorDescription(GetLastError()));
      tries++;
   }
}


void TrailStop() {
   bool bres;
   double StopLoss;
   if ( TrailingStop > 2 ) {
      for (int i = 0; i < OrdersTotal(); i++) {
         if ( OrderSelect (i, SELECT_BY_POS) == false )  continue;
         if ( OrderSymbol() != Symbol() || OrderMagicNumber() != expertId )  continue;
         if ( OrderType() == OP_BUY ) {
            if ( Bid < OrderOpenPrice()+TrailingStop*Point )  return;
            StopLoss = Bid-TrailingStop*Point;
            if ( StopLoss > OrderStopLoss() ) {
                  bres=OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, White);
					   if (!bres) Print("Error Modifying BUY order : ",ErrorDescription(GetLastError()));
            }
         }
   
         if ( OrderType() == OP_SELL ) {
            if ( Ask > OrderOpenPrice()-TrailingStop*Point )  return;
            StopLoss = Ask+TrailingStop*Point;
            if ( StopLoss < OrderStopLoss() ) {
                  bres=OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Gold);
					   if (!bres) Print("Error Modifying SELL order : ",ErrorDescription(GetLastError()));
            }
         }
      }
   }
   return;
}

