Tuesday, May 7, 2019

ADX MT4 Expert Advisor

ADX EA trades with ADX indicator strategies has Trailing Stop Loss &Take Profit works on all time frames major forex pairs and stocks NASDAQ.

USEMOVETOBREAKEVEN system functions like a stop loss

But a one-time function with a smaller value than the subsequent Stop Loss value to lock minimal profit and avoid loss if the price goes against you.

If you have reached a certain value of pips with the direction of the trade -

WHENTOMOVETOBE - When to move break even (values: 10-100).

So how many pips would you like to move the stop loss above the price line of the open trade-

PIPSTOMOVESL - How much pips to move stop loss (values: 10-100).

This EA trades only with the price of open candle!

Trade volume of a position depends on previous trading results.

It provides the possibility to limit the maximum risk (in % of deposit) of the trade.

If you want to trade with constant lotsize say:0.01 lot ,you need to set "MaximumRisk =0" and "DecreaseFactor=0"

Or else you will have a calculation of Percent (%) of deposit and MaximumRisk.
Parameters

Enable Breakout Strategies=ADX Main Line/+DI/-DI crosses above/below Entry Level(values:true/false).
Set the Breakout Level=(values: 1-100).
Use +DI/-DI Trend Filter=open only buy/sell orders if cross(values:true/false).
Minimum.difference.+DI.-DI= Min Price difference between+DI.-DI(values: 1-100).
Enable Cross Strategies=(values:true/false).
Min_Level_Of_Main_Line=minimum price of the ADX Main line(values: 1-100).
Main_Line_Sloping_Upwards=(values:true/false).
Confirm_Cross_On_Breakout=(values:true/false).
Exit_Level=(values: 1-100).
USEMOVETOBREAKEVEN - Enable "no loss" break even system (values: 0-1).
WHENTOMOVETOBE - When to move break even (values: 10-100).
PIPSTOMOVESL - How much pips to move stop loss (values: 10-100).
Lots - Lots size (values: 0.01-10).
MaximumRisk - maximum risk from total margin in %, (values: 0.01 - 0.3).
If "MaximumRisk =0" then "Lot=constant"
DecreaseFactor - decrease from total margin if you lose a trade.
TrailingStop-set a value from 10 to 100 to activate trailing stop loss & take profit, "0" will not activate trailing stop loss.
Stop_Loss - Stop Loss (values: 10-100).
MagicNumber - Magic number (values: 1-100000).
TakeProfit - Take Profit (values: 10-100).

<--------- Source Code -------------->
//+------------------------------------------------------------------+
//|            15MIN SCALPING                                        |
//|             http://algorithmic-trading-ea-mt4.000webhostapp.com/ |
//|                                                    AHARON TZADIK |
//+------------------------------------------------------------------+
#property copyright   "AHARON TZADIK"
#property link        "http://algorithmic-trading-ea-mt4.000webhostapp.com/"
#property version     "1.00"
#property strict


extern string     str1="Breakout Strategies";
extern bool       Breakout_Strategies=true;     //Enable Breakout Strategies
extern double     Entry_Level=10;               //Set the Breakout Level.
extern bool       Trend_Filter=true;           //Use +DI/-DI Trend Filter
extern double     Min_Price_Difference=10;     //Minimum.difference.+DI.-DI
extern string     str2="*****************";
extern string     str3=" Cross Strategy";
extern bool       Cross_Strategy=true;           //Enable Cross Strategies
extern double     Min_Level_Of_Main_Line=10;
extern bool       Main_Line_Sloping_Upwards=true;
extern bool       Confirm_Cross_On_Breakout=true;
extern string     str4="*****************";
extern string      str5="Trade Direction";
extern double     Distance=5;          //Distance 
extern int        FastMA=6;             //FastMA 
extern int        SlowMA=85;            //SlowMA 
extern string     str6="*****************";
extern double     Exit_Level=10;
extern bool        USEMOVETOBREAKEVEN=true;//Enable "no loss"
extern double         WHENTOMOVETOBE=10;      //When to move break even
extern double         PIPSTOMOVESL=5;         //How much pips to move sl
extern double      Lots=0.01;              //Lots size 
input  double       MaximumRisk   =0.02;
input  double       DecreaseFactor=3;
extern double         TrailingStop=40;        //TrailingStop 
extern double         Stop_Loss=20;           //Stop Loss  
extern int         MagicNumber=1234;       //MagicNumber 
input  double       TakeProfit=50;          //TakeProfit
int           err;
bool               FractalsUp=false;
bool               FractalsDown=false;
double             FractalsUpPrice=0;
double             FractalsDownPrice=0;
int                FractalsLimit=200;
int total=0;
double
Lot,Dmax,Dmin,// Amount of lots in a selected order
Lts,                             // Amount of lots in an opened order
Min_Lot,                         // Minimal amount of lots
Step,                            // Step of lot size change
Free,                            // Current free margin
One_Lot,                         // Price of one lot
Price,                           // Price of a selected order,
pips,
MA_1,MA_2,MA_3,MACD_SIGNAL;
int Type,freeze_level,Spread;
//--- price levels for orders and positions
double priceopen,stoploss,takeprofit;
//--- ticket of the current order 
int orderticket;

