//+------------------------------------------------------------------+
//|                                               2slopeBs_hgeus.mq4 |
//|                                  Copyright 2020, Fxautomated.com |
//|                                       http://www.fxautomated.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Fxautomated.com"
#property link      "http://www.fxautomated.com"
#property version   "1.00"
#property strict

//---- input parameters
extern double    Lots=0.1;
extern int       Slip=5;
extern string    StopSettings="Set stops below";
extern double    TakeProfit=150;
extern double    StopLoss=100;
extern string    TrailingStopSettings="Settings for trailing stop";  // trailing stop
extern bool      AllowTrailingStop=true;
extern int       TrailDistance=50;
extern int       TrailTrigger=50;
extern double    TrailStepPips=5;
extern bool      AllowBuy=true;
extern bool      AllowSell=true;
extern bool      CloseOnReverseSignal=true;
extern string    TimeSettings="Set the time range the EA should trade";
extern string    StartTime="00:00";
extern string    EndTime="23:59";
extern string    SlopeDirection="Settings for slope indicator";
input string     SlopeTerminalName="Slope_Direction_Line_Alert";
extern int       speriod=20;
extern int       method=1;                         // MODE_SMA
extern int       price=0;
extern string    SecondSlopeDirection="Settings for slope indicator";
extern int       speriod2=40;
extern int       method2=1;                         // MODE_SMA
extern int       price2=0;
extern string    BsTrendIndicatorSettings="Settings for bstrend indicator";
extern bool      AllowBsTrend=true;
extern int       period=12;
/*
extern bool AllowSecondBsTrend=true;
extern int SecondBsTrendPeriod=12;
extern string TmaCenteredMACD="Settings for TMA centered macd";
extern bool      AllowTma=true;
extern string    TmaFileName="TMA centered MACD v1 TT";
extern int       FastHalfLength=24;
extern int       SlowHalfLength=96;
*/
extern string    MagicNumbers="Set different magicnumber for each timeframe of a pair";
extern int       MagicNumber=1003;

string freeze;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int init()
  {
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----

   int StopMultd=10;
   int Slippage=Slip*StopMultd;

   int i,closesell=0,closebuy=0;

   double  TP=NormalizeDouble(TakeProfit*StopMultd,Digits);
   double  SL=NormalizeDouble(StopLoss*StopMultd,Digits);


//-------------------------------------------------------------------+
//Check open orders
//-------------------------------------------------------------------+
   int haltbuy=0,haltsell=0;
   if(OrdersTotal()>0)
     {
      for(i=1; i<=OrdersTotal(); i++) // Cycle searching in orders
        {
         if(OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
           {
            if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Symbol() && OrderType()==OP_BUY)
              {
               haltbuy=1;
              }
            if(OrderMagicNumber()==MagicNumber && OrderSymbol()==Symbol() && OrderType()==OP_SELL)
              {
               haltsell=1;
              }


           }
        }
     }

//-------------------------------------------------------------------+
// time check
//-------------------------------------------------------------------
   int TradeTimeOk;
   if((TimeCurrent()>=StrToTime(StartTime)) && (TimeCurrent()<=StrToTime(EndTime)))
     {
      TradeTimeOk=1;
     }
   else
     { TradeTimeOk=0; }
//-----------------------------------------------------------------
// indicator checks
//-----------------------------------------------------------------



// BsTrend
   double Bsbc0=iCustom(NULL,0,"bstrend-indicator",period,0,0);
   double Bsbc1=iCustom(NULL,0,"bstrend-indicator",period,0,1);
   double Bsbc2=iCustom(NULL,0,"bstrend-indicator",period,0,2);
//string text=StringConcatenate("v0_",Bsbc0,"_v1_",Bsbc1,"_v2_",Bsbc2);
//Comment(text);

// slope1
   double SlopeBlue0=iCustom(NULL,0,SlopeTerminalName,speriod,method,price,1,1,1,0);
   double SlopeBlue1=iCustom(NULL,0,SlopeTerminalName,speriod,method,price,1,1,1,1);

   double SlopeRed0=iCustom(NULL,0,SlopeTerminalName,speriod,method,price,1,1,2,0);
   double SlopeRed1=iCustom(NULL,0,SlopeTerminalName,speriod,method,price,1,1,2,1);

// slope2
   double Slope2Blue0=iCustom(NULL,0,SlopeTerminalName,speriod2,method2,price2,1,1,1,0);
   double Slope2Blue1=iCustom(NULL,0,SlopeTerminalName,speriod2,method2,price2,1,1,1,1);

   double Slope2Red0=iCustom(NULL,0,SlopeTerminalName,speriod2,method2,price2,1,1,2,0);
   double Slope2Red1=iCustom(NULL,0,SlopeTerminalName,speriod2,method2,price2,1,1,2,1);



//-----------------comput indicators---------------------------------------


//Bstrend
   string BsFil="none";
   if(Bsbc0>0&&Bsbc1>0/*&&Bsbc2>0*/)
     {
      BsFil="buy";
     }
   if(Bsbc0<0&&Bsbc1<0/*&&Bsbc2<0*/)
     {
      BsFil="sell";
     }
   if(AllowBsTrend==false)
     {
      BsFil="off";
     }

// slope1
   string slope1="none";
   if(SlopeBlue1!=EMPTY_VALUE)
     {
      slope1="blue";
     }
   if(SlopeRed1!=EMPTY_VALUE)
     {
      slope1="red";
     }

// slope2
   string slope2="none";
   if(Slope2Blue1!=EMPTY_VALUE)
     {
      slope2="blue";
     }
   if(Slope2Red1!=EMPTY_VALUE)
     {
      slope2="red";
     }

//------------------opening criteria------------------------
   bool buysignal,sellsignal;
   if((BsFil=="buy"||BsFil=="off")&&slope1=="blue"&&slope2=="blue")
     { buysignal=true;}
   else
     {
      buysignal=false;
     }

   if((BsFil=="sell"||BsFil=="off")&&slope1=="red"&&slope2=="red")
     { sellsignal=true;}
   else
     {
      sellsignal=false;
     }

//------------------------------closing criteria--------------
   if(/*(MA1_bc>MA2_bc)&&(MA1_bp>MA2_bp)&&(MA1_bl<MA2_bl)*/sellsignal==true)
     {
      closebuy=1;
     }
   else
     {
      closebuy=0;
     }
   if(/*(MA1_bc<MA2_bc)&&(MA1_bp<MA2_bp)&&(MA1_bl>MA2_bl)*/buysignal==true)
     {
      closesell=1;
     }
   else
     {
      closesell=0;
     }




//-----------------------------------------------------------------------------------------------------
// Opening criteria
//-----------------------------------------------------------------------------------------------------

   int openbuy=0,opensell=0;
// Open buy
   if((buysignal==true) && (closebuy!=1) && (freeze!="Buying trend") && (TradeTimeOk==1))
     {

      if(AllowBuy==true && haltbuy!=1)
         openbuy=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"Xtrader hgeus buy order",MagicNumber,0,Blue);

     }

