Author: AHARON TZADIK

Okay, here's a breakdown of what this MetaTrader MQL script appears to do, explained in plain language for someone who isn't a programmer.

Overall Purpose:

This script is designed to automate trading on the MetaTrader platform. It analyzes price data and market conditions to decide when to open and close trades, aiming to generate profit based on a set of predefined rules and strategies. It is a "robot" or "Expert Advisor" (EA) intended to execute trades automatically without human intervention.

Key Sections and Their Logic:

  1. Setup (Properties and Inputs):

    • The script starts by defining its basic information like name ("AHARON TZADIK"), a website link, and version number.
    • Crucially, it defines a number of input parameters. These are settings that the user can adjust to customize how the script operates. These include things like:
      • Lot size: which determines the size of the trades the robot should make.
      • Stop loss and take profit levels: these define risk management by setting the price at which a trade will automatically close to prevent further loss or to secure a profit.
      • Trailing stop: This is used for managing existing positions.
      • Moving Average (MA) periods: These define the lookback period the moving average is calculated on.
      • Momentum values: These are settings for a momentum indicator, influencing buy and sell decisions.
  2. Initialization (OnInit):

    • This section runs once when the script is first loaded onto a chart.
    • It performs some initial calculations and sets up the environment for trading.
    • A key part of this is to determine coefficients based on the current time frame, affecting calculations made by the script.
    • It also checks that the trading environment is suitable (e.g., enough bars on the chart).
  3. Deinitialization (OnDeinit):

    • This section runs when the script is removed from the chart or when MetaTrader closes.
    • In this specific script, it currently doesn't have any actions defined, implying a clean shutdown is not critical for functionality
  4. Main Loop (OnTick):

    • This is the heart of the script. It runs every time there's a new price update (a "tick") in the market.
    • Inside this loop, the script continuously analyzes the market and makes trading decisions.
    • It starts by calculating potential Take Profit based on different criteria (money or percentage), if either or both is selected to true.
    • It is also used to calculate if the trailing stop needs to be updated for existing trades if its enabled by the user.
    • It also has an equity stop to stop trading if a specific value is meet.
    • It also can move the break even to a "no loss" position, if enabled by the user.
    • It checks whether it's time to create a new order
    • It then retrieves price data.
  5. Trading Logic (Inside OnTick):

    • The script checks if the maximum number of allowed trades has been reached. If not, it proceeds with analysis.
    • It uses moving averages (MAs), Rate of Change (ROC) to identify the market trend.
    • Based on these indicators, it decides whether to place a "Buy" or "Sell" order
    • Before placing an order, it performs several checks:
      • Enough free margin (available funds) in the account.
      • Volume limits meet requirements (minimum and maximum lot sizes).
      • Stop loss and take profit levels are within acceptable ranges.
    • If all checks pass, it uses the OrderSend function to place the trade.
    • It sets the stop loss and take profit levels for the order.
    • The script sends a notification of a buy or sell signal.
  6. Order Management (Stop):

    • This section is triggered when the user enables the "exit" strategy or an equity risk has been meet.
    • The key purpose here is to manage existing open trades.
    • It checks if the current market conditions signal that a trade should be closed. This is again based on things like moving averages, ROC.
    • If the conditions are met, it uses OrderClose to close the trade.
    • Here is where "Dalyn Guppy MMA" is applied, which is a series of moving averages to decide whether to close the position.
    • Also in this code we can find the use of Bollinger Bands for exit strategies.
  7. Trailing Stop Logic:

    • This functionality adjusts the stop loss level of an open trade as the price moves in a favorable direction.
    • It ensures that if the price reverses, the trade will be closed at a more profitable level than the initial stop loss.
  8. Break-Even Logic:

    • This offers functionality to move the stop loss order to the break even price, or better, by some PIPs (points).

In Summary:

This MQL script is a trading robot that:

  • Uses technical indicators (moving averages, Momentum, etc.) to identify potential trading opportunities.
  • Automatically places "Buy" or "Sell" orders based on its analysis.
  • Manages risk by setting stop loss and take profit levels.
  • Can dynamically adjust stop loss levels using a trailing stop.
  • Can also close positions based on the "Dalyn Guppy MMA" and Bollinger Bands analysis
  • This script is driven by parameters that allow user to configure it.