//--------------------------------------------------------------- 3 --
int
Period_MA_2,  Period_MA_3,       // Calculation periods of MA for other timefr.
Period_MA_02, Period_MA_03,      // Calculation periods of supp. MAs
K2,K3,T;
//---

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {

//--------------------------------------------------------------- 5 --
   switch(Period())                 // Calculating coefficient for..
     {                              // .. different timeframes
      case     1: K2=5;K3=15;T=PERIOD_M15; break;// Timeframe M1
      case     5: K2=3;K3= 6;T=PERIOD_M30; break;// Timeframe M5
      case    15: K2=2;K3= 4;T=PERIOD_H1; break;// Timeframe M15
      case    30: K2=2;K3= 8;T=PERIOD_H4; break;// Timeframe M30
      case    60: K2=4;K3=24;T=PERIOD_D1; break;// Timeframe H1
      case   240: K2=6;K3=42;T=PERIOD_W1; break;// Timeframe H4
      case  1440: K2=7;K3=30;T=PERIOD_MN1; break;// Timeframe D1
      case 10080: K2=4;K3=12; break;// Timeframe W1
      case 43200: K2=3;K3=12; break;// Timeframe MN
     }

   double ticksize=MarketInfo(Symbol(),MODE_TICKSIZE);
   if(ticksize==0.00001 || ticksize==0.001)
      pips=ticksize*10;
   else pips=ticksize;
   return(INIT_SUCCEEDED);
//--- distance from the activation price, within which it is not allowed to modify orders and positions
   freeze_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
   if(freeze_level!=0)
     {
      PrintFormat("SYMBOL_TRADE_FREEZE_LEVEL=%d: order or position modification is not allowed,"+
                  " if there are %d points to the activation price",freeze_level,freeze_level);
     }
      
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick(void)
  {
 stop();
   if(USEMOVETOBREAKEVEN) MOVETOBREAKEVEN();
   Trail1();
   int    ticket;
// Check for New Bar (Compatible with both MQL4 and MQL5)
   static datetime dtBarCurrent=WRONG_VALUE;
   datetime dtBarPrevious=dtBarCurrent;
   dtBarCurrent=(datetime) SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
   bool NewBarFlag=(dtBarCurrent!=dtBarPrevious);
// initial data checks
// it is important to make sure that the expert works with a normal
// chart and the user did not make any mistakes setting external 
// variables (Lots, StopLoss, TakeProfit, 
// TrailingStop) in our case, we check TakeProfit
// on a chart of less than 100 bars
//---
   if(Bars<100)
     {
      Print("bars less than 100");
      return;
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return;
     }
//--- to simplify the coding and speed up access data are put into internal variables     
//+------------------------------------------------------------------+
   double middleBB=iBands(Symbol(),0,20, 2,0,0,MODE_MAIN,1);//middle
   double lowerBB=iBands(Symbol(),0,20, 2,0,0,MODE_LOWER,1);//lower
   double upperBB=iBands(Symbol(),0,20, 2,0,0,MODE_UPPER,1);//upper
//+------------------------------------------------------------------+                                        
   double  MacdMAIN=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   double  MacdSIGNAL=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
//+------------------------------------------------------------------+    
//-------------------------------------------------------------------------------------------------- 
   double ADX=iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0);          //Base indicator line
   double PLUS_DI=iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0);    //+DI indicator line
   double MINUS_DI=iADX(NULL,0,14,PRICE_HIGH,MODE_MINUSDI,0);  //-DI indicator line
   double ADX1=iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,1);         //Base indicator line
   double PLUS_DI1=iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,1);   //+DI indicator line
   double MINUS_DI1=iADX(NULL,0,14,PRICE_HIGH,MODE_MINUSDI,1); //-DI indicator line       