// Open sell
   if((sellsignal==true) && (closesell!=1) && (freeze!="Selling trend") && (TradeTimeOk==1))
     {

      if(AllowSell==true && haltsell!=1)
         opensell=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"Xtrader hgeus sell order",MagicNumber,0,Red);

     }


   if(buysignal==true)
     {
      freeze="Buying trend";
     }
   if(sellsignal==true)
     {
      freeze="Selling trend";
     }

//-------------------------------------------------------------------------------------------------
// Closing criteria
//-------------------------------------------------------------------------------------------------

   if(closesell==1 || closebuy==1 || openbuy<1 || opensell<1)
     {
      // start
      if(OrdersTotal()>0)
        {
         for(i=1; i<=OrdersTotal(); i++)
           {
            // Cycle searching in orders

            if(OrderSelect(i-1,SELECT_BY_POS)==true)
              {
               // If the next is available
               if(CloseOnReverseSignal==true)
                 {
                  if(OrderMagicNumber()==MagicNumber && closebuy==1&&OrderType()==OP_BUY&&OrderSymbol()==Symbol())
                    {
                     bool oc1=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,CLR_NONE);
                    }
                  if(OrderMagicNumber()==MagicNumber&&closesell==1&&OrderType()==OP_SELL&&OrderSymbol()==Symbol())
                    {
                     bool oc2=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,CLR_NONE);
                    }
                 }
               // set stops

               // Calculate take profit
               double tpb=NormalizeDouble(OrderOpenPrice()+TP*Point,Digits);
               double tps=NormalizeDouble(OrderOpenPrice()-TP*Point,Digits);
               // Calculate stop loss
               double slb=NormalizeDouble(OrderOpenPrice()-SL*Point,Digits);
               double sls=NormalizeDouble(OrderOpenPrice()+SL*Point,Digits);


               if(TakeProfit>0)
                 {
                  // if tp not 0
                  if((OrderMagicNumber()==MagicNumber) && (OrderTakeProfit()==0) && (OrderSymbol()==Symbol()) && (OrderType()==OP_BUY))
                    {
                     bool om1=OrderModify(OrderTicket(),0,OrderStopLoss(),tpb,0,CLR_NONE);
                    }
                  if((OrderMagicNumber()==MagicNumber) && (OrderTakeProfit()==0) && (OrderSymbol()==Symbol()) && (OrderType()==OP_SELL))
                    {
                     bool om2=OrderModify(OrderTicket(),0,OrderStopLoss(),tps,0,CLR_NONE);
                    }
                 }

               if(StopLoss>0)
                 {
                  // if sl not 0
                  if((OrderMagicNumber()==MagicNumber) && (OrderStopLoss()==0) && (OrderSymbol()==Symbol()) && (OrderType()==OP_BUY))
                    {
                     bool om3=OrderModify(OrderTicket(),0,slb,OrderTakeProfit(),0,CLR_NONE);
                    }
                  if((OrderMagicNumber()==MagicNumber) && (OrderStopLoss()==0) && (OrderSymbol()==Symbol()) && (OrderType()==OP_SELL))
                    {
                     bool om4=OrderModify(OrderTicket(),0,sls,OrderTakeProfit(),0,CLR_NONE);
                    }
                 }


              } // if available
           } // cycle
        }// orders total

     }// stop