Important Considerations (Not Addressed by the Description Request, But Still Important):

  • Risk: Automated trading can be risky. It is crucial to thoroughly test any trading robot in a demo account before using it with real money.
  • Market Conditions: A strategy that works well in one market condition might perform poorly in another.
  • Optimization: The input parameters need to be optimized for the specific currency pair and timeframe being traded. This often requires extensive testing.
Orders Execution
It automatically opens orders when conditions are reachedChecks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategyChecks for the total of closed orders
Indicators Used
Moving average indicatorMomentum indicatorMACD HistogramBollinger bands indicator
Miscellaneous
It issuies visual alerts to the screenIt sends emails
7 Views
0 Downloads
0 Favorites
ROC_v2
ÿþ//+------------------------------------------------------------------+

//|           ROC                                                    |

//|            https://5d3071208c5e2.site123.me/                     |

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

#property copyright   "AHARON TZADIK"

#property link        "https://5d3071208c5e2.site123.me/"

#property version     "1.00"

#property strict











extern bool   Use_TP_In_Money=false;

extern double TP_In_Money=10;

extern bool   Use_TP_In_percent=false;

extern double TP_In_Percent=10;

//--------------------------------------------------------------------

//--------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////////

input    string               txt32                    = "------------[Money Trailing Stop]---------------"; //                                           

input    bool                 Enable_Trailing           = true; //Enable_Trailing

input    double               Take_Profit_Money       = 40.0; //Take Profit In Money (in current currency)

input    double               Stop_Loss_Money         = 10; //Stop Loss In Money(in current currency)

/////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------------------

//--------------------------------------------------------------------

//extern int History=100;       //History

extern int Period_MA_0=31;          //Period_MA_0

extern int Period_MA_1=6;          //Period_MA_1

extern int Bars_V=45;          //Bars_V

extern int Aver_Bars  =30;           //Aver_Bars

extern double K       =41;           //K

//--------------------------------------------------------------- 3 --

extern bool         Exit=false;//Enable Exit strategy

extern double       Lots=0.01;              //Lots size

extern double       IncreaseFactor=0.000;   //IncreaseFactor

extern double       Stop_Loss=100;           //Stop Loss

extern int          MagicNumber=1234;       //MagicNumber

input  double       Take_Profit=100;          //TakeProfit

extern int          FastMA=1;               //FastMA

extern int          SlowMA=5;              //SlowMA

extern double       Mom_Sell=0.3;           //Momentum_Sell

extern double       Mom_Buy=0.3;            //Momentum_Buy

input bool   UseEquityStop = true;  //Use Equity Stop

input double TotalEquityRisk = 1.0; //Total Equity Risk

input int    Max_Trades=5;

extern double       TrailingStop=50;        //TrailingStop

input bool         USEMOVETOBREAKEVEN=false;//Enable "no loss"

input double       WHENTOMOVETOBE=30;      //When to move break even

input double       PIPSTOMOVESL=30;         //How much pips to move sl



int           err;

double       AccountEquityHighAmt,PrevEquity;

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,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,L;

//---

int INDEX2=0;

double PROFIT_SUM1=0;

double PROFIT_SUM2=0;

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

//| Expert initialization function                                   |

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

