//             P L E A S E   -   D O    N O T    D E L E T E    A N Y T H I N G ! ! !
// -------------------------------------------------------------------------------------------------
//                                   ROBODOZ3R v1.05
//
//                       				  	  by Rodolfo
//                             rodolfo.leonardo@gmail.com
//
//--------------------------------------------------------------------------------------------------
//   THIS EA IS 100 % FREE OPENSOURCE, WHICH MEANS THAT IT'S NOT A COMMERCIAL PRODUCT
// -------------------------------------------------------------------------------------------------

#property copyright " ROBODOZ3R.05 - rodolfo.leonardo@gmail.com"
#property link "https://goo.gl/6mXoPZ"
#property version "1.05"
#property description "ROBODOZ3R M1"
#property description "Strategy: When MM signal is purchased or sold engine 1 MACHX starts and  MM  and RSI signal  is purchased or sold engine 2 MACHX starts"
#property description "This EA is 100% FREE OpenSource "
#property description "Coder: rodolfo.leonardo@gmail.com "
#property strict

extern string Version__ = "-----------------------------------------------------------------";
extern string vg_versao = " ROBODOZ3R 2019-05-14 http://codepen4mql.minerasoft.com.br ";
extern string Version____ = "-----------------------------------------------------------------";
 
 
//Sensor STOP
 
extern string _SensorStop_ = "-----------------------------Sensor Stop --------------------";
extern bool   EnableEquityTarget_SensorStop   = false;     // closes all orders once Equity hits this $ amount and stop trades
extern int    EquityTarget_SensorStop     = 1500;           // closes all orders once Equity hits this $ amount and stop trades
extern bool   CloseAllNow_SensorStop      = false;          // closes all orders now and stop trades
extern bool   CloseProfitableTradesOnly_SensorStop = false; // closes only profitable trades and continue trade
extern double ProftableTradeAmount_SensorStop      = 1;     // Only trades above this amount close out
extern bool   ClosePendingOnly_SensorStop = false;          // closes pending orders only and continue trade
extern bool   EnabbleMaxDrawdownPercent_SensorStop = true;  // closes all trades once  DrawdownPercent and stop trades
extern double MaxDrawdownPercent_SensorStop = 10;            // Max  DrawdownPercent to stop trades
extern bool   EnabbleMinFreeMarging_SensorStop = true;      // Enable Min  Free Marging to trades hits this $ amount
extern double MinFreeMarging_SensorStop = 10;                 // Min  Free Marging to trades hits this $ amount
extern bool   UseAlerts_SensorStop        = false;

 
 double BalanceHigh_SensorStop;
 string AccSTOP_SensorStop;

void ReadBalanceHigh_SensorStop()
{
   if(GlobalVariableCheck("AccBalanceHigh_SensorStop"))
   {
      BalanceHigh_SensorStop = GlobalVariableGet("AccBalanceHigh_SensorStop");
   }
   else
   {
      BalanceHigh_SensorStop = AccountBalance();
      GlobalVariableSet("AccBalanceHigh_SensorStop",BalanceHigh_SensorStop);
   }
}

void WriteBalanceHigh_SensorStop()
{
   if(GlobalVariableSet("AccBalanceHigh_SensorStop",BalanceHigh_SensorStop)>0)
   {
      Print("New balance written to file: ", BalanceHigh_SensorStop);
   } 
   else Print("Error writing BalanceHigh: ",GetLastError());
}

//+------------------------------------------------------------------------+
//| Closes everything
//+------------------------------------------------------------------------+
void CloseAll_SensorStop(int a_magic_0)
{
  for(int i=OrdersTotal()-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
    bool result = false;
        if ( OrderType() == OP_BUY)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
        if ( OrderType() == OP_SELL)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
        if ( OrderType()== OP_BUYSTOP)  result = OrderDelete( OrderTicket() );
        if ( OrderType()== OP_SELLSTOP)  result = OrderDelete( OrderTicket() );
        if (UseAlerts_SensorStop) PlaySound("alert.wav");
 }
  return; 
}
   
//+------------------------------------------------------------------------+
//| cancels all orders that are in profit
//+------------------------------------------------------------------------+
void CloseAllinProfit_SensorStop(int a_magic_0)
{
  for(int i=OrdersTotal()-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
    bool result = false;
        if ( OrderType() == OP_BUY && OrderProfit()+OrderSwap()>ProftableTradeAmount_SensorStop)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
        if ( OrderType() == OP_SELL && OrderProfit()+OrderSwap()>ProftableTradeAmount_SensorStop)  result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
        if (UseAlerts_SensorStop) PlaySound("alert.wav");
 }
  return; 
}

//+------------------------------------------------------------------------+
//| cancels all pending orders 
//+------------------------------------------------------------------------+
void ClosePendingOrdersOnly_SensorStop(int a_magic_0)
{
  for(int i=OrdersTotal()-1;i>=0;i--)
 {
    OrderSelect(i, SELECT_BY_POS);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
    bool result = false;
        if ( OrderType()== OP_BUYSTOP)   result = OrderDelete( OrderTicket() );
        if ( OrderType()== OP_SELLSTOP)  result = OrderDelete( OrderTicket() );
  }
  return; 
  }

//+-----------+
//| Add in Main  (Start()) return to continue or not  trade  |
//+-----------+
bool  SensorStop_start(int a_magic_0)
  {
   int      OrdersBUY;
   int      OrdersSELL;
   double   BuyLots, SellLots, BuyProfit, SellProfit;

//+------------------------------------------------------------------+
//  Determine last order price                                       |
//-------------------------------------------------------------------+
      for(int i=0;i<OrdersTotal();i++)
      {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
           if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
           if(OrderType()==OP_BUY)  OrdersBUY++;
           if(OrderType()==OP_SELL) OrdersSELL++;
           if(OrderType()==OP_BUY)  BuyLots += OrderLots();
           if(OrderType()==OP_SELL) SellLots += OrderLots();
           if(OrderType() == OP_BUY)  BuyProfit += OrderProfit() + OrderCommission() + OrderSwap();
           if(OrderType() == OP_SELL)  SellProfit += OrderProfit() + OrderCommission() + OrderSwap();
      }               
   
    if(CloseAllNow_SensorStop) { CloseAll_SensorStop(a_magic_0);  return false;}
    
    if(CloseProfitableTradesOnly_SensorStop) { CloseAllinProfit_SensorStop(a_magic_0);   }
    
    if(EnableEquityTarget_SensorStop && AccountEquity() >= EquityTarget_SensorStop) { CloseAll_SensorStop(a_magic_0);   return false;}

    if(ClosePendingOnly_SensorStop) { ClosePendingOrdersOnly_SensorStop(a_magic_0);  }

    if(AccSTOP_SensorStop == "1")    return false;

    if(EnabbleMinFreeMarging_SensorStop && AccountFreeMargin() < MinFreeMarging_SensorStop )  {  CloseAll_SensorStop(a_magic_0);  return false;}
    
   if(EnabbleMaxDrawdownPercent_SensorStop){
        ReadBalanceHigh_SensorStop();
      
        // New balance high
        if(BalanceHigh_SensorStop < AccountBalance()) 
        {
            BalanceHigh_SensorStop = AccountBalance();
            WriteBalanceHigh_SensorStop();
        }
        
        if(BalanceHigh_SensorStop-AccountBalance() >= 0.01*MaxDrawdownPercent_SensorStop*BalanceHigh_SensorStop)
        {
            Print("EA Manager: Max drawdown reached!");
            CloseAll_SensorStop(a_magic_0); 
            AccSTOP_SensorStop = "1";
            return false;
        }
    }

    return true;
 }  

//SDK EAframework 

double MathRound(double x, double m) { return m * MathRound(x / m); }
double MathFloor(double x, double m) { return m * MathFloor(x / m); }
double MathCeil(double x, double m) { return m * MathCeil(x / m); }

//+------------------------------------------------------------------+
//|           CalculateProfit                                   |
//+------------------------------------------------------------------+
double CalculateProfit(int MagicNumber)
{
    double Profit = 0;
    for (int vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
            if (OrderType() == OP_BUY || OrderType() == OP_SELL)
                Profit += OrderProfit();
    }
    return (Profit);
}

//------------------------------------------------------------------------------------
// GetTimeFrame()
//------------------------------------------------------------------------------------
string GetTimeFrame(int timePeriod)
{
    string timeframe = "";
    switch (timePeriod)
    {
    case 1:
        timeframe = "M1";
        break;
    case 5:
        timeframe = "M5";
        break;
    case 15:
        timeframe = "M15";
        break;
    case 30:
        timeframe = "M30";
        break;
    case 60:
        timeframe = "H1";
        break;
    case 240:
        timeframe = "H4";
        break;
    case 1440:
        timeframe = "D1";
        break;
    case 10080:
        timeframe = "W1";
        break;
    }
    return timeframe;
}

//+------------------------------------------------------------------+
int OrdersScaner(int vMAGIC, int &orders_buy, int &orders_sell, double &profit, int &MinPriceBuy, int &MaxPriceSell, int &pending)
{

    orders_buy = 0;
    orders_sell = 0;
    profit = 0;
    MinPriceBuy = 0;
    MaxPriceSell = 0;
    pending = 0;
    for (int i = OrdersTotal(); i >= 1; i--)
    {
        if (OrderSelect(i - 1, SELECT_BY_POS, MODE_TRADES) == FALSE)
            break;
        if (OrderSymbol() != Symbol())
            continue;
        if (OrderMagicNumber() != vMAGIC)
            continue;
        if (OrderType() > 1)
            pending++;
        if (OrderType() == OP_BUY)
        {
            orders_buy++;
            if (orders_buy == 1)
                MinPriceBuy = OrderOpenPrice();
            if (orders_buy > 1 && OrderOpenPrice() < MinPriceBuy)
                MinPriceBuy = OrderOpenPrice();
            profit += OrderProfit() + OrderSwap();
        }
        if (OrderType() == OP_SELL)
        {
            orders_sell++;
            if (orders_sell == 1)
                MaxPriceSell = OrderOpenPrice();
            if (orders_sell > 1 && OrderOpenPrice() > MaxPriceSell)
                MaxPriceSell = OrderOpenPrice();
            profit += OrderProfit() + OrderSwap();
        }
    }
    int status = orders_buy + orders_sell;
    return (status);
}

//-----------------------------------------------------------------------------------
void SetHLine(color vColorSetHLine, string vNomeSetHLine = "", double vBidSetHLine = 0.0, int vStyleSetHLine = 0, int vTamanhoSetHLine = 1)
{
    if (vNomeSetHLine == "")
        vNomeSetHLine = DoubleToStr(Time[0], 0);
    if (vBidSetHLine <= 0.0)
        vBidSetHLine = Bid;
    if (ObjectFind(vNomeSetHLine) < 0)
        ObjectCreate(vNomeSetHLine, OBJ_HLINE, 0, 0, 0);
    ObjectSet(vNomeSetHLine, OBJPROP_PRICE1, vBidSetHLine);
    ObjectSet(vNomeSetHLine, OBJPROP_COLOR, vColorSetHLine);
    ObjectSet(vNomeSetHLine, OBJPROP_STYLE, vStyleSetHLine);
    ObjectSet(vNomeSetHLine, OBJPROP_WIDTH, vTamanhoSetHLine);
}

//+------------------------------------------------------------------+
//|           StopLong                                   |
//+------------------------------------------------------------------+
double StopLong(double price, int stop)
{
    if (stop == 0)
        return (0);
    else
        return (price - stop * Point);
}

//+------------------------------------------------------------------+
//|           StopShort                                   |
//+------------------------------------------------------------------+
double StopShort(double price, int stop)
{
    if (stop == 0)
        return (0);
    else
        return (price + stop * Point);
}

//+------------------------------------------------------------------+
//|           TakeLong                                   |
//+------------------------------------------------------------------+
double TakeLong(double price, int stop)
{
    if (stop == 0)
        return (0);
    else
        return (price + stop * Point);
}

//+------------------------------------------------------------------+
//|           TakeShort                                   |
//+------------------------------------------------------------------+
double TakeShort(double price, int stop)
{
    if (stop == 0)
        return (0);
    else
        return (price - stop * Point);
}

//+------------------------------------------------------------------+
//|           CalculateProfit                                   |
//+------------------------------------------------------------------+
double CalculateProfit(int MagicNumber, int &vg_cnt)
{
    double Profit = 0;
    for (vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
            if (OrderType() == OP_BUY || OrderType() == OP_SELL)
                Profit += OrderProfit() + OrderCommission() + OrderSwap();
    }
    return (Profit);
}
//+------------------------------------------------------------------+
//|           TrailingAlls                                   |
//+------------------------------------------------------------------+
void TrailingAlls(int pType, int stop, double AvgPrice, int MagicNumber)
{
    double profit;
    double stoptrade;
    double stopcal;
    if (stop != 0)
    {
        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)
                    {
                        profit = NormalizeDouble((Bid - AvgPrice) / Point, 0);
                        if (profit < pType)
                            continue;
                        stoptrade = OrderStopLoss();
                        stopcal = Bid - stop * Point;
                        if (stoptrade == 0.0 || (stoptrade != 0.0 && stopcal > stoptrade))
                            OrderModify(OrderTicket(), AvgPrice, stopcal, OrderTakeProfit(), 0, Aqua);
                    }
                    if (OrderType() == OP_SELL)
                    {
                        profit = NormalizeDouble((AvgPrice - Ask) / Point, 0);
                        if (profit < pType)
                            continue;
                        stoptrade = OrderStopLoss();
                        stopcal = Ask + stop * Point;
                        if (stoptrade == 0.0 || (stoptrade != 0.0 && stopcal < stoptrade))
                            OrderModify(OrderTicket(), AvgPrice, stopcal, OrderTakeProfit(), 0, Red);
                    }
                }
                Sleep(1000);
            }
        }
    }
}

//+------------------------------------------------------------------+
//|           CountTrades                                   |
//+------------------------------------------------------------------+
int CountTrades(int MagicNumber)
{
    int count = 0;
    for (int trade = OrdersTotal() - 1; trade >= 0; trade--)
    {
        OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
            if (OrderType() == OP_SELL || OrderType() == OP_BUY)
                count++;
    }
    return (count);
}
//+------------------------------------------------------------------+
//|           CloseAllTicket                                   |
//+------------------------------------------------------------------+
void CloseAllTicket(int aType, int ticket, int MagicN, int pSlipPage)
{
    for (int i = OrdersTotal() - 1; i >= 0; i--)
        if (OrderSelect(i, SELECT_BY_POS))
            if (OrderSymbol() == Symbol())
                if (OrderMagicNumber() == MagicN)
                {
                    if (OrderType() == aType && OrderType() == OP_BUY)
                        if (OrderProfit() > 0 || OrderTicket() == ticket)
                            if (!OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits()), pSlipPage, clrRed))
                                Print(" OrderClose OP_BUY Error N", GetLastError());

                    if (OrderType() == aType && OrderType() == OP_SELL)
                        if (OrderProfit() > 0 || OrderTicket() == ticket)
                            if (!OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits()), pSlipPage, clrRed))
                                Print(" OrderClose OP_SELL Error N", GetLastError());
                }
}
//+------------------------------------------------------------------+
//|           CloseThisSymbolAll                                   |
//+------------------------------------------------------------------+
void CloseThisSymbolAll(int MagicNumber, int InpSlip)
{
    for (int trade = OrdersTotal() - 1; trade >= 0; trade--)
    {
        OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() == Symbol())
        {
            if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
            {
                if (OrderType() == OP_BUY)
                    OrderClose(OrderTicket(), OrderLots(), Bid, InpSlip, Blue);
                if (OrderType() == OP_SELL)
                    OrderClose(OrderTicket(), OrderLots(), Ask, InpSlip, Red);
            }
            Sleep(1000);
        }
    }
}

