Need help with one piece of code

 

Hi, can anybody please give an advice where to add this code snippet below to my EA to make it work? I tried it on several positions of code and I also can compile it but it had no effect.

Thanks a lot.


int SetOrder(int type)
{
  double price = 0, sl = 0, tp = 0;
  color col = clrNONE;


bool canBuy=true,canSell=true;
   if(OrdersTotal()>0)
      for(int i=OrdersTotal()-1; i>=0; i--)
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Symbol && OrderMagicNumber()==MagicNumber)
           {
            if(OrderType()==OP_BUY && (OrderStopLoss()<OrderOpenPrice() || OrderStopLoss()==0))  canBuy=false;
            if(OrderType()==OP_SELL && (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0)) canSell=false; 
                       }

 if (type == OP_BUY && !canBuy) return 0;

if (type == OP_SELL && !canSell) return 0;
}

//+------------------------------------------------------------------+
//|                                      Strategy: VolumePowerEA.mq4 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+

#property version   "1.00"
#property description "EA based on VolumePowerIndicator"

#include <stdlib.mqh>
#include <stderror.mqh>

extern int Volume_BROKER_GMT = 3;
extern int Volume_Bars = 1;
extern double Volume_Delta = 0.5;
extern int FXPower_Period = 12;
extern int FXPower_Bars = 1;
extern double FXPower_Delta = 0.5;
extern double BufferSL_long = 10;
extern double BufferSL_short = 10;
extern int FisherRangePeriods = 10;
extern double FisherPriceSmoothing = 0;
extern double FisherIndexSmoothing = 0;
extern int ChandelierRange = 1;
extern int ChandelierShift = 0;
extern int ChandelierATRPeriod = 1;
extern double ChandelierATRMultipl = 4.5;
int LotDigits; //initialized in OnInit
extern int MagicNumber = 1;
extern double MM_Percent = 1;
int MaxSlippage = 5; //adjusted in OnInit
int MaxOpenTrades = 1000;
int MaxLongTrades = 1000;
int MaxShortTrades = 1000;
int MaxPendingOrders = 1000;
int MaxLongPendingOrders = 1000;
int MaxShortPendingOrders = 1000;
bool Hedging = true;
int OrderRetry = 5; //# of retries if sending order returns error
int OrderWait = 5; //# of seconds to wait if sending order returns error
double myPoint; //initialized in OnInit

double MM_Size(double SL) //Risk % per trade, SL = relative Stop Loss to calculate risk
  {
   double MaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   double MinLot = MarketInfo(Symbol(), MODE_MINLOT);
   double tickvalue = MarketInfo(Symbol(), MODE_TICKVALUE);
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   double lots = MM_Percent * 1.0 / 100 * AccountBalance() / (SL / ticksize * tickvalue);
   if(lots > MaxLot) lots = MaxLot;
   if(lots < MinLot) lots = MinLot;
   return(lots);
  }

double MM_Size_BO() //Risk % per trade for Binary Options
  {
   double MaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   double MinLot = MarketInfo(Symbol(), MODE_MINLOT);
   double tickvalue = MarketInfo(Symbol(), MODE_TICKVALUE);
   double ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   return(MM_Percent * 1.0 / 100 * AccountBalance());
  }

void myAlert(string type, string message)
  {
   if(type == "print")
      Print(message);
   else if(type == "error")
     {
      Print(type+" | VolumePowerEA @ "+Symbol()+","+IntegerToString(Period())+" | "+message);
     }
   else if(type == "order")
     {
      Print(type+" | VolumePowerEA @ "+Symbol()+","+IntegerToString(Period())+" | "+message);
     }
   else if(type == "modify")
     {
      Print(type+" | VolumePowerEA @ "+Symbol()+","+IntegerToString(Period())+" | "+message);
     }
  }

int TradesCount(int type) //returns # of open trades for order type, current symbol and magic number
  {
   int result = 0;
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      result++;
     }
   return(result);
  }

double TotalOpenProfit(int direction)
  {
   double result = 0;
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)   
     {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
      if((direction < 0 && OrderType() == OP_BUY) || (direction > 0 && OrderType() == OP_SELL)) continue;
      result += OrderProfit();
     }
   return(result);
  }

int myOrderSend(int type, double price, double volume, string ordername) //send order, return ticket ("price" is irrelevant for market orders)
  {
   if(!IsTradeAllowed()) return(-1);
   int ticket = -1;
   int retries = 0;
   int err = 0;
   int long_trades = TradesCount(OP_BUY);
   int short_trades = TradesCount(OP_SELL);
   int long_pending = TradesCount(OP_BUYLIMIT) + TradesCount(OP_BUYSTOP);
   int short_pending = TradesCount(OP_SELLLIMIT) + TradesCount(OP_SELLSTOP);
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   //test Hedging
   if(!Hedging && ((type % 2 == 0 && short_trades + short_pending > 0) || (type % 2 == 1 && long_trades + long_pending > 0)))
     {
      myAlert("print", "Order"+ordername_+" not sent, hedging not allowed");
      return(-1);
     }
   //test maximum trades
   if((type % 2 == 0 && long_trades >= MaxLongTrades)
   || (type % 2 == 1 && short_trades >= MaxShortTrades)
   || (long_trades + short_trades >= MaxOpenTrades)
   || (type > 1 && type % 2 == 0 && long_pending >= MaxLongPendingOrders)
   || (type > 1 && type % 2 == 1 && short_pending >= MaxShortPendingOrders)
   || (type > 1 && long_pending + short_pending >= MaxPendingOrders)
   )
     {
      myAlert("print", "Order"+ordername_+" not sent, maximum reached");
      return(-1);
     }
   //prepare to send order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   if(type == OP_BUY)
      price = Ask;
   else if(type == OP_SELL)
      price = Bid;
   else if(price < 0) //invalid price for pending order
     {
      myAlert("order", "Order"+ordername_+" not sent, invalid price for pending order");
          return(-1);
     }
   int clr = (type % 2 == 1) ? clrRed : clrBlue;
   while(ticket < 0 && retries < OrderRetry+1)
     {
      ticket = OrderSend(Symbol(), type, NormalizeDouble(volume, LotDigits), NormalizeDouble(price, Digits()), MaxSlippage, 0, 0, ordername, MagicNumber, 0, clr);
      if(ticket < 0)
        {
         err = GetLastError();
         myAlert("print", "OrderSend"+ordername_+" error #"+IntegerToString(err)+" "+ErrorDescription(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(ticket < 0)
     {
      myAlert("error", "OrderSend"+ordername_+" failed "+IntegerToString(OrderRetry+1)+" times; error #"+IntegerToString(err)+" "+ErrorDescription(err));
      return(-1);
     }
   string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop"};
   myAlert("order", "Order sent"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+IntegerToString(MagicNumber));
   return(ticket);
  }

int myOrderModify(int ticket, double SL, double TP) //modify SL and TP (absolute price), zero targets do not modify
  {
   if(!IsTradeAllowed()) return(-1);
   bool success = false;
   int retries = 0;
   int err = 0;
   SL = NormalizeDouble(SL, Digits());
   TP = NormalizeDouble(TP, Digits());
   if(SL < 0) SL = 0;
   if(TP < 0) TP = 0;
   //prepare to select order
   while(IsTradeContextBusy()) Sleep(100);
   if(!OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
     {
      err = GetLastError();
      myAlert("error", "OrderSelect failed; error #"+IntegerToString(err)+" "+ErrorDescription(err));
      return(-1);
     }
   //prepare to modify order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   if(CompareDoubles(SL, 0)) SL = OrderStopLoss(); //not to modify
   if(CompareDoubles(TP, 0)) TP = OrderTakeProfit(); //not to modify
   if(CompareDoubles(SL, OrderStopLoss()) && CompareDoubles(TP, OrderTakeProfit())) return(0); //nothing to do
   while(!success && retries < OrderRetry+1)
     {
      success = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits()), NormalizeDouble(SL, Digits()), NormalizeDouble(TP, Digits()), OrderExpiration(), CLR_NONE);
      if(!success)
        {
         err = GetLastError();
         myAlert("print", "OrderModify error #"+IntegerToString(err)+" "+ErrorDescription(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(!success)
     {
      myAlert("error", "OrderModify failed "+IntegerToString(OrderRetry+1)+" times; error #"+IntegerToString(err)+" "+ErrorDescription(err));
      return(-1);
     }
   string alertstr = "Order modified: ticket="+IntegerToString(ticket);
   if(!CompareDoubles(SL, 0)) alertstr = alertstr+" SL="+DoubleToString(SL);
   if(!CompareDoubles(TP, 0)) alertstr = alertstr+" TP="+DoubleToString(TP);
   myAlert("modify", alertstr);
   return(0);
  }

void myOrderClose(int type, int volumepercent, string ordername) //close open orders for current symbol, magic number and "type" (OP_BUY or OP_SELL)
  {
   if(!IsTradeAllowed()) return;
   if (type > 1)
     {
      myAlert("error", "Invalid type in myOrderClose");
      return;
     }
   bool success = false;
   int err = 0;
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   int total = OrdersTotal();
   int orderList[][2];
   int orderCount = 0;
   for(int i = 0; i < total; i++)
     {
      while(IsTradeContextBusy()) Sleep(100);
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      orderCount++;
      ArrayResize(orderList, orderCount);
      orderList[orderCount - 1][0] = OrderOpenTime();
      orderList[orderCount - 1][1] = OrderTicket();
     }
   if(orderCount > 0)
      ArraySort(orderList, WHOLE_ARRAY, 0, MODE_ASCEND);
   for(i = 0; i < orderCount; i++)
     {
      if(!OrderSelect(orderList[i][1], SELECT_BY_TICKET, MODE_TRADES)) continue;
      while(IsTradeContextBusy()) Sleep(100);
      RefreshRates();
      double price = (type == OP_SELL) ? Ask : Bid;
      double volume = NormalizeDouble(OrderLots()*volumepercent * 1.0 / 100, LotDigits);
      if (NormalizeDouble(volume, LotDigits) == 0) continue;
      success = OrderClose(OrderTicket(), volume, NormalizeDouble(price, Digits()), MaxSlippage, clrWhite);
      if(!success)
        {
         err = GetLastError();
         myAlert("error", "OrderClose"+ordername_+" failed; error #"+IntegerToString(err)+" "+ErrorDescription(err));
        }
     }
   string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop"};
   if(success) myAlert("order", "Orders closed"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+IntegerToString(MagicNumber));
  }

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {   
   //initialize myPoint
   myPoint = Point();
   if(Digits() == 5 || Digits() == 3)
     {
      myPoint *= 10;
      MaxSlippage *= 10;
     }
   //initialize LotDigits
   double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   if(LotStep >= 1) LotDigits = 0;
   else if(LotStep >= 0.1) LotDigits = 1;
   else if(LotStep >= 0.01) LotDigits = 2;
   else LotDigits = 3;
   return(INIT_SUCCEEDED);
  }

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

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   int ticket = -1;
   double price;   
   double TradeSize;
   double TotalOpenProfitLong = TotalOpenProfit(1);
   double TotalOpenProfitShort = TotalOpenProfit(-1);
   double SL;
   
   
   //Close Long Positions
   if(iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 1, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 1, 0) != EMPTY_VALUE //VolumePowerIndicator is not equal to fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_BUY, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Long Positions
   if(iCustom(NULL, PERIOD_CURRENT, "Fisher_no_repainting", FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, 2, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "Fisher_no_repainting", FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, 2, 0) != EMPTY_VALUE //Fisher_no_repainting is not equal to fixed value
   && TotalOpenProfitLong >= 0 //Total Open Profit (Long) >= fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_BUY, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Short Positions
   if(iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 0, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 0, 0) != EMPTY_VALUE //VolumePowerIndicator is not equal to fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_SELL, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Close Short Positions
   if(iCustom(NULL, PERIOD_CURRENT, "Fisher_no_repainting", FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, 1, 0) != 0 && iCustom(NULL, PERIOD_CURRENT, "Fisher_no_repainting", FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, 1, 0) != EMPTY_VALUE //Fisher_no_repainting is not equal to fixed value
   && TotalOpenProfitShort >= 0 //Total Open Profit (Short) >= fixed value
   )
     {   
      if(IsTradeAllowed())
         myOrderClose(OP_SELL, 100, "");
      else //not autotrading => only send alert
         myAlert("order", "");
     }
   
   //Open Buy Order
   if(iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 0, 1) != 0 && iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 0, 1) != EMPTY_VALUE //VolumePowerIndicator is not equal to fixed value
   )
     {
      RefreshRates();
      price = Ask;
      SL = iCustom(NULL, PERIOD_CURRENT, "chandelier-exit", 10, 0, 10, 3.5, 0, 0) - BufferSL_long * myPoint; //Stop Loss = chandelier-exit - fixed value
      TradeSize = MM_Size(price - SL);   
      if(IsTradeAllowed())
        {
         ticket = myOrderSend(OP_BUY, price, TradeSize, "");
         if(ticket <= 0) return;
        }
      else //not autotrading => only send alert
         myAlert("order", "");
      myOrderModify(ticket, SL, 0);
     }
   
   //Open Sell Order
   if(iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 1, 1) != 0 && iCustom(NULL, PERIOD_CURRENT, "VolumePowerIndicator", Volume_BROKER_GMT, Volume_Bars, Volume_Delta, FXPower_Period, FXPower_Bars, FXPower_Delta, FisherRangePeriods, FisherPriceSmoothing, FisherIndexSmoothing, ChandelierRange, ChandelierShift, ChandelierATRPeriod, ChandelierATRMultipl, 1, 1) != EMPTY_VALUE //VolumePowerIndicator is not equal to fixed value
   )
     {
      RefreshRates();
      price = Bid;
      SL = iCustom(NULL, PERIOD_CURRENT, "chandelier-exit", 10, 0, 10, 3.5, 1, 0) + BufferSL_short * myPoint; //Stop Loss = chandelier-exit + fixed value
      TradeSize = MM_Size(SL - price);   
      if(IsTradeAllowed())
        {
         ticket = myOrderSend(OP_SELL, price, TradeSize, "");
         if(ticket <= 0) return;
        }
      else //not autotrading => only send alert
         myAlert("order", "");
      myOrderModify(ticket, SL, 0);
     }
  }
//+------------------------------------------------------------------+
 
I know that it is not obvious, but topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I will move your topic to the MQL4 and Metatrader 4 section.
 
  1. Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page?)
              General rules and best pratices of the Forum. - General - MQL5 programming forum?
    Next time post in the correct place. The moderators will likely move this thread there soon.

  2. matzeperi91: give an advice where to add this code snippet below to my EA to make it work? 
    MT4: Learn to code it.
    MT5: Begin learning to code it.
    If you don't learn MQL4/5, there is no common language for us to communicate. If we tell you what you need, you can't code it. If we give you the code, you don't know how to integrate it into your code.

    or pay (Freelance) someone to code it.
              Hiring to write script - General - MQL5 programming forum 2019.08.21

  3. We're not going to code it for you (although it could happen if you are lucky or the problem is interesting.) We are willing to help you when you post your attempt (using CODE button) and state the nature of your problem.
              No free help 2017.04.21

  4. show us your attempt (using the CODE button) and state the nature of your problem.
              No free help 2017.04.21

    Or pay someone. Top of every page is the link Freelance.
              Hiring to write script - General - MQL5 programming forum 2018.05.12