//-------------------------------------------------------------------- - -----------------------
   if(getOpenOrders()==0)

     {
      //--- no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ",AccountFreeMargin());
         return;
        }
      if(NewBarFlag)
        {
         //--- check for long position (BUY) possibility
         //+------------------------------------------------------------------+ 
         //| BUY                      BUY                 BUY                 |
         //+------------------------------------------------------------------+
         // if(Volume[0]>1) return;
           {
            if(adx()==1)
              {
               ticket=OrderSend(Symbol(),OP_BUY,LotsOptimized(),ND(Ask),3,NDTP(Bid-Stop_Loss*pips),NDTP(Bid+TakeProfit*pips),"renko",MagicNumber,0,PaleGreen);
               if(ticket>0)
                 {
                  if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                     Print("BUY order opened : ",OrderOpenPrice());
                 }
               else
                  Print("Error opening BUY order : ",GetLastError());
               return;
              }
           }
         //--- check for short position (SELL) possibility
         //+------------------------------------------------------------------+
         //| SELL             SELL                       SELL                 |
         //+------------------------------------------------------------------+
         if(adx()==2)
           {
            ticket=OrderSend(Symbol(),OP_SELL,LotsOptimized(),ND(Bid),3,NDTP(Ask+Stop_Loss*pips),NDTP(Ask-TakeProfit*pips),"Short 1",MagicNumber,0,Red);
            if(ticket>0)
              {
               if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                  Print("SELL order opened : ",OrderOpenPrice());
              }
            else
               Print("Error opening SELL order : ",GetLastError());
           }
         
         return;
        }
     }
  }