int OnInit()

  {



//---------------------------------------------------------------  --

   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)

  {

   if(Use_TP_In_Money)

     { Take_Profit_In_Money();}

   if(Use_TP_In_percent)

     { Take_Profit_In_percent();}

   if(Enable_Trailing==true)

     {TRAIL_PROFIT_IN_MONEY2();}

   double CurrentPairProfit=CalculateProfit();

// 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);

   if(NewBarFlag)

     {

      if(UseEquityStop)

        {

         if(CurrentPairProfit<0.0 && MathAbs(CurrentPairProfit)>TotalEquityRisk/100.0*AccountEquityHigh())

           {

            CloseThisSymbolAll();

            Print("Closed All due to Stop Out");



           }

        }

      if(Exit)

        {

         stop();

        }

      if(USEMOVETOBREAKEVEN)

        {MOVETOBREAKEVEN();}

      Trail1();

      int    ticket=0;

      // 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(Take_Profit<10)

        {

         Print("TakeProfit less than 10");

         return;

        }

      //--- to simplify the coding and speed up access data are put into internal variables

      HideTestIndicators(true);

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

      double  MA_1_t=iMA(NULL,L,FastMA,0,MODE_LWMA,PRICE_TYPICAL,0); // _1

      double MA_2_t=iMA(NULL,L,SlowMA,0,MODE_LWMA,PRICE_TYPICAL,0); // _2

      //----------------------------------------------------------------------------

      //--------------------------------------------------------------------------------------------------

      double   MomLevelB=MathAbs(100-iMomentum(NULL,T,14,PRICE_CLOSE,1));

      double   MomLevelB1=MathAbs(100 - iMomentum(NULL,T,14,PRICE_CLOSE,2));

      double   MomLevelB2=MathAbs(100 - iMomentum(NULL,T,14,PRICE_CLOSE,3));

      double   MomLevelS=MathAbs(iMomentum(NULL,T,14,PRICE_CLOSE,1)-100);

      double   MomLevelS1=MathAbs(iMomentum(NULL,T,14,PRICE_CLOSE,2)-100);

      double   MomLevelS2=MathAbs(iMomentum(NULL,T,14,PRICE_CLOSE,3)-100);

      //--------------------------------------------------------------------------------------------------

      //--------------------------------------------------------------------------------------------------

      double  MacdMAIN0=iMACD(NULL,PERIOD_MN1,12,26,9,PRICE_CLOSE,MODE_MAIN,1);

      double  MacdSIGNAL0=iMACD(NULL,PERIOD_MN1,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);

      HideTestIndicators(false);

      //--------------------------------------------------------------------------------------------------

      // if(getOpenOrders()==0)

      if(CountTrades()<Max_Trades)

        {

         //--- no opened orders identified

         if(AccountFreeMargin()<(1000*Lots))

           {

            Print("We have no money. Free Margin = ",AccountFreeMargin());

            return;

           }



         //--- check for long position (BUY) possibility

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

         //| BUY                      BUY                 BUY                 |

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

         if(ROC()==1)

            if(MA_1_t>MA_2_t)

               if(MomLevelB>Mom_Buy || MomLevelB1>Mom_Buy || MomLevelB2>Mom_Buy)

                  if((MacdMAIN0>0 && MacdMAIN0>MacdSIGNAL0) || (MacdMAIN0<0 && MacdMAIN0>MacdSIGNAL0))

                    {

                     if((CheckVolumeValue(LotsOptimized(Lots)))==TRUE)

                        if((CheckMoneyForTrade(Symbol(),LotsOptimized(Lots),OP_BUY))==TRUE)

                           if((CheckStopLoss_Takeprofit(OP_BUY,NDTP(Bid-Stop_Loss*pips),NDTP(Bid+Take_Profit*pips)))==TRUE)

                              ticket=OrderSend(Symbol(),OP_BUY,LotsOptimized(Lots),ND(Ask),3,NDTP(Bid-Stop_Loss*pips),NDTP(Bid+Take_Profit*pips),"Long 1",MagicNumber,0,PaleGreen);

                     if(ticket>0)

                       {

                        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))

                           Print("BUY order opened : ",OrderOpenPrice());

                        Alert("we just got a buy signal on the ",_Period,"M",_Symbol);

                        SendNotification("we just got a buy signal on the1 "+(string)_Period+"M"+_Symbol);

                        SendMail("Order sent successfully","we just got a buy signal on the1 "+(string)_Period+"M"+_Symbol);

                       }

                     else

                        Print("Error opening BUY order : ",GetLastError());

                     return;

                    }

         //--- check for short position (SELL) possibility

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

         //| SELL             SELL                       SELL                 |

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

         if(ROC()==2)

            if(MA_1_t<MA_2_t)

               if(MomLevelS>Mom_Sell || MomLevelS1>Mom_Sell || MomLevelS2>Mom_Sell)

                  if((MacdMAIN0>0 && MacdMAIN0<MacdSIGNAL0) || (MacdMAIN0<0 && MacdMAIN0<MacdSIGNAL0))

                    {

                     if((CheckVolumeValue(LotsOptimized(Lots)))==TRUE)

                        if((CheckMoneyForTrade(Symbol(),LotsOptimized(Lots),OP_SELL))==TRUE)

                           if((CheckStopLoss_Takeprofit(OP_SELL,NDTP(Ask+Stop_Loss*pips),NDTP(Ask-Take_Profit*pips)))==TRUE)

                              ticket=OrderSend(Symbol(),OP_SELL,LotsOptimized(Lots),ND(Bid),3,NDTP(Ask+Stop_Loss*pips),NDTP(Ask-Take_Profit*pips),"Short 1",MagicNumber,0,Red);

                     if(ticket>0)

                       {

                        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))

                           Print("SELL order opened : ",OrderOpenPrice());

                        Alert("we just got a sell signal on the ",_Period,"M",_Symbol);

                        SendMail("Order sent successfully","we just got a sell signal on the "+(string)_Period+"M"+_Symbol);

                       }

                     else

                        Print("Error opening SELL order : ",GetLastError());

                    }

         //--- exit from the "no opened orders" block

         return;

        }

     }

  }

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