//+------------------------------------------------------------------+
//|           AccountEquityHigh                       |
//+------------------------------------------------------------------+
double AccountEquityHigh(int MagicNumber, double vg_AccountEquityHighAmt, double vg_PrevEquity)
{
    if (CountTrades(MagicNumber) == 0)
        vg_AccountEquityHighAmt = AccountEquity();
    if (vg_AccountEquityHighAmt < vg_PrevEquity)
        vg_AccountEquityHighAmt = vg_PrevEquity;
    else
        vg_AccountEquityHighAmt = AccountEquity();
    vg_PrevEquity = AccountEquity();
    return (vg_AccountEquityHighAmt);
}

//+------------------------------------------------------------------+
//|           FindLastBuyPrice                                     |
//+------------------------------------------------------------------+
double FindLastBuyPrice(int MagicNumber, double &v_sumLots)
{

    v_sumLots = 0;
    double oldorderopenprice=0;
    int oldticketnumber=0;
    double unused = 0;
    int ticketnumber = 0;
    for (int vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderType() == OP_BUY)
        {
            oldticketnumber = OrderTicket();
            if (oldticketnumber > ticketnumber)
            {
                oldorderopenprice = OrderOpenPrice();
                //unused = oldorderopenprice;
                v_sumLots += OrderLots();
                ticketnumber = oldticketnumber;
            }
        }
    }
    return (oldorderopenprice);
}

//+------------------------------------------------------------------+
//|           FindLastBuyPrice                                     |
//+------------------------------------------------------------------+
double FindLastBuyPriceLL(int MagicNumber, double &v_sumLots, double &v_lastLots)
{

    v_sumLots = 0;
    double oldorderopenprice =0;
    int oldticketnumber =0;
    double unused = 0;
    int ticketnumber = 0;
    for (int vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderType() == OP_BUY)
        {
            oldticketnumber = OrderTicket();
            if (oldticketnumber > ticketnumber)
            {
                oldorderopenprice = OrderOpenPrice();
                //unused = oldorderopenprice;
                v_sumLots += OrderLots();
                v_lastLots = OrderLots();
                ticketnumber = oldticketnumber;
            }
        }
    }
    return (oldorderopenprice);
}

//+------------------------------------------------------------------+
//|           FindLastSellPrice                                     |
//+------------------------------------------------------------------+
double FindLastSellPriceLL(int MagicNumber, double &v_sumLots, double &v_lastLots)
{

    v_sumLots = 0;
    double oldorderopenprice=0;
    int oldticketnumber=0;
    double unused = 0;
    int ticketnumber = 0;
    for (int vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderType() == OP_SELL)
        {
            oldticketnumber = OrderTicket();
            if (oldticketnumber > ticketnumber)
            {
                oldorderopenprice = OrderOpenPrice();
                //unused = oldorderopenprice;
                v_sumLots += OrderLots();
                v_lastLots = OrderLots();
                ticketnumber = oldticketnumber;
            }
        }
    }
    return (oldorderopenprice);
}
//+------------------------------------------------------------------+
//|           OpenOrder                                   |
//+------------------------------------------------------------------+
int OpenOrder(int pType, double pLots, double pLevel, int sp, double pr, int sl, int tp, string pComment, int pMagic, int pDatetime, color pColor)
{
    int ticket = 0;
    int err = 0;
    int c = 0;
    int NumberOfTries = 100;
    switch (pType)
    {
    case 2:
        for (c = 0; c < NumberOfTries; c++)
        {
            ticket = OrderSend(Symbol(), OP_BUYLIMIT, pLots, pLevel, sp, StopLong(pr, sl), TakeLong(pLevel, tp), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("BUYLIMIT " + Symbol() + ", BuyLimit, " + DoubleToStr(pLevel, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(1000);
        }
        break;
    case 4:
        for (c = 0; c < NumberOfTries; c++)
        {
            ticket = OrderSend(Symbol(), OP_BUYSTOP, pLots, pLevel, sp, StopLong(pr, sl), TakeLong(pLevel, tp), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("BUYSTOP " + Symbol() + ", BuyStop, " + DoubleToStr(pLevel, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(5000);
        }
        break;
    case 0:
        for (c = 0; c < NumberOfTries; c++)
        {
            RefreshRates();
            ticket = OrderSend(Symbol(), OP_BUY, pLots, NormalizeDouble(Ask, Digits), sp, NormalizeDouble(StopLong(Bid, sl), Digits), NormalizeDouble(TakeLong(Ask, tp), Digits), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("BuyOrder: " + Symbol() + ", Buy, " + DoubleToStr(Ask, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(5000);
        }
        break;
    case 3:
        for (c = 0; c < NumberOfTries; c++)
        {
            ticket = OrderSend(Symbol(), OP_SELLLIMIT, pLots, pLevel, sp, StopShort(pr, sl), TakeShort(pLevel, tp), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("SELLLIMIT " + Symbol() + ", SellLimit, " + DoubleToStr(pLevel, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(5000);
        }
        break;
    case 5:
        for (c = 0; c < NumberOfTries; c++)
        {
            ticket = OrderSend(Symbol(), OP_SELLSTOP, pLots, pLevel, sp, StopShort(pr, sl), TakeShort(pLevel, tp), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("SELLSTOP " + Symbol() + ", SellStop, " + DoubleToStr(pLevel, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(5000);
        }
        break;
    case 1:
        for (c = 0; c < NumberOfTries; c++)
        {
            ticket = OrderSend(Symbol(), OP_SELL, pLots, NormalizeDouble(Bid, Digits), sp, NormalizeDouble(StopShort(Ask, sl), Digits), NormalizeDouble(TakeShort(Bid, tp), Digits), pComment, pMagic, pDatetime, pColor);
            err = GetLastError();
            if (err == 0 /* NO_ERROR */)
            {
                SendNotification("SELL " + Symbol() + ", Sell, " + DoubleToStr(Bid, Digits) + ", " + DoubleToStr(pLots, 2));
                break;
            }
            if (!(err == 4 /* SERVER_BUSY */ || err == 137 /* BROKER_BUSY */ || err == 146 /* TRADE_CONTEXT_BUSY */ || err == 136 /* OFF_QUOTES */))
                break;
            Sleep(5000);
        }
    }
    return (ticket);
}
//+------------------------------------------------------------------+
//|           FindLastSellPrice                                     |
//+------------------------------------------------------------------+
double FindLastSellPrice(int MagicNumber, double &v_sumLots)
{
    v_sumLots = 0;
    double oldorderopenprice=0;
    int oldticketnumber;
    double unused = 0;
    int ticketnumber = 0;
    for (int vg_cnt = OrdersTotal() - 1; vg_cnt >= 0; vg_cnt--)
    {
        OrderSelect(vg_cnt, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber)
            continue;
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderType() == OP_SELL)
        {
            oldticketnumber = OrderTicket();
            if (oldticketnumber > ticketnumber)
            {
                oldorderopenprice = OrderOpenPrice();
                //unused = oldorderopenprice;
                v_sumLots += OrderLots();
                ticketnumber = oldticketnumber;
            }
        }
    }
    return (oldorderopenprice);
}
void PainelUPER(string textpainel)
{
    string Ygs_104 = "A";
    string name_0 = Ygs_104 + "L_1";
    if (ObjectFind(name_0) == -1)
    {
        ObjectCreate(name_0, OBJ_LABEL, 0, 0, 0);
        ObjectSet(name_0, OBJPROP_CORNER, 0);
        ObjectSet(name_0, OBJPROP_XDISTANCE, 300);
        ObjectSet(name_0, OBJPROP_YDISTANCE, 10);
    }
    ObjectSetText(name_0, textpainel, 12, "Arial", White);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum ENUM_TYPE_GRID_LOT
{
    fix_lot = 0,        // Fixed Start Lot 0.01 / 0.01 / 0.01 / 0.01 / 0.01 /.............
    Summ_lot = 1,       // Summ Sart Lot   0.01 / 0.02 / 0.03 / 0.04 / 0.05 /.............
    Martingale = 2,     // Martingale Lot  0.01 / 0.02 / 0.04 / 0.08 / 0.16 /.............
    Step_lot = 3,       // Step Lot        0.01 / 0.01 / 0.01 / 0.02 / 0.02 / 0.02 / 0.03 / 0.03 / 0.03 / 0.04 / 0.04 / 0.04 /............
    Step_Invert_lot = 4 // Step Invert Lot        0.10 / 0.10 / 0.10 / 0.09 / 0.09 / 0.09 / 0.08 / 0.08 / 0.08 / 0.08 / 0.08 / 0.07 /............
};

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum ENUM_Trade
{
    Only_BUY,  // Only BUY
    Only_SELL, // Only SELL
    All_Trade  // BUY and SELL
};

double CalcLot(int TypeLot, int TypeOrder, int vQtdTrades, double LastLot, double StartLot, double GridFactor, int GridStepLot, double StepLot)
{
    double rezult = 0;
    switch (TypeLot)
    {
    case 0: // Standart lot
        if (TypeOrder == OP_BUY || TypeOrder == OP_SELL)
            rezult = StartLot;
        break;

    case 1: // Summ lot
        rezult = StartLot * vQtdTrades;

        break;

    case 2: // Martingale lot
        rezult = StartLot * MathPow(GridFactor, vQtdTrades);

        break;

    case 3: // Step lot
        if (vQtdTrades == 0)
            return StartLot;
        if (vQtdTrades % GridStepLot == 0)
            rezult = LastLot + StepLot;
        else
            rezult = LastLot;

        break;
    case 4: // Step Invert lot
        if (vQtdTrades == 0)
            return StartLot;
        if (vQtdTrades % GridStepLot == 0)
            rezult = LastLot - StepLot;
        else
            rezult = LastLot;

        break;
    }
    return rezult;
}

// add leading zeros that the resulting string has 'digits' length.
string sub_maketimestring(int par_number, int par_digits)
{
    string result;

    result = DoubleToStr(par_number, 0);
    while (StringLen(result) < par_digits)
        result = "0" + result;

    return (result);
}

// Make a screenshoot / printscreen
void sub_makescreenshot(string par_sx = "")
{
    static int no = 0;

    no++;
    string fn = "SnapShot" + Symbol() + Period() + "\\" + Year() + "-" + sub_maketimestring(Month(), 2) + "-" + sub_maketimestring(Day(), 2) + " " + sub_maketimestring(Hour(), 2) + "_" + sub_maketimestring(Minute(), 2) + "_" + sub_maketimestring(Seconds(), 2) + " " + no + par_sx + ".gif";
    if (!ScreenShot(fn, 640, 480))
        Print("ScreenShot error: ", GetLastError());
}

void DrawRects(int xPos, int yPos, color clr, int width = 150, int height = 17, string Texto = "")
{

    string id = "_l" + Texto;

    ObjectDelete(0, id);

    ObjectCreate(0, id, OBJ_BUTTON, 0, 100, 100);
    ObjectSetInteger(0, id, OBJPROP_XDISTANCE, xPos);
    ObjectSetInteger(0, id, OBJPROP_YDISTANCE, yPos);
    ObjectSetInteger(0, id, OBJPROP_BGCOLOR, clr);
    ObjectSetInteger(0, id, OBJPROP_COLOR, clrWhite);
    ObjectSetInteger(0, id, OBJPROP_XSIZE, 150);
    ObjectSetInteger(0, id, OBJPROP_YSIZE, 35);

    ObjectSetInteger(0, id, OBJPROP_WIDTH, 0);
    ObjectSetString(0, id, OBJPROP_FONT, "Arial");
    ObjectSetString(0, id, OBJPROP_TEXT, Texto);
    ObjectSetInteger(0, id, OBJPROP_SELECTABLE, 0);
    ObjectSetInteger(0, id, OBJPROP_STATE, false);
}

//--------------------------------------------------------------------
bool ButtonCreate(const long chart_ID = 0,           // ID ãðàôèêà
                  const string name = "Button",      // èìÿ êíîïêè
                  const int sub_window = 0,          // íîìåð ïîäîêíà
                  const long x = 0,                  // êîîðäèíàòà ïî îñè X
                  const long y = 0,                  // êîîðäèíàòà ïî îñè Y
                  const int width = 50,              // øèðèíà êíîïêè
                  const int height = 18,             // âûñîòà êíîïêè
                  const string text = "Button",      // òåêñò
                  const string font = "Arial",       // øðèôò
                  const int font_size = 8,           // ðàçìåð øðèôòà
                  const color clr = clrBlack,        // öâåò òåêñòà
                  const color clrON = clrLightGray,  // öâåò ôîíà
                  const color clrOFF = clrLightGray, // öâåò ôîíà
                  const color border_clr = clrNONE,  // öâåò ãðàíèöû
                  const bool state = false,          //
                  const ENUM_BASE_CORNER CORNER = CORNER_RIGHT_UPPER)
{
    if (ObjectFind(chart_ID, name) == -1)
    {
        ObjectCreate(chart_ID, name, OBJ_BUTTON, sub_window, 0, 0);
        ObjectSetInteger(chart_ID, name, OBJPROP_XSIZE, width);
        ObjectSetInteger(chart_ID, name, OBJPROP_YSIZE, height);
        ObjectSetInteger(chart_ID, name, OBJPROP_CORNER, CORNER);
        ObjectSetString(chart_ID, name, OBJPROP_FONT, font);
        ObjectSetInteger(chart_ID, name, OBJPROP_FONTSIZE, font_size);
        ObjectSetInteger(chart_ID, name, OBJPROP_BACK, 0);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTABLE, 0);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTED, 0);
        ObjectSetInteger(chart_ID, name, OBJPROP_HIDDEN, 1);
        ObjectSetInteger(chart_ID, name, OBJPROP_ZORDER, 1);
        ObjectSetInteger(chart_ID, name, OBJPROP_STATE, state);
    }
    ObjectSetInteger(chart_ID, name, OBJPROP_BORDER_COLOR, border_clr);
    color back_clr;
    if (ObjectGetInteger(chart_ID, name, OBJPROP_STATE))
        back_clr = clrON;
    else
        back_clr = clrOFF;
    ObjectSetInteger(chart_ID, name, OBJPROP_BGCOLOR, back_clr);
    ObjectSetInteger(chart_ID, name, OBJPROP_COLOR, clr);
    ObjectSetString(chart_ID, name, OBJPROP_TEXT, text);
    ObjectSetInteger(chart_ID, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(chart_ID, name, OBJPROP_YDISTANCE, y);
    return (true);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawLABEL(int c, string name, string Name, int X, int Y, color clr)
{
    if (ObjectFind(name) == -1)
    {
        ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
        ObjectSet(name, OBJPROP_CORNER, c);
        ObjectSet(name, OBJPROP_XDISTANCE, X);
        ObjectSet(name, OBJPROP_YDISTANCE, Y);
        ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
        ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
    }
    ObjectSetText(name, Name, 10, "Arial", clr);
}

//--------------------------------------------------------------------
bool RectLabelCreate(const long chart_ID = 0,                   // ID ãðàôèêà
                     const string name = "RectLabel",           // èìÿ ìåòêè
                     const int sub_window = 0,                  // íîìåð ïîäîêíà
                     const long x = 0,                          // êîîðäèíàòà ïî îñè X
                     const long y = 0,                          // êîîðäèíàòà ïî îñè y
                     const int width = 50,                      // øèðèíà
                     const int height = 18,                     // âûñîòà
                     const color back_clr = clrWhite,           // öâåò ôîíà
                     const color clr = clrBlack,                // öâåò ïëîñêîé ãðàíèöû (Flat)
                     const ENUM_LINE_STYLE style = STYLE_SOLID, // ñòèëü ïëîñêîé ãðàíèöû
                     const int line_width = 1,                  // òîëùèíà ïëîñêîé ãðàíèöû
                     const bool back = false,                   // íà çàäíåì ïëàíå
                     const bool selection = false,              // âûäåëèòü äëÿ ïåðåìåùåíèé
                     const bool hidden = true,                  // ñêðûò â ñïèñêå îáúåêòîâ
                     const long z_order = 0)                    // ïðèîðèòåò íà íàæàòèå ìûøüþ
{
    ResetLastError();
    if (ObjectFind(chart_ID, name) == -1)
    {
        ObjectCreate(chart_ID, name, OBJ_RECTANGLE_LABEL, sub_window, 0, 0);
        ObjectSetInteger(chart_ID, name, OBJPROP_BORDER_TYPE, BORDER_FLAT);
        ObjectSetInteger(chart_ID, name, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
        ObjectSetInteger(chart_ID, name, OBJPROP_STYLE, style);
        ObjectSetInteger(chart_ID, name, OBJPROP_WIDTH, line_width);
        ObjectSetInteger(chart_ID, name, OBJPROP_BACK, back);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTABLE, selection);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTED, selection);
        ObjectSetInteger(chart_ID, name, OBJPROP_HIDDEN, hidden);
        ObjectSetInteger(chart_ID, name, OBJPROP_ZORDER, z_order);
        //ObjectSetInteger(chart_ID,name,OBJPROP_ALIGN,ALIGN_RIGHT);
    }
    ObjectSetInteger(chart_ID, name, OBJPROP_BGCOLOR, back_clr);
    ObjectSetInteger(chart_ID, name, OBJPROP_COLOR, clr);
    ObjectSetInteger(chart_ID, name, OBJPROP_XSIZE, width);
    ObjectSetInteger(chart_ID, name, OBJPROP_YSIZE, height);
    ObjectSetInteger(chart_ID, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(chart_ID, name, OBJPROP_YDISTANCE, y);
    return (true);
}
//--------------------------------------------------------------------
bool LabelCreate(const long chart_ID = 0,                           // ID �������
                 const string name = "Label",                       // ��� �����
                 const int sub_window = 0,                          // ����� �������
                 const long x = 0,                                  // ���������� �� ��� X
                 const long y = 0,                                  // ���������� �� ��� y
                 const ENUM_BASE_CORNER corner = CORNER_LEFT_UPPER, // ���� ������� ��� ��������
                 const string text = "Label",                       // �����
                 const string font = "Arial",                       // �����
                 const int font_size = 10,                          // ������ ������
                 const color clr = clrNONE,
                 const double angle = 0.0,                           // ������ ������
                 const ENUM_ANCHOR_POINT anchor = ANCHOR_LEFT_UPPER, // ������ ��������
                 const bool back = false,                            // �� ������ �����
                 const bool selection = false,                       // �������� ��� �����������
                 const bool hidden = true,                           // ����� � ������ ��������
                 const long z_order = 0)                             // ��������� �� ������� �����
{
    ResetLastError();
    if (ObjectFind(chart_ID, name) == -1)
    {
        if (!ObjectCreate(chart_ID, name, OBJ_LABEL, sub_window, 0, 0))
        {
            Print(__FUNCTION__, ": �� ������� ������� ��������� �����! ��� ������ = ", GetLastError());
            return (false);
        }
        ObjectSetInteger(chart_ID, name, OBJPROP_CORNER, corner);
        ObjectSetString(chart_ID, name, OBJPROP_FONT, font);
        ObjectSetInteger(chart_ID, name, OBJPROP_FONTSIZE, font_size);
        ObjectSetDouble(chart_ID, name, OBJPROP_ANGLE, angle);
        ObjectSetInteger(chart_ID, name, OBJPROP_ANCHOR, anchor);
        ObjectSetInteger(chart_ID, name, OBJPROP_BACK, back);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTABLE, selection);
        ObjectSetInteger(chart_ID, name, OBJPROP_SELECTED, selection);
        ObjectSetInteger(chart_ID, name, OBJPROP_HIDDEN, hidden);
        ObjectSetInteger(chart_ID, name, OBJPROP_ZORDER, z_order);
    }
    ObjectSetInteger(chart_ID, name, OBJPROP_COLOR, clr);
    ObjectSetInteger(chart_ID, name, OBJPROP_XDISTANCE, x);
    ObjectSetInteger(chart_ID, name, OBJPROP_YDISTANCE, y);
    ObjectSetString(chart_ID, name, OBJPROP_TEXT, text);
    return (true);
}

double ValidStopLoss(int type, double price, double SL)
{

    double mySL;
    double minstop;

    minstop = MarketInfo(Symbol(), MODE_STOPLEVEL);
    if (Digits == 3 || Digits == 5)
        minstop = minstop / 10;

    mySL = SL;
    if (type == OP_BUY)
    {
        if ((price - mySL) < minstop * Point)
            mySL = price - minstop * Point;
    }
    if (type == OP_SELL)
    {
        if ((mySL - price) < minstop * Point)
            mySL = price + minstop * Point;
    }

    return (NormalizeDouble(mySL, MarketInfo(Symbol(), MODE_DIGITS)));
}

int CountBuys(int a_magic_0)
{
    int l_count_4 = 0;
    int l_ord_total_12 = OrdersTotal();
    for (int l_pos_8 = 0; l_pos_8 < l_ord_total_12; l_pos_8++)
    {
        OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        if (OrderType() == OP_BUY)
            l_count_4++;
    }
    return (l_count_4);
}

int CountSells(int a_magic_0)
{
    int l_count_4 = 0;
    int l_ord_total_12 = OrdersTotal();
    for (int l_pos_8 = 0; l_pos_8 < l_ord_total_12; l_pos_8++)
    {
        OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        if (OrderType() == OP_SELL)
            l_count_4++;
    }
    return (l_count_4);
}

int CountBuyLimit(int a_magic_0)
{
    int li_ret_4=0;
    for (int l_pos_8 = 0; l_pos_8 < OrdersTotal(); l_pos_8++)
    {
        OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() == Symbol() && OrderType() == OP_BUYLIMIT && OrderMagicNumber() == a_magic_0)
            li_ret_4++;
    }
    return (li_ret_4);
}

int CountSellLimit(int a_magic_0)
{
    int li_ret_4=0;
    for (int l_pos_8 = 0; l_pos_8 < OrdersTotal(); l_pos_8++)
    {
        OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() == Symbol() && OrderType() == OP_SELLLIMIT && OrderMagicNumber() == a_magic_0)
            li_ret_4++;
    }
    return (li_ret_4);
}

double LastBuyLot(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_lots_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && (OrderType() == OP_BUY || OrderType() == OP_BUYLIMIT) && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_lots_16 = OrderLots();
        }
    }
    return (l_ord_lots_16);
}

double LastSellLot(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_lots_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && (OrderType() == OP_SELL || OrderType() == OP_SELLLIMIT) && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_lots_16 = OrderLots();
        }
    }
    return (l_ord_lots_16);
}

double LastBuyLimLot(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_lots_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_BUYLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_lots_16 = OrderLots();
        }
    }
    return (l_ord_lots_16);
}

double LastSellLimLot(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_lots_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_SELLLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_lots_16 = OrderLots();
        }
    }
    return (l_ord_lots_16);
}

string LastComm(int a_magic_0)
{
    int l_hist_total_4 = OrdersHistoryTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    string ls_ret_16 = "0";
    for (int l_pos_24 = 0; l_pos_24 < l_hist_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_HISTORY);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderCloseTime();
        if (l_datetime_8 > l_datetime_12 && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            ls_ret_16 = OrderComment();
        }
    }
    return (ls_ret_16);
}

double BuyProfit(int a_magic_0)
{
    double ld_ret_4 = 0;
    for (int l_pos_12 = 0; l_pos_12 < OrdersTotal(); l_pos_12++)
    {
        OrderSelect(l_pos_12, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == a_magic_0)
            if (OrderType() == OP_BUY)
                ld_ret_4 += OrderProfit() + OrderCommission() + OrderSwap();
    }
    return (ld_ret_4);
}

double SellProfit(int a_magic_0)
{
    double ld_ret_4 = 0;
    for (int l_pos_12 = 0; l_pos_12 < OrdersTotal(); l_pos_12++)
    {
        OrderSelect(l_pos_12, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == a_magic_0)
            if (OrderType() == OP_SELL)
                ld_ret_4 += OrderProfit() + OrderCommission() + OrderSwap();
    }
    return (ld_ret_4);
}

double LastBSPrice(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_open_price_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_BUYLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_open_price_16 = OrderOpenPrice();
        }
    }
    return (l_ord_open_price_16);
}

double LastSSPrice(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_open_price_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_SELLLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_open_price_16 = OrderOpenPrice();
        }
    }
    return (l_ord_open_price_16);
}

int LastBSTime(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    int l_datetime_16 = 0;
    for (int l_pos_20 = 0; l_pos_20 < l_ord_total_4; l_pos_20++)
    {
        OrderSelect(l_pos_20, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_BUYLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_datetime_16 = OrderOpenTime();
        }
    }
    return (l_datetime_16);
}

int LastSSTime(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    int l_datetime_16 = 0;
    for (int l_pos_20 = 0; l_pos_20 < l_ord_total_4; l_pos_20++)
    {
        OrderSelect(l_pos_20, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;

        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_SELLLIMIT && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_datetime_16 = OrderOpenTime();
        }
    }
    return (l_datetime_16);
}

double LastBuyPrice(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_open_price_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_BUY && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_open_price_16 = OrderOpenPrice();
        }
    }
    return (l_ord_open_price_16);
}
int Counts(int a_magic_0, int &l_count_buy, int &l_count_sell, int &l_count_selllimit,
           int &l_count_buylimit, double &l_profit_buy, double &l_profit_sell,
           double &l_last_lots_Buy, double &l_last_lots_Sell, double &l_last_lots_BuyLimit,
           double &l_last_lots_SellLimit, double &l_last_open_price_Buy, double &l_last_open_price_Sell,
           double &l_last_open_price_BuyLimit, double &l_last_open_price_SellLimit,
           int & l_datetime_ord_lots_BuyLimit, int& l_datetime_ord_lots_SellLimit, double & m_mediaprice)
{

    int l_ord_total_12 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_ord_lots_Buy = 0;
    int l_datetime_ord_lots_Sell = 0;
   // int l_datetime_ord_lots_BuyLimit = 0;
   // int l_datetime_ord_lots_SellLimit = 0;

    for (int l_pos_8 = 0; l_pos_8 < l_ord_total_12; l_pos_8++)
    {
        OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != a_magic_0)
            continue;

        l_datetime_8 = OrderOpenTime();

        if (l_datetime_8 > l_datetime_ord_lots_BuyLimit && OrderType() == OP_BUYLIMIT)
        {
            l_datetime_ord_lots_BuyLimit = l_datetime_8;
            l_last_lots_BuyLimit = OrderLots();
        }

        if (l_datetime_8 > l_datetime_ord_lots_SellLimit && OrderType() == OP_SELLLIMIT)
        {
            l_datetime_ord_lots_SellLimit = l_datetime_8;
            l_last_lots_SellLimit = OrderLots();
        }

        if (l_datetime_8 > l_datetime_ord_lots_Buy && (OrderType() == OP_BUY || OrderType() == OP_BUYLIMIT))
        {
            l_datetime_ord_lots_Buy = l_datetime_8;
            l_last_lots_Buy = OrderLots();

            if (OrderType() == OP_BUY)
                l_last_open_price_Buy = OrderOpenPrice();

            if (OrderType() == OP_BUYLIMIT)
                l_last_open_price_BuyLimit = OrderOpenPrice();
        }

        if (l_datetime_8 > l_datetime_ord_lots_Sell && (OrderType() == OP_SELL || OrderType() == OP_SELLLIMIT))
        {
            l_datetime_ord_lots_Sell = l_datetime_8;
            l_last_lots_Sell = OrderLots();

            if (OrderType() == OP_SELL)
                l_last_open_price_Sell = OrderOpenPrice();

            if (OrderType() == OP_SELLLIMIT)
                l_last_open_price_SellLimit = OrderOpenPrice();
        }

        if (OrderType() == OP_BUY)
        {
            l_profit_buy += OrderProfit() + OrderCommission() + OrderSwap();
            m_mediaprice += OrderOpenPrice() * OrderLots();
            l_count_buy++;
        }
        if (OrderType() == OP_SELL)
        {
            l_profit_sell += OrderProfit() + OrderCommission() + OrderSwap();
            m_mediaprice += OrderOpenPrice() * OrderLots();
            l_count_sell++;
        }
        if (OrderType() == OP_SELLLIMIT)
            l_count_selllimit++;
        if (OrderType() == OP_BUYLIMIT)
            l_count_buylimit++;
    }

    return (l_ord_total_12);
}

double LastSellPrice(int a_magic_0)
{
    int l_ord_total_4 = OrdersTotal();
    int l_datetime_8 = 0;
    int l_datetime_12 = 0;
    double l_ord_open_price_16 = 0;
    for (int l_pos_24 = 0; l_pos_24 < l_ord_total_4; l_pos_24++)
    {
        OrderSelect(l_pos_24, SELECT_BY_POS, MODE_TRADES);
        l_datetime_8 = OrderOpenTime();
        if (l_datetime_8 > l_datetime_12 && OrderType() == OP_SELL && OrderMagicNumber() == a_magic_0)
        {
            l_datetime_12 = l_datetime_8;
            l_ord_open_price_16 = OrderOpenPrice();
        }
    }
    return (l_ord_open_price_16);
}


double FindFirstOrderTickets(int magic, string Symb, int Type, int QtdProfit, int &tickets[])
{
  int Ticket = 0;
  double profit = 0;
  datetime EarliestOrder = D'2099/12/31';
  int c = 0;
  double ordprofit[100];
  for (int i = 0; i < OrdersTotal(); i++)
  {
    if (OrderSelect(i, SELECT_BY_POS))
    {
      if (OrderType() == Type && OrderSymbol() == Symb && OrderMagicNumber() == magic)
      {
        if (EarliestOrder > OrderOpenTime())
        {
          EarliestOrder = OrderOpenTime();
          Ticket = OrderTicket();
          profit = OrderProfit() + OrderCommission() + OrderSwap();
          
          tickets[c] = Ticket;
          ordprofit[c] = profit;
          c++;
        }
      }
    }
  }

   for (int t = 0; t < QtdProfit; t++)
    {
      profit += ordprofit[t];
    }

  return profit; // Returns 0 if no matching orders
}
void Draw_RectangleLabel(string objEA,color color_InfoPanel,int xArea,int yArea,int width,int height,ENUM_BASE_CORNER InpCorner)
  {
//--- define rectangle label coordinates 
   int InpX=xArea;
   int InpY=yArea;

   string InpName=objEA+"RectangleWL";
   color InpBackColor=color_InfoPanel;

   ENUM_BORDER_TYPE InpBorder=BORDER_SUNKEN;
//ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER;
//color InpColor=clrBisque;
   color InpColor=clrBlack;
   ENUM_LINE_STYLE InpStyle=STYLE_SOLID;
   int InpLineWidth=1;
   bool InpBack=false;
   bool InpSelection=false;          // Highlight to move
   bool InpHidden=false;
   long InpZOrder=0;

//--- create a rectangle label 
   if(!RectLabelCreate(0,InpName,0,InpX,InpY,width,height,InpBackColor,InpBorder,InpCorner,
      InpColor,InpStyle,InpLineWidth,InpBack,InpSelection,InpHidden,InpZOrder))
     {
      return;
     }
  }
//+------------------------------------------------------------------+ 
//| Create rectangle label                                           | 
//+------------------------------------------------------------------+ 
bool RectLabelCreate(const long             chart_ID=0,               // chart's ID 
                     const string           name="RectLabel",         // label name 
                     const int              sub_window=0,             // subwindow index 
                     const int              x=0,                      // X coordinate 
                     const int              y=0,                      // Y coordinate 
                     const int              width=50,                 // width 
                     const int              height=18,                // height 
                     const color            back_clr=C'236,233,216',  // background color 
                     const ENUM_BORDER_TYPE border=BORDER_SUNKEN,     // border type 
                     const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for anchoring 
                     const color            clr=clrRed,               // flat border color (Flat) 
                     const ENUM_LINE_STYLE  style=STYLE_SOLID,        // flat border style 
                     const int              line_width=1,             // flat border width 
                     const bool             back=false,               // in the background 
                     const bool             selection=false,          // highlight to move 
                     const bool             hidden=true,              // hidden in the object list 
                     const long             z_order=0)                // priority for mouse click 
  {
//--- reset the error value 
   ResetLastError();
//--- create a rectangle label 
   if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0))
     {
      Print(__FUNCTION__,": failed to create a rectangle label! Error code = ",GetLastError());
      return(false);
     }

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border);
   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_width);
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
   return(true);
  }
//+------------------------------------------------------------------+
//| Create the button                                                |
//+------------------------------------------------------------------+
bool ButtonCreate(const long              chart_ID=0,               // chart's ID
                  const string            name="Button",            // button name
                  const int               sub_window=0,             // subwindow index
                  const int               x=0,                      // X coordinate
                  const int               y=0,                      // Y coordinate
                  const int               width=50,                 // button width
                  const int               height=18,                // button height
                  const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // chart corner for anchoring
                  const string            text="Button",            // text
                  const string            font="Arial",             // font
                  const int               font_size=10,             // font size
                  const color             clr=clrBlack,             // text color
                  const color             back_clr=C'236,233,216',  // background color
                  const color             border_clr=clrNONE,       // border color
                  const bool              state=false,              // pressed/released
                  const bool              back=false,               // in the background
                  const bool              selection=false,          // highlight to move
                  const bool              hidden=true,              // hidden in the object list
                  const long              z_order=0)                // priority for mouse click
  {
//--- reset the error value
   ResetLastError();
//--- create the button
   int idObject=ObjectFind(name);
   if(idObject<0)
     {
      if(!ObjectCreate(chart_ID,name,OBJ_BUTTON,sub_window,0,0))
        {
         Print(__FUNCTION__,": failed to create the button! Error code = ",GetLastError());
         return(false);
        }
     }

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
   ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
   return(true);
  }
//+------------------------------------------------------------------+
//| Create a text label                                              |
//+------------------------------------------------------------------+
bool LabelCreate(const long              chart_ID=0,               // chart's ID
                 const string            name="Label",             // label name
                 const int               sub_window=0,             // subwindow index
                 const int               x=0,                      // X coordinate
                 const int               y=0,                      // Y coordinate
                 const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // chart corner for anchoring
                 const string            text="Label",             // text
                 const string            font="Arial",             // font
                 const int               font_size=10,             // font size
                 const color             clr=clrRed,               // color
                 const double            angle=0.0,                // text slope
                 const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
                 const bool              back=false,               // in the background
                 const bool              selection=false,          // highlight to move
                 const bool              hidden=true,              // hidden in the object list
                 const long              z_order=0)                // priority for mouse click
  {
//--- reset the error value
   ResetLastError();
//--- create a text label
   int idObject=ObjectFind(name);
   if(idObject<0)
     {
      if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0))
        {
         Print(__FUNCTION__,": failed to create text label! #"+name+"# Error code = ",GetLastError());
         return(false);
        }
     }

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
   return(true);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Draw_HorizontalLine(string objEA,string sText,double price1,color dColor)
  {
   ChartSetInteger(0,CHART_SHOW_OBJECT_DESCR,true);
   
   string sName=objEA+sText;

   if(price1==0)
     {
      if(ObjectFind(sName)>=0) ObjectDelete(sName);
      return;
     }

   if(ObjectFind(sName)<0)
     {
      ObjectCreate(0,sName,OBJ_HLINE,0,0,price1);
      ObjectSetInteger(0,sName,OBJPROP_COLOR,dColor);
      ObjectSetInteger(0,sName,OBJPROP_WIDTH,2);
      ObjectSetInteger(0,sName,OBJPROP_STYLE,STYLE_SOLID);
      ObjectSetInteger(0,sName,OBJPROP_BACK,false);
      string sEmpty="                                            ";
      sText=StringConcatenate(sEmpty,sText);     
      ObjectSetString(0,sName,OBJPROP_TEXT,sText);
     }
   else
      ObjectSetDouble(0,sName,OBJPROP_PRICE,price1);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Move_HorizontalLine(string objEA,string sText,double price1)
  {
   string sName=objEA+sText;
   ObjectSetDouble(0,sName,OBJPROP_PRICE,price1);
  }
//+------------------------------------------------------------------+


//SDK TrailingStop
extern string TrailingStop__ = "-------------------------Trailling Stop-------------------------";
extern bool InpUseTrailingStop = TRUE; // Use Trailling Stop´?
extern double InpTrailStart = 35.0;    // TraillingStart
extern double InpTrailStep = 29.0;     // Size Trailling step

// SE TrailingStop  ENABLE
// if (InpUseTrailingStop) TrailingAlls(InpTrailStart, InpTrailStep, AveragePrice, MagicNumber);

//+------------------------------------------------------------------+
//|           TrailingAlls                                   |
//+------------------------------------------------------------------+
void TrailingAlls(double AvgPrice, int MagicNumber)
{
    int profit;
    double stoptrade;
    double stopcal;
    if (InpTrailStep != 0)
    {
        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)
                    {
                        profit = NormalizeDouble((Bid - AvgPrice) / Point, 0);
                        if (profit < InpTrailStart)
                            continue;
                        stoptrade = OrderStopLoss();
                        stopcal = Bid + InpTrailStep * Point;
                        stopcal = ValidStopLoss(OP_BUY, Bid, stopcal);
                        if (AvgPrice < stopcal && (stoptrade == 0.0 || (stoptrade != 0.0 && stopcal > stoptrade)))
                            OrderModify(OrderTicket(), AvgPrice, stopcal, OrderTakeProfit(), 0, Aqua);
                    }
                    if (OrderType() == OP_SELL)
                    {
                        profit = NormalizeDouble((AvgPrice - Ask) / Point, 0);
                        if (profit < InpTrailStart)
                            continue;
                        stoptrade = OrderStopLoss();
                        stopcal = Ask - InpTrailStep * Point;
                        stopcal = ValidStopLoss(OP_SELL, Ask, stopcal);
                        if (AvgPrice > stopcal && (stoptrade == 0.0 || (stoptrade != 0.0 && stopcal < stoptrade)))
                            OrderModify(OrderTicket(), AvgPrice, stopcal, OrderTakeProfit(), 0, Red);
                    }
                }
                Sleep(1000);
            }
        }
    }
}