//+------------------------------------------------------------------+
//|   stop                                                           |
//+------------------------------------------------------------------+   
//-----------------------------------------------------------------------------+ 
void stop()
  {
   int cnt;
//+------------------------------------------------------------------+
   double middleBB=iBands(Symbol(),0,20, 2,0,0,MODE_MAIN,1);//middle
   double lowerBB=iBands(Symbol(),0,20, 2,0,0,MODE_LOWER,1);//lower
   double upperBB=iBands(Symbol(),0,20, 2,0,0,MODE_UPPER,1);//upper
//+------------------------------------------------------------------+                                        
   double  MacdMAIN=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   double  MacdSIGNAL=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
//+------------------------------------------------------------------+       
   for(cnt=0;cnt<total;cnt++)
     {
      if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
         continue;
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for symbol
        {
         //--- long position is opened
         if(OrderType()==OP_BUY)
           {
            //--- should it be closed?

            if( Close[1]==upperBB)
               exitbuys();
            //--- check for trailing stop
           }
         else // go to short position
           {
            //--- should it be closed?

            if(Close[1]==lowerBB)
               exitsells();
            //--- check for trailing stop
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Trailing stop loss                                               |
//+------------------------------------------------------------------+ 
// --------------- ----------------------------------------------------------- ------------------------                    
void Trail1()
  {
   total=OrdersTotal();
//--- it is important to enter the market correctly, but it is more important to exit it correctly...   
   for(int cnt=0;cnt<total;cnt++)
     {
      if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
         continue;
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for symbol
        {
         //--- long position is opened
         if(OrderType()==OP_BUY)
           {

            //--- check for trailing stop
            if(TrailingStop>0)
              {
               if(Bid-OrderOpenPrice()>pips*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-pips*TrailingStop)
                    {

                     RefreshRates();
                     stoploss=Bid-(pips*TrailingStop);
                     takeprofit=OrderTakeProfit()+pips*TrailingStop;
                     double StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD);
                     if(stoploss<StopLevel*pips) stoploss=StopLevel*pips;
                     string symbol=OrderSymbol();
                     double point=SymbolInfoDouble(symbol,SYMBOL_POINT);
                     if(MathAbs(OrderStopLoss()-stoploss)>point)
                        if((pips*TrailingStop)>(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL)*pips)

                           //--- modify order and exit
                           if(CheckStopLoss_Takeprofit(OP_BUY,stoploss,takeprofit))
                              if(OrderModifyCheck(OrderTicket(),OrderOpenPrice(),stoploss,takeprofit))
                                 if(!OrderModify(OrderTicket(),OrderOpenPrice(),stoploss,takeprofit,0,Green))
                                    Print("OrderModify error ",GetLastError());
                     return;
                    }
                 }
              }
           }
         else // go to short position
           {
            //--- check for trailing stop
            if(TrailingStop>0)
              {
               if((OrderOpenPrice()-Ask)>(pips*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+pips*TrailingStop)) || (OrderStopLoss()==0))
                    {

                     RefreshRates();
                     stoploss=Ask+(pips*TrailingStop);
                     takeprofit=OrderTakeProfit()-pips*TrailingStop;
                     double StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL)+MarketInfo(Symbol(),MODE_SPREAD);
                     if(stoploss<StopLevel*pips) stoploss=StopLevel*pips;
                     if(takeprofit<StopLevel*pips) takeprofit=StopLevel*pips;
                     string symbol=OrderSymbol();
                     double point=SymbolInfoDouble(symbol,SYMBOL_POINT);
                     if(MathAbs(OrderStopLoss()-stoploss)>point)
                        if((pips*TrailingStop)>(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL)*pips)

                           //--- modify order and exit
                           if(CheckStopLoss_Takeprofit(OP_SELL,stoploss,takeprofit))
                              if(OrderModifyCheck(OrderTicket(),OrderOpenPrice(),stoploss,takeprofit))
                                 if(!OrderModify(OrderTicket(),OrderOpenPrice(),stoploss,takeprofit,0,Red))
                                    Print("OrderModify error ",GetLastError());
                     return;
                    }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//+---------------------------------------------------------------------------+
//|                          MOVE TO BREAK EVEN                               |
//+---------------------------------------------------------------------------+
void MOVETOBREAKEVEN()

  {
   for(int b=OrdersTotal()-1;b>=0;b--)
     {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()!=MagicNumber)continue;
      if(OrderSymbol()==Symbol())
         if(OrderType()==OP_BUY)
            if(Bid-OrderOpenPrice()>WHENTOMOVETOBE*pips)
               if(OrderOpenPrice()>OrderStopLoss())
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(PIPSTOMOVESL*pips),OrderTakeProfit(),0,CLR_NONE))
                     Print("eror");
     }

   for(int s=OrdersTotal()-1;s>=0;s--)
     {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
         if(OrderMagicNumber()!=MagicNumber)continue;
      if(OrderSymbol()==Symbol())
         if(OrderType()==OP_SELL)
            if(OrderOpenPrice()-Ask>WHENTOMOVETOBE*pips)
               if(OrderOpenPrice()<OrderStopLoss())
                  if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(PIPSTOMOVESL*pips),OrderTakeProfit(),0,CLR_NONE))
                     Print("eror");
     }
  }
//--------------------------------------------------------------------------------------

//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=OrdersHistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   if(MaximumRisk>0)
     {
      lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
     }
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() /*|| OrderType()>OP_SELL*/)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- minimal allowed volume for trade operations
   double minlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   if(lot<minlot)
     { lot=minlot; }
// Print("Volume is less than the minimal allowed ,we use",minlot);}
// lot=minlot;

//--- maximal allowed volume of trade operations
   double maxlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   if(lot>maxlot)
     { lot=maxlot;  }
//  Print("Volume is greater than the maximal allowed,we use",maxlot);}
// lot=maxlot;

//--- get minimal step of volume changing
   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
   int ratio=(int)MathRound(lot/volume_step);
   if(MathAbs(ratio*volume_step-lot)>0.0000001)
     {  lot=ratio*volume_step;}
   return(lot);
/* else  Print("StopOut level  Not enough money for ",OP_SELL," ",lot," ",Symbol());
   return(0);*/
  }
