Trying to write a Trailing Hedge EA, but I'm stuck - Please help

 

Hi Everyone

EDIT:  I did not receive any help on my original request, so I decided that it might be better to break it down in smaller sections, rather than ask all my questions in one go.  So I have edited this post and would like to start out by asking advise on this code, please: 

The following code appears to be old, and does not seem to work well on all currency pairs.  This is suppose to calculate the pips value for trailing stops etc. Is there a better way for me to code my EA so it works on all currency pairs?  I have a 5 digit broker.  I have searched and seen code e.g. pips2dbl and digits%2 etc, but I was wondering if this is current.  Thank you

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == true)
      if (OrderSymbol() != Symbol()) continue; // Skipping positions in other currency pairs
      //Calculate the point value in case there are extra digits in the quotes
      if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.01) PointValue = 0.1;
      else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
 if (Bid - OrderOpenPrice() > TrailingStart*PointValue)
         {
            if (OrderStopLoss() < Bid - TrailingStop*PointValue)
Files:
 

Hi Everyone

 

I thought it would be better to reduce the number of questions, so I edited/ updated my post above and would really appreciate any help/ teaching.  Thanks.  Gary 

 

If operating with different symbols do not use Bid. Bid is the value for the chart symbol.

Use MarketInfo to find the Bid value of the OrderSymbol. 

 

Thank you very much for the reply.  I have now simplified the EA and have the following code, but it still does not work on all pairs.  It still compiles with a warning regarding the return value because if I leave it as in post #1, the EA doesn't work at all.

int start()
{
  double lots;
  for (int i = 0; i < OrdersTotal(); i++) 
  {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      MarketInfo(OrderSymbol(), MODE_POINT);
      MarketInfo(OrderSymbol(), MODE_BID);
      
      double Pip = Point*10;
      
      //calculate new lotsize of hedge based on lotsize of current open trade*Multiplier
      lots = NormalizeDouble(OrderLots() * Multiplier, 2);      
       
      if (OrderType() == OP_BUY)
      {
         if (Bid - OrderOpenPrice() > TrailingStart*Pip)
         {
            if (OrderStopLoss() < Bid - TrailingStop*Pip)
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - TrailingStop*Pip, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  Print("Error setting Buy trailing stop: ", GetLastError());
            }
         }
       }
      else if (OrderType() == OP_SELL)
      {
         if (OrderOpenPrice() - Ask > TrailingStart*Pip)
         {
            if ((OrderStopLoss() > Ask + TrailingStop*Pip) || (OrderStopLoss() == 0))
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + TrailingStop*Pip, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  Print("Error setting Sell trailing stop: ", GetLastError());
            }
         }
       }   
        }
 
   return(0);
}
 
      MarketInfo(OrderSymbol(), MODE_POINT);
      MarketInfo(OrderSymbol(), MODE_BID);

You are not assigning these values to any variables.

You are using Bid, Ask and Point, these only apply for the chart symbol. I have already explained this. 

GumRai:

If operating with different symbols do not use Bid. Bid is the value for the chart symbol.

Use MarketInfo to find the Bid value of the OrderSymbol. 

 
GumRai:

You are not assigning these values to any variables.

You are using Bid, Ask and Point, these only apply for the chart symbol. I have already explained this. 

 

Thank you again.  I have now modified the code as below, and noticed that it is still only trading currency pairs that have my base currency (which is USD), eg eurusd.  It does not trade any other pairs that do not contain my base currency  such as eurjpy.
 for (int i = 0; i < OrdersTotal(); i++) 
  {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      
      double vbid    = MarketInfo(OrderSymbol(),MODE_BID);
      double vask    = MarketInfo(OrderSymbol(),MODE_ASK);
      double vpoint  = MarketInfo(OrderSymbol(),MODE_POINT);
      double PointValue = vpoint*10;
      
      if (OrderType() == OP_BUY)
      {
         if (vbid - OrderOpenPrice() > TrailingStart*PointValue)
         {
            if (OrderStopLoss() < vbid - TrailingStop*PointValue)
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), vbid - TrailingStop*PointValue, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  Print("Error setting Buy trailing stop: ", GetLastError());
            }
         }
       }
      else if (OrderType() == OP_SELL)
      {
         if (OrderOpenPrice() - vask > TrailingStart*PointValue)
         {
            if ((OrderStopLoss() > vask + TrailingStop*PointValue) || (OrderStopLoss() == 0))
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), vask + TrailingStop*PointValue, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  Print("Error setting Sell trailing stop: ", GetLastError());
            }
         }
       }   
        }
 
   return(0);
}
 

Hi Everyone

Please help! 

I am extremely sad because I cannot get this to work.  I have been struggling with this every day for many weeks now.  I have tried so many things.  I even found this post where th person had the same problem as mine.  He managed to resolve the issue somehow:  https://forum.mql4.com/58840

 

I am now at version 30 and it seems to work sometimes, but I am getting error code 1:

ERR_NO_RESULT1No error returned, but the result is unknown.

 

My code now looks like this and I have also attached the whole EA.  Thank you