double GetPoint(string mySymbol)
{
   double mPoint, myDigits;
   
   myDigits = MarketInfo (mySymbol, MODE_DIGITS);
   if (myDigits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}


//ENGINE MACHX1

extern string MACH__ = "-----------------------------------------------------------------";
extern string MACH = "                                  MODULE MACH GRID               ";
extern string MACH____ = "---------------------------------------------------------------";
string MACH_EAName = "MACH";
input bool InpEnableMACH = true;           //Enable MACH
extern int MACH_MagicNumber = 1101111;     //Magic MACH
extern double MACH_InpTakeProfit = 1800.0; //Take Profit
extern double MACH_InpStoploss = 500.0;    //Stoploss
extern double MACH_InpSlip = 3.0;          //Slip
input double MACH_InpMaxLot = 99;          // Max Lot

extern string MACH_Configgrid__ = "---------------------------GRID--------------------------------------";
input ENUM_TYPE_GRID_LOT MACH_TypeGridLot = Step_lot; // Type MACH_Grid Lot
extern double MACH_InpLotExponent = 1.3;              // MACH_Grid Increment Factor (If Martingale)
extern bool MACH_InpDynamicSizeGrid = true;           // Dynamic Size MACH_Grid
extern int MACH_InpStepSizeGridDefault = 12;          // Step Size in Pips [Default if MACH_InpDynamicSizeGrid true]
extern int MACH_InpGlubina = 24;                      //( Dynamic MACH_Grid) Qtd Periodos p/ maxima e minima
extern int MACH_InpDEL = 3;                           //( Dynamic MACH_Grid) Divizor de (maxima - minima) p/ calculo do tamanho do grid
extern int MACH_InpMaxTrades = 99;                    // Max Lot Open Simultaneo
input int MACH_InpGridStepLot = 3;                    // Level to Change STEP LOT (If  Step Lot)
extern double MACH_InpStepLot = 0.01;                 // STEP LOT (If  Step Lot)
extern double MACH_InpTakeProfitAddLevel = 3;         // Add Take Profit to New Level Grid

extern string MACH_FilterOpenOneCandle__ = "--------------------Filter One Order by Candle--------------";
input bool MACH_InpOpenOneCandle = false;                        // Open one order by candle
input ENUM_TIMEFRAMES MACH_InpTimeframeBarOpen = PERIOD_CURRENT; // Timeframe OpenOneCandle

extern string MACH_EquityCaution__ = "------------------------Filter Caution of Equity ---------------";
extern bool MACH_InpUseEquityCaution = true;                       //  EquityCaution?
extern double MACH_InpValueEquityRiskCaution = 1;                  // Total $ Risk to EquityCaution
extern ENUM_TIMEFRAMES MACH_InpTimeframeEquityCaution = PERIOD_H1; // Timeframe as EquityCaution
extern string MACH_CloseProfit__ = "------------------------ Close in profit Level X ---------------";
input double MACH_MinProfit = 10.00;   // Minimal Profit Close
input int MACH_QtdTradesMinProfit = 2; // Qtd Trades Open to Minimal Profit Close
input bool MACH_MinimalProfitProtectGrid = true; // Min Profit closeds protect all MACH_Grid parent
//VAR MACH1
double MACH_PriceTarget, MACH_StartEquity, MACH_BuyTarget, MACH_SellTarget, MACH_CurrentPairProfit;
double MACH_AveragePrice, MACH_SellLimit, MACH_BuyLimit, MACH_sumLots;
double MACH_LastBuyPrice, MACH_LastSellPrice, MACH_Stopper = 0.0, MACH_iLots, MACH_ordprof;
int MACH_NumOfTrades = 0, MACH_totalOrdensOpen, MACH_ticket, MACH_timeprev = 0, MACH_expiration, MACH_orders_count;
bool MACH_TradeNow = FALSE, MACH_LongTrade = FALSE, MACH_ShortTrade = FALSE, MACH_flag, MACH_NewOrdersPlaced = FALSE;
datetime MACH_vDatetimeUltCandleOpen, MACH_m_time_equityrisk;
bool MACH_equityrisk;

//VARIAVEIS GLOBAIS MACH
int MACH_vg_cnt = 0;
int MACH_vg_GridSize = 0;
string MACH_ID = "MACH", MACH_vg_filters_on = "";
double  MACH_l_lastlot = 0;
double MACH_InpLotdecimal; //Lotdecimal
double MACH_BuyProfit = 0;
double MACH_SellProfit = 0;
int MACH_Level = 0;

double
 MACH_BuyPriceMax=0,MACH_BuyPriceMin=0,MACH_BuyPriceMaxLot=0,MACH_BuyPriceMinLot=0,MACH_BuyPriceAll=0,MACH_BuySumLot=0,
 MACH_SelPriceMin=0,MACH_SelPriceMax=0,MACH_SelPriceMinLot=0,MACH_SelPriceMaxLot=0,MACH_SelPriceAll=0,MACH_SelSumLot=0;

 int
 MACH_BuyPriceMaxTic=0,MACH_BuyPriceMinTic=0,MACH_SelPriceMaxTic=0,MACH_SelPriceMinTic=0;

 double
 MACH_op=0,MACH_lt=0,MACH_tp=0,MACH_sl=0;

 int
 MACH_tk=0,MACH_b=0,MACH_s=0;

   double MACH_oldorderLastLot_Buy;

   double MACH_oldorderopenprice_Buy;
   int MACH_oldticketnumber_Buy;
   int MACH_ticketnumber_Buy = 0;

 double MACH_oldorderLastLot_Sell;

   double MACH_oldorderopenprice_Sell;
   int MACH_oldticketnumber_Sell;
   int MACH_ticketnumber_Sell = 0;

string MACH_Grid ="";
//+------------------------------------------------------------------+
//|           EA MACH x                                              |
//+------------------------------------------------------------------+
void MACHx(int vSinal, bool LotInformado, double Lots)
{
  MACH_BuyPriceMax=0;
  MACH_BuyPriceMin=0;
  MACH_BuyPriceMaxLot=0;
  MACH_BuyPriceMinLot=0;
  MACH_BuyPriceAll=0;
  MACH_BuySumLot=0;
MACH_Grid ="";
 MACH_SelPriceMin=0;
 MACH_SelPriceMax=0;
 MACH_SelPriceMinLot=0;
 MACH_SelPriceMaxLot=0;
 MACH_SelPriceAll=0;
 MACH_SelSumLot=0;

  MACH_BuyPriceMaxTic=0;
 MACH_BuyPriceMinTic=0;
 MACH_SelPriceMaxTic=0;
 MACH_SelPriceMinTic=0;

  MACH_op=0;
 MACH_lt=0;
 MACH_tp=0;
 MACH_sl=0;

 MACH_tk=0;
 MACH_b=0;
 MACH_s=0;

  if (!InpEnableMACH)
      return;

  if (MACH_InpUseEquityCaution && (MACH_m_time_equityrisk == iTime(NULL, MACH_InpTimeframeEquityCaution, 0)))
  {
      MACH_vg_filters_on += "Filter EquityCaution MACH  ON \n";
      MACH_equityrisk = true;
      return;
  }
  else
  {
      MACH_equityrisk = false;
      MACH_vg_filters_on = "";
      MACH_m_time_equityrisk = -1;
  }

  color avgLine = Blue;
  if (MACH_ShortTrade)
      avgLine = Red;

  if (MACH_LongTrade || MACH_ShortTrade)
      SetHLine(avgLine, "Avg" + MACH_ID, MACH_AveragePrice, 0, 3);
  else
      ObjectDelete("Avg" + MACH_ID);

  //NORMALIZA LOT
  if (Lots < MarketInfo(Symbol(), 23))
      Lots = MarketInfo(Symbol(), 23);
  if (Lots > MarketInfo(Symbol(), 25))
      Lots = MarketInfo(Symbol(), 25);

  // SE DynamicPips  ENABLE
  if (MACH_InpDynamicSizeGrid)
  {

      // calculate highest and lowest price from last bar to 24 bars ago
      double hival = High[iHighest(NULL, 0, MODE_HIGH, MACH_InpGlubina, 1)];

      // chart used for symbol and time period
      double loval = Low[iLowest(NULL, 0, MODE_LOW, MACH_InpGlubina, 1)];
      // calculate pips for spread between orders
      MACH_vg_GridSize = NormalizeDouble((hival - loval) / MACH_InpDEL / Point, 0);

      if (MACH_vg_GridSize < MACH_InpStepSizeGridDefault / MACH_InpDEL)
          MACH_vg_GridSize = NormalizeDouble(MACH_InpStepSizeGridDefault / MACH_InpDEL, 0);

      // if dynamic pips fail, assign pips extreme value
      if (MACH_vg_GridSize > MACH_InpStepSizeGridDefault * MACH_InpDEL)
          MACH_vg_GridSize = NormalizeDouble(MACH_InpStepSizeGridDefault * MACH_InpDEL, 0);
  }
  else
      MACH_vg_GridSize = MACH_InpStepSizeGridDefault;

  MACH_CurrentPairProfit = CalculateProfit(MACH_MagicNumber);

  // CONTROL DRAWDOWN
  if (MACH_InpUseEquityCaution && (MACH_CurrentPairProfit < 0.0 && (MACH_CurrentPairProfit < MACH_InpValueEquityRiskCaution * -1)))
  {
      MACH_m_time_equityrisk = iTime(NULL, MACH_InpTimeframeEquityCaution, 0);
      MACH_equityrisk = true;
  }
  else
  {
      MACH_m_time_equityrisk = -1;
      MACH_equityrisk = false;
  }

  double orders_profit=0;

   MACH_oldorderopenprice_Buy=0;
   MACH_oldticketnumber_Buy=0;
   MACH_ticketnumber_Buy = 0;

   MACH_oldorderopenprice_Sell=0;
   MACH_oldticketnumber_Sell=0;
   MACH_ticketnumber_Sell = 0;

  for(int i=OrdersTotal()-1;i>=0;i--)
   {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
       if(OrderMagicNumber()==MACH_MagicNumber)
          if(OrderSymbol()==Symbol())
            {
             MACH_op=NormalizeDouble(OrderOpenPrice(),Digits());
             MACH_lt=NormalizeDouble(OrderLots(),2);
             MACH_tk=OrderTicket();
             if(OrderType()==OP_BUY)
               {
                MACH_totalOrdensOpen++;
                MACH_LongTrade = TRUE;
                MACH_ShortTrade = FALSE;
                MACH_b++;
                MACH_oldticketnumber_Buy = MACH_tk;
                   if (MACH_oldticketnumber_Buy > MACH_ticketnumber_Buy)
                   {
                       MACH_oldorderopenprice_Buy = OrderOpenPrice();
                       MACH_oldorderLastLot_Buy = OrderLots();
                       MACH_ticketnumber_Buy = MACH_oldticketnumber_Buy;
                   }

                if(MACH_op>MACH_BuyPriceMax || MACH_BuyPriceMax==0)
                  {
                 MACH_Grid = MACH_tk;
                   MACH_BuyPriceMax    = MACH_op;
                   MACH_BuyPriceMaxLot = MACH_lt;
                   MACH_BuyPriceMaxTic = MACH_tk;
                  }
                if(MACH_op<MACH_BuyPriceMin || MACH_BuyPriceMin==0)
                  {
                
                   MACH_BuyPriceMin    = MACH_op;
                   MACH_BuyPriceMinLot = MACH_lt;
                   MACH_BuyPriceMinTic = MACH_tk;
                  }
                MACH_BuyPriceAll+=MACH_op*MACH_lt;
                MACH_BuySumLot+=MACH_lt;
               }
             // ===
             if(OrderType()==OP_SELL)
               {
                MACH_totalOrdensOpen++;
                MACH_LongTrade = FALSE;
                MACH_ShortTrade = TRUE;
                MACH_s++;

               MACH_oldticketnumber_Sell = MACH_tk;
                   if (MACH_oldticketnumber_Sell > MACH_ticketnumber_Sell)
                   {
                       MACH_oldorderopenprice_Sell = OrderOpenPrice();
                       MACH_oldorderLastLot_Sell = OrderLots();
                       MACH_ticketnumber_Sell = MACH_oldticketnumber_Sell;
                   }

                if(MACH_op>MACH_SelPriceMax || MACH_SelPriceMax==0)
                  {
                
                   MACH_SelPriceMax    = MACH_op;
                   MACH_SelPriceMaxLot = MACH_lt;
                   MACH_SelPriceMaxTic = MACH_tk;
                  }
                if(MACH_op<MACH_SelPriceMin || MACH_SelPriceMin==0)
                  {
                       MACH_Grid = MACH_tk;
                   MACH_SelPriceMin    = MACH_op;
                   MACH_SelPriceMinLot = MACH_lt;
                   MACH_SelPriceMinTic = MACH_tk;
                  }
                MACH_SelPriceAll+=MACH_op*MACH_lt;
                MACH_SelSumLot+=MACH_lt;
               }

                 orders_profit += OrderProfit() + OrderCommission() + OrderSwap();
            }
   }
 
  int l_hist_total_4 = OrdersHistoryTotal();

  double profitHist= 0;
    MACH_totalOrdensOpen = MACH_b+MACH_s;

    if(MACH_totalOrdensOpen > 1 ){
  for (int l_pos_24 = 0; l_pos_24 < l_hist_total_4; l_pos_24++)
  {
      OrderSelect(l_pos_24, SELECT_BY_POS, MODE_HISTORY);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH_MagicNumber)
          continue;

     //Lucro do grid
     if(OrderComment() == MACH_Grid){
         profitHist += OrderProfit() + OrderCommission() + OrderSwap();
     }

  }
  }
   //Caso MACH_Grid Esteja no lucro e grid está grande Fecha todos do grid para evitar DD
  if(MACH_MinimalProfitProtectGrid && (orders_profit +  profitHist ) > MACH_MinProfit  && MACH_totalOrdensOpen > MACH_QtdTradesMinProfit)
       CloseThisSymbolAll(MACH_MagicNumber,MACH_InpSlip );

   //VERIFICA SE POSSUI TRADER ATIVO
   if (MACH_totalOrdensOpen == 0)
      MACH_flag = FALSE;

  //VERIFY GRID SPACE TO TRADE
  if (MACH_totalOrdensOpen > 0 && MACH_totalOrdensOpen <= MACH_InpMaxTrades)
  {
      RefreshRates();
   
      MACH_LastBuyPrice = MACH_oldorderopenprice_Buy;//FindLastBuyPrice(MACH_MagicNumber, MACH_l_sumlot1);
      MACH_LastSellPrice = MACH_oldorderopenprice_Sell;//FindLastSellPrice(MACH_MagicNumber, MACH_l_sumlot2);
      MACH_sumLots = MACH_BuySumLot + MACH_SelSumLot;

      if (MACH_LongTrade && MACH_LastBuyPrice - Ask >= MACH_vg_GridSize * Point)
          MACH_TradeNow = TRUE;
      if (MACH_ShortTrade && Bid - MACH_LastSellPrice >= MACH_vg_GridSize * Point)
          MACH_TradeNow = TRUE;
  }

  if (MACH_totalOrdensOpen < 1)
  {
      MACH_ShortTrade = FALSE;
      MACH_LongTrade = FALSE;
      MACH_TradeNow = TRUE;
      MACH_StartEquity = AccountEquity();
  }

  // SE OpenOneCandle   ENABLE
  if (!MACH_InpOpenOneCandle || (MACH_InpOpenOneCandle && MACH_vDatetimeUltCandleOpen != iTime(NULL, MACH_InpTimeframeBarOpen, 0)))
  {

      // ORDEM DE GRID
      if (MACH_TradeNow && (MACH_ShortTrade || MACH_LongTrade))
      {
     
      
          MACH_LastBuyPrice = MACH_oldorderopenprice_Buy;//FindLastBuyPriceLL(MACH_MagicNumber, MACH_l_sumlot1, MACH_l_lastlot1);
          MACH_LastSellPrice =  MACH_oldorderopenprice_Sell;//FindLastSellPriceLL(MACH_MagicNumber, MACH_l_sumlot2, MACH_l_lastlot2);
          MACH_sumLots = MACH_BuySumLot + MACH_SelSumLot;
          MACH_l_lastlot = MACH_oldorderLastLot_Sell + MACH_oldorderLastLot_Buy;

          MACH_NumOfTrades = MACH_totalOrdensOpen;

          MACH_InpLotdecimal = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);

          //if(LotInformado)
          //   MACH_iLots = Lots;
          //else
          if (MACH_ShortTrade)
              MACH_iLots = MathRound(CalcLot(MACH_TypeGridLot, OP_BUY, MACH_NumOfTrades, MACH_l_lastlot, Lots, MACH_InpLotExponent, MACH_InpGridStepLot, MACH_InpStepLot), MACH_InpLotdecimal);
          if (MACH_LongTrade)
              MACH_iLots = MathRound(CalcLot(MACH_TypeGridLot, OP_SELL, MACH_NumOfTrades, MACH_l_lastlot, Lots, MACH_InpLotExponent, MACH_InpGridStepLot, MACH_InpStepLot), MACH_InpLotdecimal);

          if (MACH_iLots < MarketInfo(Symbol(), 23))
              MACH_iLots = MarketInfo(Symbol(), 23);
          if (MACH_iLots > MarketInfo(Symbol(), 25))
              MACH_iLots = MarketInfo(Symbol(), 25);
          if (MACH_iLots > MACH_InpMaxLot && !LotInformado)
              MACH_iLots = MACH_InpMaxLot;

          RefreshRates();

          //SELL
          if (MACH_ShortTrade && vSinal == -1)
          {

              MACH_ticket = OpenOrder((string)1, MACH_iLots, Bid, MACH_InpSlip, Ask, 0, 0, MACH_Grid, MACH_MagicNumber, 0, HotPink);
              if (MACH_ticket < 0)
              {
                  Print("Error: ", GetLastError());
                  return;
              }
              MACH_LastSellPrice = MACH_oldorderopenprice_Sell;//FindLastSellPrice(MACH_MagicNumber, MACH_sumLots);
              MACH_TradeNow = FALSE;
              MACH_vDatetimeUltCandleOpen = iTime(NULL, MACH_InpTimeframeBarOpen, 0);
              MACH_NewOrdersPlaced = TRUE;
          }

          //BUY
          if (MACH_LongTrade && vSinal == 1)
          {

              MACH_ticket = OpenOrder(0, MACH_iLots, Ask, MACH_InpSlip, Bid, 0, 0, MACH_Grid, MACH_MagicNumber, 0, Lime);
              if (MACH_ticket < 0)
              {
                  Print("Error: ", GetLastError());
                  return;
              }
              MACH_LastBuyPrice = MACH_oldorderopenprice_Buy;//FindLastBuyPrice(MACH_MagicNumber, MACH_sumLots);
              MACH_TradeNow = FALSE;
              MACH_vDatetimeUltCandleOpen = iTime(NULL, MACH_InpTimeframeBarOpen, 0);
              MACH_NewOrdersPlaced = TRUE;
          }
      }
  }

  //  OpenOneCandle
  if (!MACH_InpOpenOneCandle || (MACH_InpOpenOneCandle && MACH_vDatetimeUltCandleOpen != iTime(NULL, MACH_InpTimeframeBarOpen, 0)))
  {

      // 1ª ORDEM DO GRID
      if (MACH_TradeNow && MACH_totalOrdensOpen < 1)
      {

          MACH_SellLimit = Bid;
          MACH_BuyLimit = Ask;
          if (!MACH_ShortTrade && !MACH_LongTrade)
          {

              MACH_NumOfTrades = MACH_totalOrdensOpen;

              if (LotInformado)
                  MACH_iLots = Lots;
              else
              {
                  MACH_iLots = Lots;
                  //if (vSinal == -1)
                  //    MACH_iLots = MathRound(CalcLot(MACH_TypeGridLot, OP_BUY, MACH_NumOfTrades, MACH_l_lastlot, Lots, MACH_InpLotExponent, MACH_InpGridStepLot, MACH_InpStepLot), MACH_InpLotdecimal);
                  // if (vSinal == 1)
                  //    MACH_iLots = MathRound(CalcLot(MACH_TypeGridLot, OP_SELL, MACH_NumOfTrades, MACH_l_lastlot, Lots, MACH_InpLotExponent, MACH_InpGridStepLot, MACH_InpStepLot), MACH_InpLotdecimal);
              }

              if (MACH_iLots < MarketInfo(Symbol(), 23))
                  MACH_iLots = MarketInfo(Symbol(), 23);
              if (MACH_iLots > MarketInfo(Symbol(), 25))
                  MACH_iLots = MarketInfo(Symbol(), 25);

              if (MACH_iLots > MACH_InpMaxLot && !LotInformado)
                  MACH_iLots = MACH_InpMaxLot;

              //SELL
              if (vSinal == -1)
              {
                  MACH_ticket = OpenOrder(1, MACH_iLots, MACH_SellLimit, MACH_InpSlip, MACH_SellLimit, 0, 0, MACH_ID + "-" + MACH_NumOfTrades, MACH_MagicNumber, 0, HotPink);
                  if (MACH_ticket < 0)
                  {
                      Print("Error: ", GetLastError());
                      return;
                  }

                  MACH_LastSellPrice =  MACH_oldorderopenprice_Sell; //FindLastSellPrice(MACH_MagicNumber, MACH_sumLots);
                  MACH_TradeNow = FALSE;
                  MACH_vDatetimeUltCandleOpen = iTime(NULL, MACH_InpTimeframeBarOpen, 0);
                  MACH_NewOrdersPlaced = TRUE;
              }

              //BUY
              if (vSinal == 1)
              {

                  MACH_ticket = OpenOrder((string)0, MACH_iLots, MACH_BuyLimit, MACH_InpSlip, MACH_BuyLimit, 0, 0, MACH_ID + "-" + MACH_NumOfTrades, MACH_MagicNumber, 0, Lime);
                  if (MACH_ticket < 0)
                  {
                      Print("Error: ", GetLastError());
                      return;
                  }
                  MACH_LastBuyPrice = MACH_oldorderopenprice_Buy;// FindLastBuyPrice(MACH_MagicNumber, MACH_sumLots);
                  MACH_TradeNow = FALSE;
                  MACH_vDatetimeUltCandleOpen = iTime(NULL, MACH_InpTimeframeBarOpen, 0);
                  MACH_NewOrdersPlaced = TRUE;
              }

              // if (MACH_ticket > 0) MACH_expiration = TimeCurrent() + 60.0 * (60.0 * InpMaxTradeOpenHours);
          }
      }
  }

  //CALC MACH_AveragePrice / Count Total Lots
  MACH_totalOrdensOpen = CountTrades(MACH_MagicNumber);
  MACH_AveragePrice = 0;
  double BuyProfit = 0;
  double SellProfit = 0;
  double order_open_price, order_lots;
  int index, orders_total, order_ticket, order_type, ticket, hour;
  int buy_ticket = 0, sell_ticket = 0;
  int buyer_counter = 0, seller_counter = 0, orders_count = 0;
  double buyer_lots = 0.0, seller_lots = 0.0;
  double Count = 0;
  for (MACH_vg_cnt = OrdersTotal() - 1; MACH_vg_cnt >= 0; MACH_vg_cnt--)
  {
      OrderSelect(MACH_vg_cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH_MagicNumber)
          continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH_MagicNumber)
      {
          if (OrderType() == OP_BUY || OrderType() == OP_SELL)
          {
              order_ticket = OrderTicket();
              order_type = OrderType();
              order_open_price = OrderOpenPrice();
              MACH_AveragePrice += OrderOpenPrice() * OrderLots();
              Count += OrderLots();
              if (order_type == OP_BUY)
              {
                  //--- Set Last Buy Order
                  if (order_ticket > buy_ticket)
                  {

                      buy_ticket = order_ticket;
                  }
                  buyer_counter++;
                  if (OrderProfit() > 0)
                      BuyProfit += OrderProfit() + OrderCommission() + OrderSwap();
              }
              //---
              if (order_type == OP_SELL)
              {
                  //--- Set Last Sell Order
                  if (order_ticket > sell_ticket)
                  {

                      sell_ticket = order_ticket;
                  }
                  seller_counter++;
                  if (OrderProfit() > 0)
                      SellProfit += OrderProfit() + OrderCommission() + OrderSwap();
              }
          }
      }
  }
  MACH_BuyProfit = BuyProfit;
  MACH_SellProfit = SellProfit;
  MACH_Level = (buyer_counter + seller_counter);

  if (BuyProfit >= MACH_MinProfit && buyer_counter >= MACH_QtdTradesMinProfit)
      CloseAllTicket(OP_BUY, buy_ticket, MACH_MagicNumber, 3);

  if (SellProfit >= MACH_MinProfit && seller_counter >= MACH_QtdTradesMinProfit)
      CloseAllTicket(OP_SELL, sell_ticket, MACH_MagicNumber, 3);

  if (MACH_totalOrdensOpen > 0)
      MACH_AveragePrice = NormalizeDouble(MACH_AveragePrice / Count, Digits);
  MACH_sumLots = Count;

  //CALC MACH_PriceTarget/MACH_BuyTarget/MACH_Stopper
  if (MACH_NewOrdersPlaced)
  {
      for (MACH_vg_cnt = OrdersTotal() - 1; MACH_vg_cnt >= 0; MACH_vg_cnt--)
      {
          OrderSelect(MACH_vg_cnt, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH_MagicNumber)
              continue;
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH_MagicNumber)
          {
              if (OrderType() == OP_BUY)
              {
                  MACH_PriceTarget = MACH_AveragePrice + (MACH_InpTakeProfit + (MACH_InpTakeProfitAddLevel * MACH_Level)) * Point;
                  MACH_BuyTarget = MACH_PriceTarget;
                  MACH_Stopper = MACH_AveragePrice - (MACH_InpStoploss + (MACH_InpTakeProfitAddLevel * MACH_Level)) * Point;
                  MACH_flag = TRUE;
              }
          }
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH_MagicNumber)
          {
              if (OrderType() == OP_SELL)
              {
                  MACH_PriceTarget = MACH_AveragePrice - (MACH_InpTakeProfit + (MACH_InpTakeProfitAddLevel * MACH_Level)) * Point;
                  MACH_SellTarget = MACH_PriceTarget;
                  MACH_Stopper = MACH_AveragePrice + (MACH_InpStoploss + (MACH_InpTakeProfitAddLevel * MACH_Level)) * Point;
                  MACH_flag = TRUE;
              }
          }
      }
  }

  //ADD TAKE PROFIT
  if (MACH_NewOrdersPlaced)
  {
      if (MACH_flag == TRUE)
      {
          for (MACH_vg_cnt = OrdersTotal() - 1; MACH_vg_cnt >= 0; MACH_vg_cnt--)
          {
              OrderSelect(MACH_vg_cnt, SELECT_BY_POS, MODE_TRADES);
              if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH_MagicNumber)
                  continue;
              if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH_MagicNumber)
                  OrderModify(OrderTicket(), NormalizeDouble(MACH_AveragePrice, Digits), NormalizeDouble(OrderStopLoss(), Digits), NormalizeDouble(MACH_PriceTarget, Digits), 0, Yellow);
              MACH_NewOrdersPlaced = FALSE;
          }
      }
  }

  //CLOSE ALL IF MaxTrades
  if (MACH_totalOrdensOpen > MACH_InpMaxTrades)
  {
      for (int pos = 0; pos < OrdersTotal(); pos++)
      {
          OrderSelect(pos, SELECT_BY_POS);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH_MagicNumber)
              continue;
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH_MagicNumber)
              if (OrderType() == OP_SELL)
              {
                  OrderClose(OrderTicket(), OrderLots(), Ask, 5, White);
                  MACH_ordprof = OrderSwap() + OrderProfit() + OrderCommission();
                  if (GetLastError() == 0)
                  {
                      SendNotification("SellOrder: " + Symbol() + ", " + (string)OrderType() + ", " + DoubleToStr(Ask, Digits) + ", " + DoubleToStr(OrderLots(), 2) + ", " + DoubleToStr(MACH_ordprof, 2));
                  }
                  pos = OrdersTotal();
              }
          if (OrderType() == OP_BUY)
          {
              int v = OrderClose(OrderTicket(), OrderLots(), Bid, 5, White);
              MACH_ordprof = OrderSwap() + OrderProfit() + OrderCommission();
              if (GetLastError() == 0)
              {
                  SendNotification("BuyOrder: " + Symbol() + ", " + (string)OrderType() + ", " + DoubleToStr(Ask, Digits) + ", " + DoubleToStr(OrderLots(), 2) + ", " + DoubleToStr(MACH_ordprof, 2));
              }
              pos = OrdersTotal();
          }
      }
  }
}