//|   stop                                                           |

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

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

int stop()

  {

   total=0;

   HideTestIndicators(true);

   double MA_1_t=iMA(NULL,L,FastMA,0,MODE_LWMA,PRICE_TYPICAL,0); // _1

   double MA_2_t=iMA(NULL,L,SlowMA,0,MODE_LWMA,PRICE_TYPICAL,0); // _2

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

   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  MacdMAIN0=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);

   double  MacdSIGNAL0=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);

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

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

//   DALYN GUPPY MMA

//----------------------------------------------------------------------------

   double  MA_3=iMA(NULL,L,3,0,MODE_EMA,PRICE_TYPICAL,0); // _3    DALYN GUPPY MMA

   double  MA_5=iMA(NULL,L,5,0,MODE_EMA,PRICE_TYPICAL,0); // _5    DALYN GUPPY MMA

   double  MA_8=iMA(NULL,L,8,0,MODE_EMA,PRICE_TYPICAL,0); // _8    DALYN GUPPY MMA

   double  MA_10=iMA(NULL,L,10,0,MODE_EMA,PRICE_TYPICAL,0); // _10 DALYN GUPPY MMA

   double  MA_12=iMA(NULL,L,12,0,MODE_EMA,PRICE_TYPICAL,0); // _12 DALYN GUPPY MMA

   double  MA_15=iMA(NULL,L,15,0,MODE_EMA,PRICE_TYPICAL,0); // _15 DALYN GUPPY MMA

   double  MA_30=iMA(NULL,L,30,0,MODE_EMA,PRICE_TYPICAL,0); // _30 DALYN GUPPY MMA

   double  MA_35=iMA(NULL,L,35,0,MODE_EMA,PRICE_TYPICAL,0); // _35 DALYN GUPPY MMA

   double  MA_40=iMA(NULL,L,40,0,MODE_EMA,PRICE_TYPICAL,0); // _40 DALYN GUPPY MMA

   double  MA_45=iMA(NULL,L,45,0,MODE_EMA,PRICE_TYPICAL,0); // _45 DALYN GUPPY MMA

   double  MA_50=iMA(NULL,L,50,0,MODE_EMA,PRICE_TYPICAL,0); // _50 DALYN GUPPY MMA

   double  MA_60=iMA(NULL,L,60,0,MODE_EMA,PRICE_TYPICAL,0); // _60 DALYN GUPPY MMA