//+------------------------------------------------------------------+
double NDTP(double val)
  {
   RefreshRates();
   double SPREAD=MarketInfo(Symbol(),MODE_SPREAD);
   double StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   if(val<StopLevel*pips+SPREAD*pips) val=StopLevel*pips+SPREAD*pips;
// double STOPLEVEL = MarketInfo(Symbol(),MODE_STOPLEVEL);
//int Stops_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);

//if (Stops_level*pips<val-Bid)
//val=Ask+Stops_level*pips;
   return(NormalizeDouble(val, Digits));
// return(val);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
double ND(double val)
  {
   return(NormalizeDouble(val, Digits));
  }
//+------------------------------------------------------------------+ 
////////////////////////////////////////////////////////////////////////////////////
int getOpenOrders()
  {

   int Orders=0;
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
        {
         continue;
        }
      if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber)
        {
         continue;
        }
      Orders++;
     }
   return(Orders);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int adx()
  {
//---
   double ADX=iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0);          //Base indicator line
   double PLUS_DI=iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0);    //+DI indicator line
   double MINUS_DI=iADX(NULL,0,14,PRICE_HIGH,MODE_MINUSDI,0);  //-DI indicator line
   double ADX1=iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,1);         //Base indicator line
   double PLUS_DI1=iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,1);   //+DI indicator line
   double MINUS_DI1=iADX(NULL,0,14,PRICE_HIGH,MODE_MINUSDI,1); //-DI indicator line       