int start()
{

  for (int i = 0; i < OrdersTotal(); i++) 
  {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      
      double vbid    = MarketInfo(OrderSymbol(),MODE_BID);
      double vask    = MarketInfo(OrderSymbol(),MODE_ASK);
      double vpoint  = MarketInfo(OrderSymbol(),MODE_POINT);
      double PointValue = vpoint*10;
      
     if (OrderType() == OP_BUY)
      {
         if (vbid - OrderOpenPrice() > TrailingStart*PointValue)
         {
            if ((OrderStopLoss() < vbid - TrailingStop*PointValue) || (OrderStopLoss() == 0))
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), vbid - TrailingStop*PointValue, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  if(!res) 
               Print("Error in OrderModify. Error code=",GetLastError()); 
            else 
               Print("Order modified successfully."); 
            }
         }            
      }
      else if (OrderType() == OP_SELL)
      {
         if (OrderOpenPrice() - vask > TrailingStart*PointValue)
         {
            if ((OrderStopLoss() > vask + TrailingStop*PointValue) || (OrderStopLoss() == 0))
            {
               if (!OrderModify(OrderTicket(), OrderOpenPrice(), vask + TrailingStop*PointValue, OrderTakeProfit(), OrderExpiration(), clrNONE))
                  if(!res) 
               Print("Error in OrderModify. Error code=",GetLastError()); 
            else 
               Print("Order modified successfully."); 
            }
         }      
      }   
        }
 
   return(0);
}
Files:
 
Trader3000: I am now at version 30 and it seems to work sometimes, but I am getting error code 1:
ERR_NO_RESULT1No error returned, but the result is unknown.
Nothing to do with code; it sent the command and received no reply. A network or sever issue. Wait a minute, verify the terminal is connected, then verify that the order was not placed.
 

RaptorUK published the old correct documentation reference: https://forum.mql4.com/61528

ERR_NO_RESULT  1 OrderModify attempts to replace the values already set with the same values.

                                One or more values must be changed, then modification attempt can be repeated. 

 

Thank you for everyone's help so far.  I have tried everything, but I cannot get it ti work.  I believe that the problem lies with calculating the pointvalue.  The original code was:

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == true)
      if (OrderSymbol() != Symbol()) continue; // Skipping positions in other currency pairs
      //Calculate the point value in case there are extra digits in the quotes
      if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.01) PointValue = 0.1;
      else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);

 Perhaps I should try and replace it with this.  I have tried but the code below will not compile without errors.  Will someone please have a look and let me know how to calculate the trailingstop*pointvalue?  Thank you

//++++ These are adjusted for 5 digit brokers.
int     pips2points;    // slippage  3 pips    3=points    30=points
double  pips2dbl;       // Stoploss 15 pips    0.0015      0.00150
int     Digits.pips;    // DoubleToStr(dbl/pips2dbl, Digits.pips)
int     init(){
     if (Digits % 2 == 1){      // DE30=1/JPY=3/EURUSD=5 forum.mql4.com/43064#515262
                pips2dbl    = Point*10; pips2points = 10;   Digits.pips = 1;
    } else {    pips2dbl    = Point;    pips2points =  1;   Digits.pips = 0; }
    // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
//---- These are adjusted for 5 digit brokers.
    /* On ECN brokers you must open first and THEN set stops
    int ticket = OrderSend(...)
    if (ticket < 0)
       Alert("OrderSend failed: ", GetLastError());
    else if (!OrderSelect(ticket, SELECT_BY_POS))
       Alert("OrderSelect failed: ", GetLastError());
    else if (!OrderModify(OrderTicket()...)
       Alert("OrderModify failed: ", GetLastError());
     */
 

Update:  I am on version 35 now, and finally have it working on all the pairs that I have tested it on.  I had to create 3 different EA's to compensate for the digits.  My broker uses 6 digits, either 5, 4, or 3 digits after the decimal.  For pairs such as EURUSD ( bid 1.09111) I multiply with 10, for pairs such as EURJPY (bid 127.282) I multiply with 20, and for pairs such as USDZAR (bid 16.8219) I multiply by 40 using this:

double pip = (MarketInfo(OrderSymbol(), MODE_POINT))*10;

 this

double pip = (MarketInfo(OrderSymbol(), MODE_POINT))*20;

 and this, respectively

double pip = (MarketInfo(OrderSymbol(), MODE_POINT))*40;

 

My code now looks like this for the USD pairs

int start()
{

  for (int i = 0; i < OrdersTotal(); i++) 
  {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      if (OrderSymbol()==Symbol() )
      double pip = (MarketInfo(OrderSymbol(), MODE_POINT))*10;
      
     if (OrderType() == OP_BUY) 
      {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *pip,4)) 
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop * pip,4)) 
            {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop * pip,4), OrderTakeProfit(), Blue))
              if(!res) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
            else 
               Print("Order modified successfully."); 
              }
            }
          }
     else if (OrderType() == OP_SELL)
      {
        if (OrderOpenPrice() - Ask > NormalizeDouble(TrailingStart * pip,4)) 
         {
          if ((OrderStopLoss() > Ask + NormalizeDouble(TrailingStop * pip,4)) || (OrderStopLoss() == 0))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Ask + NormalizeDouble(TrailingStop * pip,4), OrderTakeProfit(), Red))
              if(!res) 
              Print("Error setting Sell trailing stop: ",GetLastError()); 
            else 
               Print("Order modified successfully."); 
              }
                 }
          }
         }
    return(0);
}

 This multiplication does not seem to be accurate esp on a pair such as AUDUSD.  There has to be a way to have only one EA that works on all pairs.  How do other people calculate Trailing stops in pips that work on all pairs?  Thank you for any help. 

Reason: