/* 
****************************************************************************************************
v0.1  Build to Bemac's request. Trailing stop EA by percentage of profit after hitting minimum pips
****************************************************************************************************
*/

#include <stderror.mqh>
#include <stdlib.mqh>

extern int        TakeProfit                    = 300;
extern int        StopLoss                      = 50;
extern int        MinPipsToActivate             = 50;
extern int        PercentageTrailBehindPrice    = 20;

extern bool       Show_Status                   = true; // Show status of trade management in action    

int Factor=1;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
         if (Digits == 5 || Digits == 3) Factor = 10; //5 digits
         Comment("");
         return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
         Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{   
   //---- check for history and trading
if(Bars<100 || IsTradeAllowed()==false) return;

int CurrentSymbolTotalOrders = CalculateCurrentOrders(Symbol());

if(CurrentSymbolTotalOrders!= 0)
{
   // ============= Looping through order list starts here
       for(int i=0;i<OrdersTotal();i++)   
         {
            if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)  break;
            if(OrderSymbol()!=Symbol()) continue;
            else
               {
                  double OpenPrice = OrderOpenPrice();
            
         // ============= Insert SL and TP into the order that was manually opened.
                  if (OrderStopLoss()==0 || OrderTakeProfit()==0)
                    {
                       if (OrderType() == OP_BUY)  
                          {
                           if (StopLoss != 0 && TakeProfit != 0) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-StopLoss*(Point*Factor),OrderOpenPrice()+TakeProfit*(Point*Factor),0);
                           if (StopLoss != 0 && TakeProfit == 0) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-StopLoss*(Point*Factor),0,0);
                           if (StopLoss == 0 && TakeProfit != 0) OrderModify(OrderTicket(),OrderOpenPrice(),0 ,OrderOpenPrice()+TakeProfit*(Point*Factor),0);
                          }
                       if (OrderType() == OP_SELL) 
                          {
                           if (StopLoss != 0 && TakeProfit != 0) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+StopLoss*(Point*Factor),OrderOpenPrice()-TakeProfit*(Point*Factor),0);
                           if (StopLoss != 0 && TakeProfit == 0) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+StopLoss*(Point*Factor),0,0);
                           if (StopLoss == 0 && TakeProfit != 0) OrderModify(OrderTicket(),OrderOpenPrice(),0,OrderOpenPrice()-TakeProfit*(Point*Factor),0);
                           }
                    }
         // ==================== Bemac Trailing logic starts here
                  double PriceDiff4Buy, PriceDiff4Sell;
                  double PriceDiff4BuyPips, PriceDiff4SellPips;
                  bool success; int err;
  
                  PriceDiff4Buy = Bid - OpenPrice; 
                  PriceDiff4Sell = OpenPrice - Ask;
                  PriceDiff4BuyPips = PriceDiff4Buy/(Factor*Point);
                  PriceDiff4SellPips = PriceDiff4Sell/(Factor*Point);

                  if (PriceDiff4BuyPips >= MinPipsToActivate && OrderType() == OP_BUY)
                     {
                        if (OrderStopLoss() < (Bid-(PercentageTrailBehindPrice/100.0*PriceDiff4Buy)))
                           {
                              success = OrderModify(OrderTicket(),OrderOpenPrice(), NormalizeDouble(Bid -(PercentageTrailBehindPrice/100.0*PriceDiff4Buy),Digits),OrderTakeProfit(),0,CLR_NONE);
                              if (!success)
                                {
                                 err=GetLastError();
                                 Print("Error closing order : (",err,") ", ErrorDescription(err));
                                 } 
                             }
                       }
                  if (PriceDiff4SellPips >= MinPipsToActivate && OrderType() == OP_SELL)
                     {
                        if (OrderStopLoss() > (Ask + (PercentageTrailBehindPrice/100.0*PriceDiff4Sell)))
                           {
                              success = OrderModify(OrderTicket(),OrderOpenPrice(), NormalizeDouble(Ask + (PercentageTrailBehindPrice/100.0*PriceDiff4Sell),Digits),OrderTakeProfit(),0,CLR_NONE);
                              if (!success)
                                {
                                 err=GetLastError();
                                 Print("Error closing order : (",err,") ", ErrorDescription(err));
                                 } 
                             }
                       }
                  if (Show_Status && CurrentSymbolTotalOrders == 1)
                     {
                        string displayorder, PriceStatus;

                        if (OrderType() == OP_BUY)
                           {
                            displayorder = Symbol()+" BOUGHT at "+ DoubleToStr(OpenPrice,Digits);
                            }
                        if(OrderType() == OP_SELL)
                           {
                            displayorder = Symbol()+" SOLD at "+ DoubleToStr(OpenPrice,Digits);
                             }
                        if(OrderType() == OP_BUY) 
                           {
                              PriceStatus = DoubleToStr(PriceDiff4BuyPips,0);
                            }
          
                         else 
                           {
                              PriceStatus = DoubleToStr(PriceDiff4SellPips,0);
                              }

                        Comment("Bemac Trade Management EA on "+AccountCompany()+" ("+Digits+" digits)"+
                                "\nPosition: "+ displayorder +
                                "\n\nStop Loss = "+ StopLoss +
                                "\nTarget Profit = " + TakeProfit +
                                "\n\nTrail behind price = " + PercentageTrailBehindPrice + "%" +
                                "\nMin. profit to activate = " + MinPipsToActivate + " pips (current: "+PriceStatus+")"
                                 );
                     } // end of show status
                  else if (Show_Status && CurrentSymbolTotalOrders > 1)
                     {
                        Comment("No status shown while managing multiple orders.");
                      }
                 }
     } // ==================== Looping through order list stops here
}
else 
   { Comment("Waiting for action ..."); }
}
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int countorders=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol())
        {
         countorders++;
        }
     }
//---- return orders volume
   return(countorders);
  }