//--------------Trailing stop-------------------------------

   TrailStop(AllowTrailingStop,TrailDistance,TrailTrigger,TrailStepPips,MagicNumber);

//----
   int Error=GetLastError();
   if(Error==130)
     {
      Alert("Wrong stops. Retrying.");
      RefreshRates();
     }
   if(Error==133)
     {
      Alert("Trading prohibited.");
     }
   if(Error==2)
     {
      Alert("Common error.");
     }
   if(Error==146)
     {
      Alert("Trading subsystem is busy. Retrying.");
      Sleep(500);
      RefreshRates();
     }

//----

//-------------------------------------------------------------------
   return(0);
  }
//+--------------------------------End----------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void TrailStop(bool tsActive,int tsDistance,int tsTrigger,double tsStep,int tsMagicNumber)
  {

   if(OrdersTotal()>0)
     {
      for(int tsi=1; tsi<=OrdersTotal(); tsi++)
        {
         // Cycle searching in orders

         if(OrderSelect(tsi-1,SELECT_BY_POS)==true && OrderMagicNumber()==tsMagicNumber && OrderSymbol()==Symbol())
           {
            // If the next is available

            //--------Trailing stop-------------
            if(tsActive==true)
              {
               // start trailing

               double FinalTrailDistance=tsDistance*Point;
               int    FinalTrailTrigger=tsTrigger;
               double FinalTrailTriggerPoint=FinalTrailTrigger*Point;
               double TrailStepR=tsStep*Point;

               if(/*Bid-OrderStopLoss()>FinalTrailDistance &&*/ OrderType()==OP_BUY)// for buy trades
                 {

                  if((OrderStopLoss()<Bid-(FinalTrailDistance+TrailStepR) && Bid-OrderOpenPrice()>FinalTrailTriggerPoint) ||
                     ((OrderStopLoss()==0 || OrderStopLoss()<OrderOpenPrice()) && Bid-OrderOpenPrice()>FinalTrailTriggerPoint)
                    )
                    {
                     double newbsl=Bid-FinalTrailDistance;
                     if(Bid-newbsl>SYMBOL_TRADE_FREEZE_LEVEL*_Point)
                       {
                        bool tsOrdMod1=OrderModify(OrderTicket(),OrderOpenPrice(),newbsl,OrderTakeProfit(),0,Yellow);
                       }
                    }

                 }

               if(/* OrderStopLoss()-Ask>FinalTrailDistance &&*/ OrderType()==OP_SELL)// for sell trades
                 {

                  if((OrderStopLoss()>Ask+(FinalTrailDistance+TrailStepR) && OrderOpenPrice()-Ask>FinalTrailTriggerPoint) ||
                     ((OrderStopLoss()==0 || OrderStopLoss()>OrderOpenPrice()) && OrderOpenPrice()-Ask>FinalTrailTriggerPoint)
                    )
                    {
                     double newssl=Ask+FinalTrailDistance;
                     if(newssl-Ask>SYMBOL_TRADE_FREEZE_LEVEL*_Point)
                       {
                        bool tsOrdMod2=OrderModify(OrderTicket(),OrderOpenPrice(),newssl,OrderTakeProfit(),0,Yellow);
                       }
                    }

                 }

              }// end trailing
            //--------Trailing stop-------------
           } // if available
        } // cycle
     }// orders total

  }
//------------------------------------------------------------------------------------