//reverse and stop
 //# include http://codepen4mql.minerasoft.com.br/AppCliente/ShowCode?id=nSy8MR8Sd6AzsmqijxCO2g==

//ENGINE MACHX2

extern string MACH2__ = "-----------------------------------------------------------------";
extern string MACH2 = "                                  MODULE MACH2 GRID               ";
extern string MACH2____ = "---------------------------------------------------------------";
string MACH2_EAName = "MACH2";
input bool InpEnableMACH2 = true;           //Enable MACH2
extern int MACH2_MagicNumber = 2201111;     //Magic MACH2
extern double MACH2_InpTakeProfit = 1800.0; //Take Profit
extern double MACH2_InpStoploss = 500.0;    //Stoploss
extern double MACH2_InpSlip = 3.0;          //Slip
input double MACH2_InpMaxLot = 99;          // Max Lot

extern string MACH2_Configgrid__ = "---------------------------GRID--------------------------------------";
input ENUM_TYPE_GRID_LOT MACH2_TypeGridLot = Step_lot; // Type MACH2_Grid Lot
extern double MACH2_InpLotExponent = 1.3;              // MACH2_Grid Increment Factor (If Martingale)
extern bool MACH2_InpDynamicSizeGrid = true;           // Dynamic Size MACH2_Grid
extern int MACH2_InpStepSizeGridDefault = 12;          // Step Size in Pips [Default if MACH2_InpDynamicSizeGrid true]
extern int MACH2_InpGlubina = 24;                      //( Dynamic MACH2_Grid) Qtd Periodos p/ maxima e minima
extern int MACH2_InpDEL = 3;                           //( Dynamic MACH2_Grid) Divizor de (maxima - minima) p/ calculo do tamanho do grid
extern int MACH2_InpMaxTrades = 99;                    // Max Lot Open Simultaneo
input int MACH2_InpGridStepLot = 3;                    // Level to Change STEP LOT (If  Step Lot)
extern double MACH2_InpStepLot = 0.01;                 // STEP LOT (If  Step Lot)
extern double MACH2_InpTakeProfitAddLevel = 3;         // Add Take Profit to New Level Grid

extern string MACH2_FilterOpenOneCandle__ = "--------------------Filter One Order by Candle--------------";
input bool MACH2_InpOpenOneCandle = false;                        // Open one order by candle
input ENUM_TIMEFRAMES MACH2_InpTimeframeBarOpen = PERIOD_CURRENT; // Timeframe OpenOneCandle

extern string MACH2_EquityCaution__ = "------------------------Filter Caution of Equity ---------------";
extern bool MACH2_InpUseEquityCaution = true;                       //  EquityCaution?
extern double MACH2_InpValueEquityRiskCaution = 1;                  // Total $ Risk to EquityCaution
extern ENUM_TIMEFRAMES MACH2_InpTimeframeEquityCaution = PERIOD_H1; // Timeframe as EquityCaution
extern string MACH2_CloseProfit__ = "------------------------ Close in profit Level X ---------------";
input double MACH2_MinProfit = 10.00;   // Minimal Profit Close
input int MACH2_QtdTradesMinProfit = 2; // Qtd Trades Open to Minimal Profit Close
input bool MACH2_MinimalProfitProtectGrid = true; // Min Profit closeds protect all MACH2_Grid parent
//VAR MACH21
double MACH2_PriceTarget, MACH2_StartEquity, MACH2_BuyTarget, MACH2_SellTarget, MACH2_CurrentPairProfit;
double MACH2_AveragePrice, MACH2_SellLimit, MACH2_BuyLimit, MACH2_sumLots;
double MACH2_LastBuyPrice, MACH2_LastSellPrice, MACH2_Stopper = 0.0, MACH2_iLots, MACH2_ordprof;
int MACH2_NumOfTrades = 0, MACH2_totalOrdensOpen, MACH2_ticket, MACH2_timeprev = 0, MACH2_expiration, MACH2_orders_count;
bool MACH2_TradeNow = FALSE, MACH2_LongTrade = FALSE, MACH2_ShortTrade = FALSE, MACH2_flag, MACH2_NewOrdersPlaced = FALSE;
datetime MACH2_vDatetimeUltCandleOpen, MACH2_m_time_equityrisk;
bool MACH2_equityrisk;

//VARIAVEIS GLOBAIS MACH2
int MACH2_vg_cnt = 0;
int MACH2_vg_GridSize = 0;
string MACH2_ID = "MACH2", MACH2_vg_filters_on = "";
double  MACH2_l_lastlot = 0;
double MACH2_InpLotdecimal; //Lotdecimal
double MACH2_BuyProfit = 0;
double MACH2_SellProfit = 0;
int MACH2_Level = 0;

double
 MACH2_BuyPriceMax=0,MACH2_BuyPriceMin=0,MACH2_BuyPriceMaxLot=0,MACH2_BuyPriceMinLot=0,MACH2_BuyPriceAll=0,MACH2_BuySumLot=0,
 MACH2_SelPriceMin=0,MACH2_SelPriceMax=0,MACH2_SelPriceMinLot=0,MACH2_SelPriceMaxLot=0,MACH2_SelPriceAll=0,MACH2_SelSumLot=0;

 int
 MACH2_BuyPriceMaxTic=0,MACH2_BuyPriceMinTic=0,MACH2_SelPriceMaxTic=0,MACH2_SelPriceMinTic=0;

 double
 MACH2_op=0,MACH2_lt=0,MACH2_tp=0,MACH2_sl=0;

 int
 MACH2_tk=0,MACH2_b=0,MACH2_s=0;

   double MACH2_oldorderLastLot_Buy;

   double MACH2_oldorderopenprice_Buy;
   int MACH2_oldticketnumber_Buy;
   int MACH2_ticketnumber_Buy = 0;

 double MACH2_oldorderLastLot_Sell;

   double MACH2_oldorderopenprice_Sell;
   int MACH2_oldticketnumber_Sell;
   int MACH2_ticketnumber_Sell = 0;