//-------------------------------------------------------------------- - -----------------------  
   double   MA_1_t=iMA(NULL,0,FastMA,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_1
   double   MA_2_t=iMA(NULL,0,SlowMA,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_2
//--------------------------------------------------------------------------------------------------   
   double   MomLevel=MathAbs(100-iMomentum(NULL,0,14,PRICE_CLOSE,1));
   double   MomLevel1=MathAbs(100 - iMomentum(NULL,0,14,PRICE_CLOSE,2));
   double   MomLevel2=MathAbs(100 - iMomentum(NULL,0,14,PRICE_CLOSE,3));
   double   MomLevel3=MathAbs(100 - iMomentum(NULL,0,14,PRICE_CLOSE,0));
//--------------------------------------------------------------------------------------------------   
   double    Mom=iMomentum(NULL,0,14,PRICE_CLOSE,1);
   double    Mom1=iMomentum(NULL,0,14,PRICE_CLOSE,2);
//--------------------------------------------------------------------------------------------------  
//+------------------------------------------------------------------+
//| BUY                                      BUY                     |
//+------------------------------------------------------------------+

   if(Breakout_Strategies==true)
     {
      // Entry Strategies
      //if(ADX>Min_Level_Of_Main_Line)
      //--------------------------------------------------------------------------------------------------          
      if(Trend_Filter==true)
        {
         if((ADX>Entry_Level)
            || (PLUS_DI>Entry_Level))
            if(PLUS_DI>MINUS_DI)
               if(MathAbs(PLUS_DI-MINUS_DI)>Min_Price_Difference)
                  if(MA_1_t>MA_2_t )

                     if(Mom>Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(1);//return(0);
        }
      //--------------------------------------------------------------------------------------------------         
      if(Trend_Filter==false)
        {
         if((ADX>Entry_Level)
            || (PLUS_DI>Entry_Level))
            if(MathAbs(PLUS_DI-MINUS_DI)>Min_Price_Difference)
               if(MA_1_t>MA_2_t )

                  if(Mom>Mom1)

                     if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                        return(1);//return(0);
        }
     }
//-------------------------------------------------------------------------------------------------- 
//------------------------------------Cross_Strategy------------------------------------------------

   if(Cross_Strategy==true)
     {

      if(Main_Line_Sloping_Upwards==true)
        {
         if(ADX>ADX1)
            if(Confirm_Cross_On_Breakout==true)
              {
               if((((ADX>Entry_Level)
                  || (PLUS_DI>Entry_Level))
                  && (PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1))
                  || (PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1))
                  if(ADX>Min_Level_Of_Main_Line)
                     if(MA_1_t>MA_2_t )

                        if(Mom>Mom1)

                           if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                              return(1);//return(0);
              }
         //--------------------------------------------------------------------------------------------------                             
         if(Confirm_Cross_On_Breakout==false)
           {
            if(PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1)
               if(ADX>Min_Level_Of_Main_Line)
                  if(MA_1_t>MA_2_t )

                     if(Mom>Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(1);
           }
        }
      //--------------------------------------------------------------------------------------------------                            
      if(Main_Line_Sloping_Upwards==false)
        {
         if(Confirm_Cross_On_Breakout==true)
           {
            if((((ADX>Entry_Level)
               || (PLUS_DI>Entry_Level))
               && (PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1))
               || (PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1))
               if(ADX>Min_Level_Of_Main_Line)
                  if(MA_1_t>MA_2_t )

                     if(Mom>Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(1);//return(0);
           }
         //--------------------------------------------------------------------------------------------------                             
         if(Confirm_Cross_On_Breakout==false)
           {
            if(PLUS_DI>MINUS_DI && PLUS_DI1<MINUS_DI1)
               if(ADX>Min_Level_Of_Main_Line)
                  if(MA_1_t>MA_2_t )

                     if(Mom>Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(1);
           }

        }
     }
//+------------------------------------------------------------------+
//| SELL                                       מכירה                 |
//+------------------------------------------------------------------+
   if(Volume[0]>1) return(0);

   if(Breakout_Strategies==true)
     {
      // Entry Strategies
      // if(ADX<Min_Level_Of_Main_Line)
      //--------------------------------------------------------------------------------------------------          
/*1*/        if(Trend_Filter==true)
        {
         if((ADX>Entry_Level)
            || (MINUS_DI<Entry_Level))
            if(PLUS_DI<MINUS_DI)
               if(MathAbs(PLUS_DI-MINUS_DI)>Min_Price_Difference)
                  if(MA_1_t<MA_2_t )

                     if(Mom<Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(2);
        }
      //--------------------------------------------------------------------------------------------------          
/*2*/    if(Trend_Filter==false)
        {
         if((ADX>Entry_Level)
            || (MINUS_DI<Entry_Level))
            if(MathAbs(PLUS_DI-MINUS_DI)>Min_Price_Difference)
               if(MA_1_t<MA_2_t )

                  if(Mom<Mom1)

                     if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                        return(2);
        }
     }
//-------------------------------------------------------------------------------------------------- 
//------------------------------------Cross_Strategy------------------------------------------------
/*3*/     if(Cross_Strategy==true)
     {

      if(Main_Line_Sloping_Upwards==true)
        {
         if(ADX>ADX1)
            if(Confirm_Cross_On_Breakout==true)
              {
               if((((ADX<Entry_Level)
                  || (MINUS_DI<Entry_Level))
                  && (PLUS_DI<MINUS_DI && PLUS_DI1>MINUS_DI1))
                  || (PLUS_DI<MINUS_DI && PLUS_DI1>MINUS_DI1))
                  if(ADX>Min_Level_Of_Main_Line)
                     if(MA_1_t<MA_2_t )

                        if(Mom<Mom1)

                           if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                              return(2);
              }
         //--------------------------------------------------------------------------------------------------                           
/*4*/     if(Confirm_Cross_On_Breakout==false)
           {
            if(PLUS_DI>MINUS_DI && PLUS_DI1>MINUS_DI1)
               if(ADX>Min_Level_Of_Main_Line)
                  if(MA_1_t<MA_2_t )

                     if(Mom<Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(2);
           }
        }
      //--------------------------------------------------------------------------------------------------                            
/*5*/    if(Main_Line_Sloping_Upwards==false)
        {
         if(Confirm_Cross_On_Breakout==true)
           {
            if((((ADX>Entry_Level)
               || (MINUS_DI<Entry_Level))
               && (PLUS_DI<MINUS_DI && PLUS_DI1>MINUS_DI1))
               || (PLUS_DI<MINUS_DI && PLUS_DI1>MINUS_DI1))
               if(MA_1_t<MA_2_t )

                  if(Mom<Mom1)

                     if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                        if(ADX>Min_Level_Of_Main_Line)
                           return(2);
           }
         //--------------------------------------------------------------------------------------------------                           
/*6*/     if(Confirm_Cross_On_Breakout==false)
           {
            if(PLUS_DI<MINUS_DI && PLUS_DI1>MINUS_DI1)
               if(ADX>Min_Level_Of_Main_Line)
                  if(MA_1_t<MA_2_t )

                     if(Mom<Mom1)

                        if(iVolume(_Symbol,0,1)>iVolume(_Symbol,0,2) || iVolume(_Symbol,0,1)>iVolume(_Symbol,0,3))
                           return(2);
           }
        }
     }
   return(0);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Checking the new values of levels before order modification      |
//+------------------------------------------------------------------+
bool OrderModifyCheck(int ticket,double price,double sl,double tp)
  {
//--- select order by ticket
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      //--- point size and name of the symbol, for which a pending order was placed
      string symbol=OrderSymbol();
      double point=SymbolInfoDouble(symbol,SYMBOL_POINT);
      //--- check if there are changes in the Open price
      bool PriceOpenChanged=true;
      int type=OrderType();
      if(!(type==OP_BUY || type==OP_SELL))
        {
         PriceOpenChanged=(MathAbs(OrderOpenPrice()-price)>point);
        }
      //--- check if there are changes in the StopLoss level
      bool StopLossChanged=(MathAbs(OrderStopLoss()-sl)>point);
      //--- check if there are changes in the Takeprofit level
      bool TakeProfitChanged=(MathAbs(OrderTakeProfit()-tp)>point);
      //--- if there are any changes in levels
      if(PriceOpenChanged || StopLossChanged || TakeProfitChanged)
         return(true);  // order can be modified      
      //--- there are no changes in the Open, StopLoss and Takeprofit levels
      else
      //--- notify about the error
         PrintFormat("Order #%d already has levels of Open=%.5f SL=%.5f TP=%.5f",
                     ticket,OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
     }
//--- came to the end, no changes for the order
   return(false);       // no point in modifying 
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
bool CheckStopLoss_Takeprofit(ENUM_ORDER_TYPE type,double SL,double TP)
  {
//--- get the SYMBOL_TRADE_STOPS_LEVEL level
   int stops_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   if(stops_level!=0)
     {
      PrintFormat("SYMBOL_TRADE_STOPS_LEVEL=%d: StopLoss and TakeProfit must"+
                  " not be nearer than %d points from the closing price",stops_level,stops_level);
     }
//---
   bool SL_check=false,TP_check=false;
//--- check only two order types
   switch(type)
     {
      //--- Buy operation
      case  ORDER_TYPE_BUY:
        {
         //--- check the StopLoss
         SL_check=(Bid-SL>stops_level*_Point);
         if(!SL_check)
            PrintFormat("For order %s StopLoss=%.5f must be less than %.5f"+
                        " (Bid=%.5f - SYMBOL_TRADE_STOPS_LEVEL=%d points)",
                        EnumToString(type),SL,Bid-stops_level*_Point,Bid,stops_level);
         //--- check the TakeProfit
         TP_check=(TP-Bid>stops_level*_Point);
         if(!TP_check)
            PrintFormat("For order %s TakeProfit=%.5f must be greater than %.5f"+
                        " (Bid=%.5f + SYMBOL_TRADE_STOPS_LEVEL=%d points)",
                        EnumToString(type),TP,Bid+stops_level*_Point,Bid,stops_level);
         //--- return the result of checking
         return(SL_check&&TP_check);
        }
      //--- Sell operation
      case  ORDER_TYPE_SELL:
        {
         //--- check the StopLoss
         SL_check=(SL-Ask>stops_level*_Point);
         if(!SL_check)
            PrintFormat("For order %s StopLoss=%.5f must be greater than %.5f "+
                        " (Ask=%.5f + SYMBOL_TRADE_STOPS_LEVEL=%d points)",
                        EnumToString(type),SL,Ask+stops_level*_Point,Ask,stops_level);
         //--- check the TakeProfit
         TP_check=(Ask-TP>stops_level*_Point);
         if(!TP_check)
            PrintFormat("For order %s TakeProfit=%.5f must be less than %.5f "+
                        " (Ask=%.5f - SYMBOL_TRADE_STOPS_LEVEL=%d points)",
                        EnumToString(type),TP,Ask-stops_level*_Point,Ask,stops_level);
         //--- return the result of checking
         return(TP_check&&SL_check);
        }
      break;
     }
//--- a slightly different function is required for pending orders
   return false;
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                      exitbuys()                  |
//+------------------------------------------------------------------+
void exitbuys()
  {
   double result;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
           {
            result=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrNONE);
            if(result!=true)//if it did not close
              {
               err=GetLastError(); Print("LastError = ",err);//get the reason why it didn't close
              }

           }
        }

     }
  }
//+------------------------------------------------------------------+  
//+------------------------------------------------------------------+
//|                    exitsells()                                   |
//+------------------------------------------------------------------+
void exitsells()
  {
   double result;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {

         if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
           {
            result=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrNONE);
            if(result!=true)//if it did not close
              {
               err=GetLastError(); Print("LastError = ",err);//get the reason why it didn't close
              }

           }
        }

     }
  }


//+------------------------------------------------------------------+