//-----------------------------------------------------------------------------------

   HideTestIndicators(false);

   for(int trade=OrdersTotal()-1; trade>=0; trade--)

     {

      if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

        {

         if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber)

            continue;

         if(OrderSymbol()==Symbol() || OrderMagicNumber()==MagicNumber)

           {

            if(OrderType()==OP_BUY)

              {

               //--- should it be closed?

               if(((MA_3==MA_5 && MA_5==MA_8 && MA_8==MA_10 && MA_10==MA_12 && MA_12==MA_15)

                   ||(MA_30==MA_35 && MA_35==MA_40 && MA_40==MA_45 && MA_45==MA_50 && MA_50==MA_60))

                  ||(Close[1]<=lowerBB))

                  if(!OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,Red))

                     Print("Did not close");

               break;

               Print(" CLOSE BY EXIT STRATEGY ");

               //--- check for trailing stop

              }

            else // go to short position

              {

               //--- should it be closed?

               if(((MA_3==MA_5 && MA_5==MA_8 && MA_8==MA_10 && MA_10==MA_12 && MA_12==MA_15)

                   ||(MA_30==MA_35 && MA_35==MA_40 && MA_40==MA_45 && MA_45==MA_50 && MA_50==MA_60))

                  ||(Close[1]<=lowerBB))

                  if(!OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,Red))

                     Print("Did not close");

               break;

               Print(" CLOSE BY EXIT STRATEGY ");

               //--- check for trailing stop

              }

           }

        }

     }

   return(0);

  }

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

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

//| 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(OrderMagicNumber()!=MagicNumber)

         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();

                     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();

                     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");

     }

  }

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

//                 NormalizeDouble                                   |

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

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;

   return(NormalizeDouble(val, Digits));

// return(val);

  }

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

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

double ND(double val)

  {

   return(NormalizeDouble(val, Digits));

  }

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

//| 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;

  }

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

////////////////////////////////////////////////////////////////////////////////////

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);

  }

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

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

//| Calculate optimal lot size buy                                   |

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

double LotsOptimized1Mxs(double llots)

  {

   double lots=llots;

//--- minimal allowed volume for trade operations

   double minlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);

   if(lots<minlot)

     { lots=minlot; }

//--- maximal allowed volume of trade operations

   double maxlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);

   if(lots>maxlot)

     { lots=maxlot;  }

//--- get minimal step of volume changing

   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   int ratio=(int)MathRound(lots/volume_step);

   if(MathAbs(ratio*volume_step-lots)>0.0000001)

     {  lots=ratio*volume_step;}

   if(((AccountStopoutMode()==1) &&

       (AccountFreeMarginCheck(Symbol(),OP_BUY,lots)>AccountStopoutLevel()))

      || ((AccountStopoutMode()==0) &&

          ((AccountEquity()/(AccountEquity()-AccountFreeMarginCheck(Symbol(),OP_BUY,lots))*100)>AccountStopoutLevel())))

      return(lots);

   /* else  Print("StopOut level  Not enough money for ",OP_SELL," ",lot," ",Symbol());*/

   return(0);

  }

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

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

//| Calculate optimal lot size buy                                   |

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

double LotsOptimizedMxs(double llots)

  {

   double lots=llots;

//--- minimal allowed volume for trade operations

   double minlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);

   if(lots<minlot)

     {

      lots=minlot;

      Print("Volume is less than the minimal allowed ,we use",minlot);

     }

//--- maximal allowed volume of trade operations

   double maxlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);

   if(lots>maxlot)

     {

      lots=maxlot;

      Print("Volume is greater than the maximal allowed,we use",maxlot);

     }

//--- get minimal step of volume changing

   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   int ratio=(int)MathRound(lots/volume_step);

   if(MathAbs(ratio*volume_step-lots)>0.0000001)

     {

      lots=ratio*volume_step;



      Print("Volume is not a multiple of the minimal step ,we use the closest correct volume ",ratio*volume_step);

     }



   return(lots);



  }

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

//| Check the correctness of the order volume                        |

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

bool CheckVolumeValue(double volume/*,string &description*/)



  {

   double lot=volume;

   int    orders=OrdersHistoryTotal();     // history orders total

   int    losses=0;                  // number of losses orders without a break

//--- select lot size

//--- maximal allowed volume of trade operations

   double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);

   if(lot>max_volume)



      Print("Volume is greater than the maximal allowed ,we use",max_volume);

//  return(false);



//--- minimal allowed volume for trade operations

   double minlot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);

   if(lot<minlot)



      Print("Volume is less than the minimal allowed ,we use",minlot);

//  return(false);



//--- 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)

     {

      Print("Volume is not a multiple of the minimal step ,we use, the closest correct volume is %.2f",

            volume_step,ratio*volume_step);

      //   return(false);

     }

//  description="Correct volume value";

   return(true);

  }

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

bool CheckMoneyForTrade(string symb,double lots,int type)

  {

   double free_margin=AccountFreeMarginCheck(symb,type,lots);

//-- if there is not enough money

   if(free_margin>0)

     {

      if((AccountStopoutMode()==1) &&

         (AccountFreeMarginCheck(symb,type,lots)<AccountStopoutLevel()))

        {

         Print("StopOut level  Not enough money ", type," ",lots," ",Symbol());

         return(false);

        }

      if(AccountEquity()-AccountFreeMarginCheck(Symbol(),type,lots)==0)

        {

         Print("StopOut level  Not enough money ", type," ",lots," ",Symbol());

         return(false);

        }

      if((AccountStopoutMode()==0) &&

         ((AccountEquity()/(AccountEquity()-AccountFreeMarginCheck(Symbol(),type,lots))*100)<AccountStopoutLevel()))

        {

         Print("StopOut level  Not enough money ", type," ",lots," ",Symbol());

         return(false);

        }

     }

   else

      if(free_margin<0)

        {

         string oper=(type==OP_BUY)? "Buy":"Sell";

         Print("Not enough money for ",oper," ",lots," ",symb," Error code=",GetLastError());

         return(false);

        }

//--- checking successful

   return(true);

  }

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

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

//                        ROC                                        |

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

int ROC()

  {

   double

   MA_0=0,MA_02,MA_03,              // Supporting MAs for diff. TF

   MA_c, MA_p;                      // Current and previous MA values

//--------------------------------------------------------------- 3 --

   int n=0;

   double

   Line_0=0,// Indicator array of supp. MA

   Line_1 =0,Line_2=0, Line_3=0,    // Indicator array of rate lines

   Line_4=0,                        // Indicator array - sum

   Line_5=0;                        // Indicator array - sum, smoothed

   int Sh_1;               // Amount of bars for rates calc.

   int Sh_2;

   int Sh_3;



//--------------------------------------------------------------- 5 --

//--------------------------------------------------------------- 6 --

   Sh_1=Bars_V;                     // Period of rate calcul. (bars)

   Sh_2=K2*Sh_1;                    // Calc. period for nearest TF

   Sh_3=K3*Sh_1;                    // Calc. period for next TF

   Period_MA_2 =K2*Period_MA_1;     // Calc. period of MA for nearest TF

   Period_MA_3 =K3*Period_MA_1;     // Calc. period of MA for next TF

   Period_MA_02=K2*Period_MA_0;     // Period of supp. MA for nearest TF

   Period_MA_03=K3*Period_MA_0;     // Period of supp. MA for next TF

//--------------------------------------------------------------- 7 --

   double   Sum=0;

   for(int i=1; i<Aver_Bars; i++)

     {

      HideTestIndicators(true);

      //-------------------------------------------------------- 12 --

      MA_0=iMA(NULL,0,Period_MA_0,0,MODE_LWMA,PRICE_TYPICAL,i);

      Line_0=MA_0;               // Value of supp. MA

      //-------------------------------------------------------- 13 --

      MA_c=iMA(NULL,0,Period_MA_1,0,MODE_LWMA,PRICE_TYPICAL,i);

      MA_p=iMA(NULL,0,Period_MA_1,0,MODE_LWMA,PRICE_TYPICAL,i+Sh_1);

      Line_1=MA_0+K*(MA_c-MA_p);// Value of 1st rate line

      //-------------------------------------------------------- 14 --

      MA_c=iMA(NULL,0,Period_MA_2,0,MODE_LWMA,PRICE_TYPICAL,i);

      MA_p=iMA(NULL,0,Period_MA_2,0,MODE_LWMA,PRICE_TYPICAL,i+Sh_2);

      MA_02=iMA(NULL,0,Period_MA_02,0,MODE_LWMA,PRICE_TYPICAL,i);

      Line_2=MA_02+K*(MA_c-MA_p);// Value of 2nd rate line

      //-------------------------------------------------------- 15 --

      MA_c=iMA(NULL,0,Period_MA_3,0,MODE_LWMA,PRICE_TYPICAL,i);

      MA_p=iMA(NULL,0,Period_MA_3,0,MODE_LWMA,PRICE_TYPICAL,i+Sh_3);

      MA_03=iMA(NULL,0,Period_MA_03,0,MODE_LWMA,PRICE_TYPICAL,i);

      HideTestIndicators(FALSE);

      Line_3=MA_03+K*(MA_c-MA_p);// Value of 3rd rate line

      //-------------------------------------------------------- 16 --

      Line_4=(Line_1+Line_2+Line_3)/3;// Summary array

      //-------------------------------------------------------- 17 --

      Sum=Sum+Line_4;       // Accum. sum of last values

      Line_5=Sum/(i); // Indic. array of smoothed line*/

     }

   if(Line_4<Line_5)

     {

      return(1);

      //TREND=1;

      Comment("The trend is up");

     }

   if(Line_4>Line_5)

     {

      return(2);

      //TREND=2;

      Comment("The trend is down");

     }

   return(0);

  }

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

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

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

//| Calculate optimal lot size buy                                   |

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

double LotsOptimized(double llots)

  {

   double lot=llots;

   int    orders=OrdersHistoryTotal();     // history orders total

   int    losses=0;                  // number of losses orders without a break

//--- calcuulate number of losses orders without a break

   if(IncreaseFactor>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())

            continue;

         //---

         if(OrderProfit()>0)

            break;

         if(OrderProfit()<0)

            losses++;

        }

      if(losses>1)

         // lot=NormalizeDouble(lot+lot*losses/IncreaseFactor,1);

         lot=AccountFreeMargin()*IncreaseFactor/1000.0;

     }

//--- 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;



      Print("Volume is not a multiple of the minimal step ,we use the closest correct volume ",ratio*volume_step);

     }

   return(lot);



  }

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

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

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

//|                                                                  |

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

int CountTrades()

  {

   int count=0;

   for(int trade=OrdersTotal()-1; trade>=0; trade--)

     {

      if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

         Print("Error");

      if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber)

         continue;

      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)

         if(OrderType()==OP_SELL || OrderType()==OP_BUY)

            count++;

     }

   return (count);

  }

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

double AccountEquityHigh()

  {

   if(CountTrades()==0)

      AccountEquityHighAmt=AccountEquity();

   if(AccountEquityHighAmt<PrevEquity)

      AccountEquityHighAmt=PrevEquity;

   else

      AccountEquityHighAmt=AccountEquity();

   PrevEquity=AccountEquity();

   return (AccountEquityHighAmt);

  }

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

double CalculateProfit()

  {

   double Profit=0;

   for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)

     {

      if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))

         Print("Error");

      if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber)

         continue;

      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)

         if(OrderType()==OP_BUY || OrderType()==OP_SELL)

            Profit+=OrderProfit();

     }

   return (Profit);

  }

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

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

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

//|                                                                  |

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

void CloseThisSymbolAll()

  {

   double CurrentPairProfit=CalculateProfit();

   for(int trade=OrdersTotal()-1; trade>=0; trade--)

     {

      if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))

         Print("Error");

      if(OrderSymbol()==Symbol())

        {

         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)

           {

            if(OrderType() == OP_BUY)

               if(!OrderClose(OrderTicket(), OrderLots(), Bid, 3, Blue))

                  Print("Error");

            if(OrderType() == OP_SELL)

               if(!OrderClose(OrderTicket(), OrderLots(), Ask, 3, Red))

                  Print("Error");

           }

         Sleep(1000);

         if(UseEquityStop)

           {

            if(CurrentPairProfit>0.0 && MathAbs(CurrentPairProfit)>TotalEquityRisk/100.0*AccountEquityHigh())

              {

               return;



              }

           }



        }

     }

  }

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

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

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

//----------------------------------------- TP_In_Money -----------------------------------------------

void Take_Profit_In_Money()

  {

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

//|                                                                  |

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

   if((TP_In_Money != 0))

     {

      PROFIT_SUM1 = 0;

      for(int i=OrdersTotal(); i>0; i--)

        {

         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

           {

            if(OrderSymbol()==Symbol())

              {

               if(OrderType() == OP_BUY || OrderType() == OP_SELL)

                 {

                  PROFIT_SUM1 = (PROFIT_SUM1 + OrderProfit());

                 }

              }

           }

        }

      if((PROFIT_SUM1 >= TP_In_Money))

        {

         RemoveAllOrders();

        }

     }

  }

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

//------------------------------------------------ TP_In_Percent -------------------------------------------------

double Take_Profit_In_percent()

  {

   if((TP_In_Percent != 0))

     {

      double TP_Percent = ((TP_In_Percent * AccountBalance()) / 100);

      double  PROFIT_SUM = 0;

      for(int i=OrdersTotal(); i>0; i--)

        {

         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

           {

            if(OrderSymbol()==Symbol())

              {

               if(OrderType() == OP_BUY || OrderType() == OP_SELL)

                 {

                  PROFIT_SUM = (PROFIT_SUM + OrderProfit());

                 }

              }

           }

         if(PROFIT_SUM >= TP_Percent)

           {

            RemoveAllOrders();

           }

        }



     }

   return(0);

  }

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

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

//       CLOSE &&  Remove  All    Orders

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

void RemoveAllOrders()

  {

   for(int i = OrdersTotal() - 1; i >= 0 ; i--)

     {

      if(!OrderSelect(i,SELECT_BY_POS))

         Print("ERROR");

      if(OrderSymbol() != Symbol())

         continue;

      double price = MarketInfo(OrderSymbol(),MODE_ASK);

      if(OrderType() == OP_BUY)

         price = MarketInfo(OrderSymbol(),MODE_BID);

      if(OrderType() == OP_BUY || OrderType() == OP_SELL)

        {

         if(!OrderClose(OrderTicket(), OrderLots(),price,5))

            Print("ERROR");

        }

      else

        {

         if(!OrderDelete(OrderTicket()))

            Print("ERROR");

        }

      Sleep(100);

      int error = GetLastError();

      // if(error > 0)

      // Print("Unanticipated error: ", ErrorDescription(error));

      RefreshRates();

     }

  }

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

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

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

//|                                                                  |

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

int TRAIL_PROFIT_IN_MONEY2()

  {

// double TP_Percent = ((TP_In_Money * AccountBalance()) / 100);

// double SL_Percent = ((SL_In_Money * AccountBalance()) / 100);

   PROFIT_SUM1 = 0;

   PROFIT_SUM2 = 0;

   INDEX2 = 0;

   double PROFIT_SUM3 = 0;

   for(int j=OrdersTotal(); j>0; j--)

     {

      if(OrderSelect(j,SELECT_BY_POS,MODE_TRADES))

        {

         if(OrderSymbol()==Symbol())

           {

            if(OrderType() == OP_BUY || OrderType() == OP_SELL)

              {

               PROFIT_SUM1  = PROFIT_SUM1 + (OrderProfit() + OrderCommission() + OrderSwap());

               // Print("PROFIT_SUM1",PROFIT_SUM1);

              }

           }

        }

     }

   if(PROFIT_SUM1>= Take_Profit_Money)

      // Print("PROFIT_SUM1",PROFIT_SUM1);

     {



      for(int i=OrdersTotal(); i>0; i--)

        {

         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

           {

            if(OrderSymbol()==Symbol())

              {



               if(OrderType() == OP_BUY || OrderType() == OP_SELL)





                 {

                  PROFIT_SUM2  = PROFIT_SUM2 + (OrderProfit() + OrderCommission() + OrderSwap());

                 }

               if(PROFIT_SUM1>= PROFIT_SUM3)

                 {PROFIT_SUM3=PROFIT_SUM1;}

               if(PROFIT_SUM2<=PROFIT_SUM3-Stop_Loss_Money)

                  RemoveAllOrders();

              }

           }

        }



     }

// if(PROFIT_SUM2<=SL_In_Money)

//  RemoveAllOrders();

   return(0);

  }

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

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

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---