string MACH2_Grid ="";
//+------------------------------------------------------------------+
//|           EA MACH2 x                                              |
//+------------------------------------------------------------------+
void MACH2x(int vSinal, bool LotInformado, double Lots)
{
  MACH2_BuyPriceMax=0;
  MACH2_BuyPriceMin=0;
  MACH2_BuyPriceMaxLot=0;
  MACH2_BuyPriceMinLot=0;
  MACH2_BuyPriceAll=0;
  MACH2_BuySumLot=0;
MACH2_Grid ="";
 MACH2_SelPriceMin=0;
 MACH2_SelPriceMax=0;
 MACH2_SelPriceMinLot=0;
 MACH2_SelPriceMaxLot=0;
 MACH2_SelPriceAll=0;
 MACH2_SelSumLot=0;

  MACH2_BuyPriceMaxTic=0;
 MACH2_BuyPriceMinTic=0;
 MACH2_SelPriceMaxTic=0;
 MACH2_SelPriceMinTic=0;

  MACH2_op=0;
 MACH2_lt=0;
 MACH2_tp=0;
 MACH2_sl=0;

 MACH2_tk=0;
 MACH2_b=0;
 MACH2_s=0;

  if (!InpEnableMACH2)
      return;

  if (MACH2_InpUseEquityCaution && (MACH2_m_time_equityrisk == iTime(NULL, MACH2_InpTimeframeEquityCaution, 0)))
  {
      MACH2_vg_filters_on += "Filter EquityCaution MACH2  ON \n";
      MACH2_equityrisk = true;
      return;
  }
  else
  {
      MACH2_equityrisk = false;
      MACH2_vg_filters_on = "";
      MACH2_m_time_equityrisk = -1;
  }

  color avgLine = Blue;
  if (MACH2_ShortTrade)
      avgLine = Red;

  if (MACH2_LongTrade || MACH2_ShortTrade)
      SetHLine(avgLine, "Avg" + MACH2_ID, MACH2_AveragePrice, 0, 3);
  else
      ObjectDelete("Avg" + MACH2_ID);

  //NORMALIZA LOT
  if (Lots < MarketInfo(Symbol(), 23))
      Lots = MarketInfo(Symbol(), 23);
  if (Lots > MarketInfo(Symbol(), 25))
      Lots = MarketInfo(Symbol(), 25);

  // SE DynamicPips  ENABLE
  if (MACH2_InpDynamicSizeGrid)
  {

      // calculate highest and lowest price from last bar to 24 bars ago
      double hival = High[iHighest(NULL, 0, MODE_HIGH, MACH2_InpGlubina, 1)];

      // chart used for symbol and time period
      double loval = Low[iLowest(NULL, 0, MODE_LOW, MACH2_InpGlubina, 1)];
      // calculate pips for spread between orders
      MACH2_vg_GridSize = NormalizeDouble((hival - loval) / MACH2_InpDEL / Point, 0);

      if (MACH2_vg_GridSize < MACH2_InpStepSizeGridDefault / MACH2_InpDEL)
          MACH2_vg_GridSize = NormalizeDouble(MACH2_InpStepSizeGridDefault / MACH2_InpDEL, 0);

      // if dynamic pips fail, assign pips extreme value
      if (MACH2_vg_GridSize > MACH2_InpStepSizeGridDefault * MACH2_InpDEL)
          MACH2_vg_GridSize = NormalizeDouble(MACH2_InpStepSizeGridDefault * MACH2_InpDEL, 0);
  }
  else
      MACH2_vg_GridSize = MACH2_InpStepSizeGridDefault;

  MACH2_CurrentPairProfit = CalculateProfit(MACH2_MagicNumber);

  // CONTROL DRAWDOWN
  if (MACH2_InpUseEquityCaution && (MACH2_CurrentPairProfit < 0.0 && (MACH2_CurrentPairProfit < MACH2_InpValueEquityRiskCaution * -1)))
  {
      MACH2_m_time_equityrisk = iTime(NULL, MACH2_InpTimeframeEquityCaution, 0);
      MACH2_equityrisk = true;
  }
  else
  {
      MACH2_m_time_equityrisk = -1;
      MACH2_equityrisk = false;
  }

  double orders_profit=0;

   MACH2_oldorderopenprice_Buy=0;
   MACH2_oldticketnumber_Buy=0;
   MACH2_ticketnumber_Buy = 0;

   MACH2_oldorderopenprice_Sell=0;
   MACH2_oldticketnumber_Sell=0;
   MACH2_ticketnumber_Sell = 0;

  for(int i=OrdersTotal()-1;i>=0;i--)
   {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
       if(OrderMagicNumber()==MACH2_MagicNumber)
          if(OrderSymbol()==Symbol())
            {
             MACH2_op=NormalizeDouble(OrderOpenPrice(),Digits());
             MACH2_lt=NormalizeDouble(OrderLots(),2);
             MACH2_tk=OrderTicket();
             if(OrderType()==OP_BUY)
               {
                MACH2_totalOrdensOpen++;
                MACH2_LongTrade = TRUE;
                MACH2_ShortTrade = FALSE;
                MACH2_b++;
                MACH2_oldticketnumber_Buy = MACH2_tk;
                   if (MACH2_oldticketnumber_Buy > MACH2_ticketnumber_Buy)
                   {
                       MACH2_oldorderopenprice_Buy = OrderOpenPrice();
                       MACH2_oldorderLastLot_Buy = OrderLots();
                       MACH2_ticketnumber_Buy = MACH2_oldticketnumber_Buy;
                   }

                if(MACH2_op>MACH2_BuyPriceMax || MACH2_BuyPriceMax==0)
                  {
                 MACH2_Grid = MACH2_tk;
                   MACH2_BuyPriceMax    = MACH2_op;
                   MACH2_BuyPriceMaxLot = MACH2_lt;
                   MACH2_BuyPriceMaxTic = MACH2_tk;
                  }
                if(MACH2_op<MACH2_BuyPriceMin || MACH2_BuyPriceMin==0)
                  {
                
                   MACH2_BuyPriceMin    = MACH2_op;
                   MACH2_BuyPriceMinLot = MACH2_lt;
                   MACH2_BuyPriceMinTic = MACH2_tk;
                  }
                MACH2_BuyPriceAll+=MACH2_op*MACH2_lt;
                MACH2_BuySumLot+=MACH2_lt;
               }
             // ===
             if(OrderType()==OP_SELL)
               {
                MACH2_totalOrdensOpen++;
                MACH2_LongTrade = FALSE;
                MACH2_ShortTrade = TRUE;
                MACH2_s++;

               MACH2_oldticketnumber_Sell = MACH2_tk;
                   if (MACH2_oldticketnumber_Sell > MACH2_ticketnumber_Sell)
                   {
                       MACH2_oldorderopenprice_Sell = OrderOpenPrice();
                       MACH2_oldorderLastLot_Sell = OrderLots();
                       MACH2_ticketnumber_Sell = MACH2_oldticketnumber_Sell;
                   }

                if(MACH2_op>MACH2_SelPriceMax || MACH2_SelPriceMax==0)
                  {
                
                   MACH2_SelPriceMax    = MACH2_op;
                   MACH2_SelPriceMaxLot = MACH2_lt;
                   MACH2_SelPriceMaxTic = MACH2_tk;
                  }
                if(MACH2_op<MACH2_SelPriceMin || MACH2_SelPriceMin==0)
                  {
                       MACH2_Grid = MACH2_tk;
                   MACH2_SelPriceMin    = MACH2_op;
                   MACH2_SelPriceMinLot = MACH2_lt;
                   MACH2_SelPriceMinTic = MACH2_tk;
                  }
                MACH2_SelPriceAll+=MACH2_op*MACH2_lt;
                MACH2_SelSumLot+=MACH2_lt;
               }

                 orders_profit += OrderProfit() + OrderCommission() + OrderSwap();
            }
   }
 
  int l_hist_total_4 = OrdersHistoryTotal();

  double profitHist= 0;
    MACH2_totalOrdensOpen = MACH2_b+MACH2_s;

    if(MACH2_totalOrdensOpen > 1 ){
  for (int l_pos_24 = 0; l_pos_24 < l_hist_total_4; l_pos_24++)
  {
      OrderSelect(l_pos_24, SELECT_BY_POS, MODE_HISTORY);
        if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH2_MagicNumber)
          continue;

     //Lucro do grid
     if(OrderComment() == MACH2_Grid){
         profitHist += OrderProfit() + OrderCommission() + OrderSwap();
     }

  }
  }
   //Caso MACH2_Grid Esteja no lucro e grid está grande Fecha todos do grid para evitar DD
  if(MACH2_MinimalProfitProtectGrid && (orders_profit +  profitHist ) > MACH2_MinProfit  && MACH2_totalOrdensOpen > MACH2_QtdTradesMinProfit)
       CloseThisSymbolAll(MACH2_MagicNumber,MACH2_InpSlip );

   //VERIFICA SE POSSUI TRADER ATIVO
   if (MACH2_totalOrdensOpen == 0)
      MACH2_flag = FALSE;

  //VERIFY GRID SPACE TO TRADE
  if (MACH2_totalOrdensOpen > 0 && MACH2_totalOrdensOpen <= MACH2_InpMaxTrades)
  {
      RefreshRates();
   
      MACH2_LastBuyPrice = MACH2_oldorderopenprice_Buy;//FindLastBuyPrice(MACH2_MagicNumber, MACH2_l_sumlot1);
      MACH2_LastSellPrice = MACH2_oldorderopenprice_Sell;//FindLastSellPrice(MACH2_MagicNumber, MACH2_l_sumlot2);
      MACH2_sumLots = MACH2_BuySumLot + MACH2_SelSumLot;

      if (MACH2_LongTrade && MACH2_LastBuyPrice - Ask >= MACH2_vg_GridSize * Point)
          MACH2_TradeNow = TRUE;
      if (MACH2_ShortTrade && Bid - MACH2_LastSellPrice >= MACH2_vg_GridSize * Point)
          MACH2_TradeNow = TRUE;
  }

  if (MACH2_totalOrdensOpen < 1)
  {
      MACH2_ShortTrade = FALSE;
      MACH2_LongTrade = FALSE;
      MACH2_TradeNow = TRUE;
      MACH2_StartEquity = AccountEquity();
  }

  // SE OpenOneCandle   ENABLE
  if (!MACH2_InpOpenOneCandle || (MACH2_InpOpenOneCandle && MACH2_vDatetimeUltCandleOpen != iTime(NULL, MACH2_InpTimeframeBarOpen, 0)))
  {

      // ORDEM DE GRID
      if (MACH2_TradeNow && (MACH2_ShortTrade || MACH2_LongTrade))
      {
     
      
          MACH2_LastBuyPrice = MACH2_oldorderopenprice_Buy;//FindLastBuyPriceLL(MACH2_MagicNumber, MACH2_l_sumlot1, MACH2_l_lastlot1);
          MACH2_LastSellPrice =  MACH2_oldorderopenprice_Sell;//FindLastSellPriceLL(MACH2_MagicNumber, MACH2_l_sumlot2, MACH2_l_lastlot2);
          MACH2_sumLots = MACH2_BuySumLot + MACH2_SelSumLot;
          MACH2_l_lastlot = MACH2_oldorderLastLot_Sell + MACH2_oldorderLastLot_Buy;

          MACH2_NumOfTrades = MACH2_totalOrdensOpen;

          MACH2_InpLotdecimal = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);

          //if(LotInformado)
          //   MACH2_iLots = Lots;
          //else
          if (MACH2_ShortTrade)
              MACH2_iLots = MathRound(CalcLot(MACH2_TypeGridLot, OP_BUY, MACH2_NumOfTrades, MACH2_l_lastlot, Lots, MACH2_InpLotExponent, MACH2_InpGridStepLot, MACH2_InpStepLot), MACH2_InpLotdecimal);
          if (MACH2_LongTrade)
              MACH2_iLots = MathRound(CalcLot(MACH2_TypeGridLot, OP_SELL, MACH2_NumOfTrades, MACH2_l_lastlot, Lots, MACH2_InpLotExponent, MACH2_InpGridStepLot, MACH2_InpStepLot), MACH2_InpLotdecimal);

          if (MACH2_iLots < MarketInfo(Symbol(), 23))
              MACH2_iLots = MarketInfo(Symbol(), 23);
          if (MACH2_iLots > MarketInfo(Symbol(), 25))
              MACH2_iLots = MarketInfo(Symbol(), 25);
          if (MACH2_iLots > MACH2_InpMaxLot && !LotInformado)
              MACH2_iLots = MACH2_InpMaxLot;

          RefreshRates();

          //SELL
          if (MACH2_ShortTrade && vSinal == -1)
          {

              MACH2_ticket = OpenOrder((string)1, MACH2_iLots, Bid, MACH2_InpSlip, Ask, 0, 0, MACH2_Grid, MACH2_MagicNumber, 0, HotPink);
              if (MACH2_ticket < 0)
              {
                  Print("Error: ", GetLastError());
                  return;
              }
              MACH2_LastSellPrice = MACH2_oldorderopenprice_Sell;//FindLastSellPrice(MACH2_MagicNumber, MACH2_sumLots);
              MACH2_TradeNow = FALSE;
              MACH2_vDatetimeUltCandleOpen = iTime(NULL, MACH2_InpTimeframeBarOpen, 0);
              MACH2_NewOrdersPlaced = TRUE;
          }

          //BUY
          if (MACH2_LongTrade && vSinal == 1)
          {

              MACH2_ticket = OpenOrder(0, MACH2_iLots, Ask, MACH2_InpSlip, Bid, 0, 0, MACH2_Grid, MACH2_MagicNumber, 0, Lime);
              if (MACH2_ticket < 0)
              {
                  Print("Error: ", GetLastError());
                  return;
              }
              MACH2_LastBuyPrice = MACH2_oldorderopenprice_Buy;//FindLastBuyPrice(MACH2_MagicNumber, MACH2_sumLots);
              MACH2_TradeNow = FALSE;
              MACH2_vDatetimeUltCandleOpen = iTime(NULL, MACH2_InpTimeframeBarOpen, 0);
              MACH2_NewOrdersPlaced = TRUE;
          }
      }
  }

  //  OpenOneCandle
  if (!MACH2_InpOpenOneCandle || (MACH2_InpOpenOneCandle && MACH2_vDatetimeUltCandleOpen != iTime(NULL, MACH2_InpTimeframeBarOpen, 0)))
  {

      // 1ª ORDEM DO GRID
      if (MACH2_TradeNow && MACH2_totalOrdensOpen < 1)
      {

          MACH2_SellLimit = Bid;
          MACH2_BuyLimit = Ask;
          if (!MACH2_ShortTrade && !MACH2_LongTrade)
          {

              MACH2_NumOfTrades = MACH2_totalOrdensOpen;

              if (LotInformado)
                  MACH2_iLots = Lots;
              else
              {
                  MACH2_iLots = Lots;
                  //if (vSinal == -1)
                  //    MACH2_iLots = MathRound(CalcLot(MACH2_TypeGridLot, OP_BUY, MACH2_NumOfTrades, MACH2_l_lastlot, Lots, MACH2_InpLotExponent, MACH2_InpGridStepLot, MACH2_InpStepLot), MACH2_InpLotdecimal);
                  // if (vSinal == 1)
                  //    MACH2_iLots = MathRound(CalcLot(MACH2_TypeGridLot, OP_SELL, MACH2_NumOfTrades, MACH2_l_lastlot, Lots, MACH2_InpLotExponent, MACH2_InpGridStepLot, MACH2_InpStepLot), MACH2_InpLotdecimal);
              }

              if (MACH2_iLots < MarketInfo(Symbol(), 23))
                  MACH2_iLots = MarketInfo(Symbol(), 23);
              if (MACH2_iLots > MarketInfo(Symbol(), 25))
                  MACH2_iLots = MarketInfo(Symbol(), 25);

              if (MACH2_iLots > MACH2_InpMaxLot && !LotInformado)
                  MACH2_iLots = MACH2_InpMaxLot;

              //SELL
              if (vSinal == -1)
              {
                  MACH2_ticket = OpenOrder(1, MACH2_iLots, MACH2_SellLimit, MACH2_InpSlip, MACH2_SellLimit, 0, 0, MACH2_ID + "-" + MACH2_NumOfTrades, MACH2_MagicNumber, 0, HotPink);
                  if (MACH2_ticket < 0)
                  {
                      Print("Error: ", GetLastError());
                      return;
                  }

                  MACH2_LastSellPrice =  MACH2_oldorderopenprice_Sell; //FindLastSellPrice(MACH2_MagicNumber, MACH2_sumLots);
                  MACH2_TradeNow = FALSE;
                  MACH2_vDatetimeUltCandleOpen = iTime(NULL, MACH2_InpTimeframeBarOpen, 0);
                  MACH2_NewOrdersPlaced = TRUE;
              }

              //BUY
              if (vSinal == 1)
              {

                  MACH2_ticket = OpenOrder((string)0, MACH2_iLots, MACH2_BuyLimit, MACH2_InpSlip, MACH2_BuyLimit, 0, 0, MACH2_ID + "-" + MACH2_NumOfTrades, MACH2_MagicNumber, 0, Lime);
                  if (MACH2_ticket < 0)
                  {
                      Print("Error: ", GetLastError());
                      return;
                  }
                  MACH2_LastBuyPrice = MACH2_oldorderopenprice_Buy;// FindLastBuyPrice(MACH2_MagicNumber, MACH2_sumLots);
                  MACH2_TradeNow = FALSE;
                  MACH2_vDatetimeUltCandleOpen = iTime(NULL, MACH2_InpTimeframeBarOpen, 0);
                  MACH2_NewOrdersPlaced = TRUE;
              }

              // if (MACH2_ticket > 0) MACH2_expiration = TimeCurrent() + 60.0 * (60.0 * InpMaxTradeOpenHours);
          }
      }
  }

  //CALC MACH2_AveragePrice / Count Total Lots
  MACH2_totalOrdensOpen = CountTrades(MACH2_MagicNumber);
  MACH2_AveragePrice = 0;
  double BuyProfit = 0;
  double SellProfit = 0;
  double order_open_price, order_lots;
  int index, orders_total, order_ticket, order_type, ticket, hour;
  int buy_ticket = 0, sell_ticket = 0;
  int buyer_counter = 0, seller_counter = 0, orders_count = 0;
  double buyer_lots = 0.0, seller_lots = 0.0;
  double Count = 0;
  for (MACH2_vg_cnt = OrdersTotal() - 1; MACH2_vg_cnt >= 0; MACH2_vg_cnt--)
  {
      OrderSelect(MACH2_vg_cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH2_MagicNumber)
          continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH2_MagicNumber)
      {
          if (OrderType() == OP_BUY || OrderType() == OP_SELL)
          {
              order_ticket = OrderTicket();
              order_type = OrderType();
              order_open_price = OrderOpenPrice();
              MACH2_AveragePrice += OrderOpenPrice() * OrderLots();
              Count += OrderLots();
              if (order_type == OP_BUY)
              {
                  //--- Set Last Buy Order
                  if (order_ticket > buy_ticket)
                  {

                      buy_ticket = order_ticket;
                  }
                  buyer_counter++;
                  if (OrderProfit() > 0)
                      BuyProfit += OrderProfit() + OrderCommission() + OrderSwap();
              }
              //---
              if (order_type == OP_SELL)
              {
                  //--- Set Last Sell Order
                  if (order_ticket > sell_ticket)
                  {

                      sell_ticket = order_ticket;
                  }
                  seller_counter++;
                  if (OrderProfit() > 0)
                      SellProfit += OrderProfit() + OrderCommission() + OrderSwap();
              }
          }
      }
  }
  MACH2_BuyProfit = BuyProfit;
  MACH2_SellProfit = SellProfit;
  MACH2_Level = (buyer_counter + seller_counter);

  if (BuyProfit >= MACH2_MinProfit && buyer_counter >= MACH2_QtdTradesMinProfit)
      CloseAllTicket(OP_BUY, buy_ticket, MACH2_MagicNumber, 3);

  if (SellProfit >= MACH2_MinProfit && seller_counter >= MACH2_QtdTradesMinProfit)
      CloseAllTicket(OP_SELL, sell_ticket, MACH2_MagicNumber, 3);

  if (MACH2_totalOrdensOpen > 0)
      MACH2_AveragePrice = NormalizeDouble(MACH2_AveragePrice / Count, Digits);
  MACH2_sumLots = Count;

  //CALC MACH2_PriceTarget/MACH2_BuyTarget/MACH2_Stopper
  if (MACH2_NewOrdersPlaced)
  {
      for (MACH2_vg_cnt = OrdersTotal() - 1; MACH2_vg_cnt >= 0; MACH2_vg_cnt--)
      {
          OrderSelect(MACH2_vg_cnt, SELECT_BY_POS, MODE_TRADES);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH2_MagicNumber)
              continue;
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH2_MagicNumber)
          {
              if (OrderType() == OP_BUY)
              {
                  MACH2_PriceTarget = MACH2_AveragePrice + (MACH2_InpTakeProfit + (MACH2_InpTakeProfitAddLevel * MACH2_Level)) * Point;
                  MACH2_BuyTarget = MACH2_PriceTarget;
                  MACH2_Stopper = MACH2_AveragePrice - (MACH2_InpStoploss + (MACH2_InpTakeProfitAddLevel * MACH2_Level)) * Point;
                  MACH2_flag = TRUE;
              }
          }
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH2_MagicNumber)
          {
              if (OrderType() == OP_SELL)
              {
                  MACH2_PriceTarget = MACH2_AveragePrice - (MACH2_InpTakeProfit + (MACH2_InpTakeProfitAddLevel * MACH2_Level)) * Point;
                  MACH2_SellTarget = MACH2_PriceTarget;
                  MACH2_Stopper = MACH2_AveragePrice + (MACH2_InpStoploss + (MACH2_InpTakeProfitAddLevel * MACH2_Level)) * Point;
                  MACH2_flag = TRUE;
              }
          }
      }
  }

  //ADD TAKE PROFIT
  if (MACH2_NewOrdersPlaced)
  {
      if (MACH2_flag == TRUE)
      {
          for (MACH2_vg_cnt = OrdersTotal() - 1; MACH2_vg_cnt >= 0; MACH2_vg_cnt--)
          {
              OrderSelect(MACH2_vg_cnt, SELECT_BY_POS, MODE_TRADES);
              if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH2_MagicNumber)
                  continue;
              if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH2_MagicNumber)
                  OrderModify(OrderTicket(), NormalizeDouble(MACH2_AveragePrice, Digits), NormalizeDouble(OrderStopLoss(), Digits), NormalizeDouble(MACH2_PriceTarget, Digits), 0, Yellow);
              MACH2_NewOrdersPlaced = FALSE;
          }
      }
  }

  //CLOSE ALL IF MaxTrades
  if (MACH2_totalOrdensOpen > MACH2_InpMaxTrades)
  {
      for (int pos = 0; pos < OrdersTotal(); pos++)
      {
          OrderSelect(pos, SELECT_BY_POS);
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != MACH2_MagicNumber)
              continue;
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MACH2_MagicNumber)
              if (OrderType() == OP_SELL)
              {
                  OrderClose(OrderTicket(), OrderLots(), Ask, 5, White);
                  MACH2_ordprof = OrderSwap() + OrderProfit() + OrderCommission();
                  if (GetLastError() == 0)
                  {
                      SendNotification("SellOrder: " + Symbol() + ", " + (string)OrderType() + ", " + DoubleToStr(Ask, Digits) + ", " + DoubleToStr(OrderLots(), 2) + ", " + DoubleToStr(MACH2_ordprof, 2));
                  }
                  pos = OrdersTotal();
              }
          if (OrderType() == OP_BUY)
          {
              int v = OrderClose(OrderTicket(), OrderLots(), Bid, 5, White);
              MACH2_ordprof = OrderSwap() + OrderProfit() + OrderCommission();
              if (GetLastError() == 0)
              {
                  SendNotification("BuyOrder: " + Symbol() + ", " + (string)OrderType() + ", " + DoubleToStr(Ask, Digits) + ", " + DoubleToStr(OrderLots(), 2) + ", " + DoubleToStr(MACH2_ordprof, 2));
              }
              pos = OrdersTotal();
          }
      }
  }
}





//SENSOR MM
extern string MovingAverageConfig__ = "-----------------------------Moving Average--------------------";
input bool EnableSinalMovingAverage = true;        //Enable Sinal  Moving Average
input bool InpMaFilterInverter   = false;          // If True Invert Filter
input ENUM_TIMEFRAMES InpMaFrame = PERIOD_M1;      // Moving Average TimeFrame
input int InpMaPeriod = 3;                        // Moving Average Period
input ENUM_MA_METHOD InpMaMethod = MODE_EMA;       // Moving Average Method
input ENUM_APPLIED_PRICE InpMaPrice = PRICE_CLOSE; // Moving Average Price
input int InpMaShift = 0;                          // Moving Average Shift

input int InpMaMargem = 6;                          // Moving Average Margem to Sinal 
//-----------------------------------------------
int DivSinalMA()
{
    if (!EnableSinalMovingAverage)
        return (0);
    else
        return (1);
}

int GetSinalMA()
{
    int vRet = 0;

    if (!EnableSinalMovingAverage)
       vRet;
    if (iClose(NULL, 0, 0) + (InpMaMargem *Point()) > iMA(NULL, InpMaFrame, InpMaPeriod, 0, InpMaMethod, InpMaPrice, InpMaShift))
        vRet= 1;
    if (iClose(NULL, 0, 0)- (InpMaMargem *Point()) < iMA(NULL, InpMaFrame, InpMaPeriod, 0, InpMaMethod, InpMaPrice, InpMaShift))
        vRet= -1;

    if(InpMaFilterInverter) vRet = vRet*-1;
    
    return vRet;
}

//SENSOR BollingerBands
//# include http://codepen4mql.minerasoft.com.br/AppCliente/ShowCode?id=hNn+WSfS99oBv9SeBcSAHA==

//SENSOR RSI
extern string SINALRSI_ = "SINAL TO MACHX2" ;
extern string RSIConfig__ = "-----------------------------RSI-------------------------------";
input bool EnableSinalRSI = true;              //Enable Sinal  RSI
input bool InpRSIFilterInverter = false;       // If True Invert Filter
input ENUM_TIMEFRAMES InpRSIFrame = PERIOD_H1; // RSI TimeFrame
extern double InpRsiMinimum = 30.0;            //Rsi Minimum
extern double InpRsiMaximum = 70.0;            //Rsi Maximum

//-----------------------------------------------
int DivSinalRSI()
{
    if (!EnableSinalRSI)
        return (0);
    else
        return (1);
}

int GetSinalRSI()
{
    int vRet = 0;

    if (!EnableSinalRSI)
        return vRet;

    double PrevCl = iClose(Symbol(), 0, 2);
    double CurrCl = iClose(Symbol(), 0, 1);

    if (PrevCl > CurrCl && iRSI(NULL, PERIOD_H1, 14, PRICE_CLOSE, 1) > InpRsiMinimum)
        vRet = 1;
    if (PrevCl < CurrCl && iRSI(NULL, PERIOD_H1, 14, PRICE_CLOSE, 1) < InpRsiMaximum)
        vRet = -1;
    if (InpRSIFilterInverter)
        vRet = vRet * -1;
    return vRet;
}

//VISOR 1


extern string _Visor1_ = "-----------------------------Visor 1 --------------------";
extern bool Visor1_Show_the_Time = True;
extern bool Visor1_Show_the_Price = True;

extern color Visor1_Price_Up_Color = LawnGreen;
extern color Visor1_Price_Down_Color = Tomato;
extern int Visor1_Price_X_Position = 10;
extern int Visor1_Price_Y_Position = 10;
extern int Visor1_Price_Size = 20;
double Visor1_Old_Price;

extern int Visor1_Porcent_X_Position = 10;
extern int Visor1_Porcent_Y_Position = 70;
extern int Visor1_Porcent_Size = 20;

extern int Visor1_Symbol_X_Position = 10;
extern int Visor1_Symbol_Y_Position = 40;
extern int Visor1_Symbol_Size = 20;

extern int Visor1_Chart_Timezone = -5;
extern color Visor1_Time_Color = Yellow;
extern int Visor1_Time_Size = 17;
extern int Visor1_Time_X_Position = 10;
extern int Visor1_Time_Y_Position = 10;

extern int Visor1_Spread_Size = 10;
extern int Visor1_Spread_X_Position = 10;
extern int Visor1_Spread_Y_Position = 100;

color Visor1_FontColor = Black;


int Visor1_Sinal =0;

void deinitVisor1()
{
  ObjectDelete("Market_Price_Label");
  ObjectDelete("Time_Label");
  ObjectDelete("Porcent_Price_Label");
  ObjectDelete("Spread_Price_Label");
  ObjectDelete("Simbol_Price_Label");

 
}


int GetSinalVisor1()
{
   return Visor1_Sinal;
}


void Visor1Handling()
{
  if (Visor1_Show_the_Price == true)
  {
    string Market_Price = DoubleToStr(Bid, Digits);

    ObjectCreate("Market_Price_Label", OBJ_LABEL, 0, 0, 0);

    if (Bid > Visor1_Old_Price)
      ObjectSetText("Market_Price_Label", Market_Price, Visor1_Price_Size, "Comic Sans MS", Visor1_Price_Up_Color);
    if (Bid < Visor1_Old_Price)
      ObjectSetText("Market_Price_Label", Market_Price, Visor1_Price_Size, "Comic Sans MS", Visor1_Price_Down_Color);
    Visor1_Old_Price = Bid;

    ObjectSet("Market_Price_Label", OBJPROP_XDISTANCE, Visor1_Price_X_Position);
    ObjectSet("Market_Price_Label", OBJPROP_YDISTANCE, Visor1_Price_Y_Position);
    ObjectSet("Market_Price_Label", OBJPROP_CORNER, 1);
  }

  if (Bid > iClose(0, 1440, 1)){
    Visor1_FontColor = LawnGreen;
    Visor1_Sinal =1;
  }
    
  if (Bid < iClose(0, 1440, 1)){
    Visor1_FontColor = Tomato;
    Visor1_Sinal =-1;
    }
string Porcent_Price = "";
double vclose =  iClose(0, 1440, 1);

  if(vclose > 0 )
         Porcent_Price = DoubleToStr(((iClose(0, 1440, 0) /vclose) - 1) * 100, 3) + " %";
  //string Porcent_Price = DoubleToStr(((iClose(0, 1440, 0) / iClose(0, 1440, 1)) - 1) * 100, 3) + " %";
  //----
  ObjectCreate("Porcent_Price_Label", OBJ_LABEL, 0, 0, 0);
  ObjectSetText("Porcent_Price_Label", Porcent_Price, Visor1_Porcent_Size, "Arial", Visor1_FontColor);
  ObjectSet("Porcent_Price_Label", OBJPROP_CORNER, 1);
  ObjectSet("Porcent_Price_Label", OBJPROP_XDISTANCE, Visor1_Porcent_X_Position);
  ObjectSet("Porcent_Price_Label", OBJPROP_YDISTANCE, Visor1_Porcent_Y_Position);

  string Symbol_Price = Symbol();

  ObjectCreate("Simbol_Price_Label", OBJ_LABEL, 0, 0, 0);
  ObjectSetText("Simbol_Price_Label", Symbol_Price, Visor1_Symbol_Size, "Arial", DeepSkyBlue);
  ObjectSet("Simbol_Price_Label", OBJPROP_CORNER, 1);
  ObjectSet("Simbol_Price_Label", OBJPROP_XDISTANCE, Visor1_Symbol_X_Position);
  ObjectSet("Simbol_Price_Label", OBJPROP_YDISTANCE, Visor1_Symbol_Y_Position);

  string Spreead = "Spread : " + (MarketInfo(Symbol(), MODE_SPREAD)) + " pips";
  ObjectCreate("Spread_Price_Label", OBJ_LABEL, 0, 0, 0);
  ObjectSetText("Spread_Price_Label", Spreead, Visor1_Spread_Size, "Arial", White);
  ObjectSet("Spread_Price_Label", OBJPROP_CORNER, 1);
  ObjectSet("Spread_Price_Label", OBJPROP_XDISTANCE, Visor1_Spread_X_Position);
  ObjectSet("Spread_Price_Label", OBJPROP_YDISTANCE, Visor1_Spread_Y_Position);
  //----------------------------------

  if (Visor1_Show_the_Time == true)
  {
    int MyHour = TimeHour(TimeCurrent());
    int MyMinute = TimeMinute(TimeCurrent());
    int MyDay = TimeDay(TimeCurrent());
    int MyMonth = TimeMonth(TimeCurrent());
    int MyYear = TimeYear(TimeCurrent());
    string MySemana = TimeDayOfWeek(TimeCurrent());
    string NewMinute = "";

    if (MyMinute < 10)
    {
       NewMinute = ("0" + MyMinute);
    }
    else
    {
      NewMinute = DoubleToStr(TimeMinute(TimeCurrent()), 0);
    }

    string NewHour = DoubleToStr(MyHour + Visor1_Chart_Timezone, 0);

    ObjectCreate("Time_Label", OBJ_LABEL, 0, 0, 0);
    ObjectSetText("Time_Label", MyDay + "-" + MyMonth + "-" + MyYear + " " + NewHour + ":" + NewMinute, Visor1_Time_Size, "Comic Sans MS", Visor1_Time_Color);

    ObjectSet("Time_Label", OBJPROP_XDISTANCE, Visor1_Time_X_Position);
    ObjectSet("Time_Label", OBJPROP_YDISTANCE, Visor1_Time_Y_Position);
  }
}

//VISOR SINAL
//# include http://codepen4mql.minerasoft.com.br/AppCliente/ShowCode?id=8aw1fIA8RsgjBcDQ2sQy7w==
 

double vg_Spread = 0;
string vg_filters_on = "";
string vg_initpainel = false;
//+------------------------------------------------------------------+
//|  input parameters                                                |
//+------------------------------------------------------------------+

extern string Filter_Spread__ = "----------------------------Filter Max Spread----------------";
extern int InpMaxvg_Spread = 24; // Max Spread

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    BalanceHigh_SensorStop = AccountBalance();
      GlobalVariableSet("AccBalanceHigh_SensorStop",BalanceHigh_SensorStop);
     AccSTOP_SensorStop = "0";

    vg_Spread = MarketInfo(Symbol(), MODE_SPREAD) * Point;

    vg_filters_on = "";
    vg_initpainel = true;

    printf(vg_versao + " - INIT");

    return (INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    Visor1Handling();
   // Comment(vg_filters_on);
    vg_filters_on = "";


    RefreshRates();

    //FILTER STOP
     if(!SensorStop_start(MACH_MagicNumber)){
        vg_filters_on += "Filter Sensor Stop ON \n";
        return;
    }
   


    //FILTER SPREAD
    if (vg_Spread > InpMaxvg_Spread)
    {
        vg_filters_on += "Filter InpMaxvg_Spread ON \n";
        return;
    }
  
    int