Download MetaTrader 5

Automatic moving Stoploss in EA

To add comments, please log in or register
Start making profit using the Market. Publish your product!
White Rose
44
White Rose 2016.11.02 09:54 

Hi Everyone,

 I am coding a EA. I dont know how to make Stoploss move automatically. Could anyone please help me on this ?

Fernando Carreiro
2346
Fernando Carreiro 2016.11.02 12:53  
White Rose:

Hi Everyone,

 I am coding a EA. I dont know how to make Stoploss move automatically. Could anyone please help me on this ?

Are you using MQL4 or MQL5?

For MQL4:

For MQL5 (it is a little more complex):

OrderModify - Trade Functions - MQL4 Reference
OrderModify - Trade Functions - MQL4 Reference
  • docs.mql4.com
OrderModify - Trade Functions - MQL4 Reference
White Rose
44
White Rose 2016.11.03 04:14  
Fernando Carreiro:

Are you using MQL4 or MQL5?

For MQL4:

For MQL5 (it is a little more complex):

Thank you for your help. I am using MQL4. I can call the code out but It does not work. I don't know why ?

Fernando Carreiro
2346
Fernando Carreiro 2016.11.03 11:59  
White Rose:

Thank you for your help. I am using MQL4. I can call the code out but It does not work. I don't know why ?

Then you are going to have to show your code so that we can spot the errors and correct them.

We are not mind readers and we cannot help you by guessing!

PS! There is now a dedicated MQL4 and MetaTrader 4 section (at the end of the main forum page). So in the future, all new topics related to MQL4 should be placed there.

EDIT: When adding code, attach it if it is long or an entire file, or use the SRC button on the forum's toolbar to add snippets of code.

White Rose
44
White Rose 2016.11.03 17:21  
Fernando Carreiro:

Then you are going to have to show your code so that we can spot the errors and correct them.

We are not mind readers and we cannot help you by guessing!

PS! There is now a dedicated MQL4 and MetaTrader 4 section (at the end of the main forum page). So in the future, all new topics related to MQL4 should be placed there.

EDIT: When adding code, attach it if it is long or an entire file, or use the SRC button on the forum's toolbar to add snippets of code.

Thank you for your support. Please see attached the code that I have written. Please help me to correct it if any thing wrong 
Fernando Carreiro
2346
Fernando Carreiro 2016.11.03 17:24  
White Rose:
Thank you for your support. Please see attached the code that I have written. Please help me to correct it if any thing wrong 
No code is attached to your post! Also, please describe in detail the nature of your difficulties and the errors you are getting!
White Rose
44
White Rose 2016.11.03 17:38  
Fernando Carreiro:
No code is attached to your post! Also, please describe in detail the nature of your difficulties and the errors you are getting!

Please see the code here 

 

void MoveBuySLTP(double NewSL,double NewTP, uint MagicNo)

   {

   uint  TTOrder=OrdersTotal();

   if(TTOrder==0)return;

   else

     {

      double NewSL=NormalizeDouble(NewSL,Digits),

                 NewTP=NormalizeDouble(NewTP,Digits);

     for(uchar i=0;i<TTOrder;i++)

       {

        if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

          {

           if(OrderSymbol()!=XAUUSD || OrderMagicNumber()!=Magic|| OrderType()!=OP_BUY)continue;

           else  

             {

              if(OrderStopLoss()<NewSL)

               if(OrderModify(OrderTicket(),OrderOpenPrice(),NewSL,NewTP,0,clrNONE))

                  Print("Stoploss moved successful"+DoubleToStr(NewSL,Digits));

             }

          }

       }

     }

  

   return;

   }
whroeder1
14543
whroeder1 2016.11.03 17:57  
White Rose: Please see the code here
How do you expect to succeed when you can't follow simple directions?
  1. Fernando Carreiro: or use the SRC button on the forum's toolbar to add snippets of code.

  2. Play video
    Please edit your post.
    For large amounts of code, attach it.
Fernando Carreiro
2346
Fernando Carreiro 2016.11.03 18:03  
White Rose: Please see the code here 

Please use the SRC button as instructed.

The following code is only meant as a "skeleton" example and is untested:

void MoveSLTP( double NewSL, double NewTP, int MagicNo, int OrdType )
{
   int TTOrder = OrdersTotal(); // OrderTotal() returns an "int", not a "uint".
  
   if( TTOrder > 0 )
   {
      NewSL = NormalizeDouble( NewSL, _Digits ); // It is not a good idea to use NormalizeDouble (its a kludge) ...
      NewTP = NormalizeDouble( NewTP, _Digits ); // ... You should normalise based on Tick-Size instead. So consider this wrong!

      for( int i = TTOrder - 1; i >= 0; i-- ) // OrderTotal() returns an "int", not a "uchar".
      {
         if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
         {
            if( ( OrderMagicNumber() == MagicNo ) &&
                ( OrderType()        == OrdType ) &&
                ( OrderSymbol()      == _Symbol ) ) // Your EA is already on the correct chart, so use the chart symbol.
            {
               bool UpdateFlag = false;
              
               // The following is not ideal, because it does not consider the minimum STOP-LEVEL or FREEZE-LEVEL ...
               // ... but it is a start so as to help you in the right direction.
               switch( OrdType )
               {
                  case OP_BUY:
                     UpdateFlag = ( NewSL > OrderStopLoss()   ) &&
                                  ( NewSL < OrderClosePrice() ) &&
                                  ( NewTP > OrderClosePrice() );
                     break;
              
                  case OP_SELL:
                     UpdateFlag = ( NewSL < OrderStopLoss()   ) &&
                                  ( NewSL > OrderClosePrice() ) &&
                                  ( NewTP < OrderClosePrice() );
                     break;
               }
              
               if( UpdateFlag )
               {
                  ResetLastError();
                  if( !OrderModify( OrderTicket(), OrderOpenPrice(), NewSL, NewTP, 0, clrNONE ) )
                     Print( "OrderModify Error: ", _LastError ); // You should consider the possible errors and act accordingly.
               }
            }
         }
      }
   }

   return;
}

Please take into account the problematic areas that I have mentioned and follow-up on the research!

EDIT: Please note that this post was reedited and the initial code posted was changed!


White Rose
44
White Rose 2016.11.04 06:48  
Fernando Carreiro:

Please use the SRC button as instructed.

The following code is only meant as a "skeleton" example and is untested:

void MoveSLTP( double NewSL, double NewTP, int MagicNo, int OrdType )
{
   int TTOrder = OrdersTotal(); // OrderTotal() returns an "int", not a "uint".
  
   if( TTOrder > 0 )
   {
      NewSL = NormalizeDouble( NewSL, _Digits ); // It is not a good idea to use NormalizeDouble (its a kludge) ...
      NewTP = NormalizeDouble( NewTP, _Digits ); // ... You should normalise based on Tick-Size instead. So consider this wrong!

      for( int i = TTOrder - 1; i >= 0; i-- ) // OrderTotal() returns an "int", not a "uchar".
      {
         if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
         {
            if( ( OrderMagicNumber() == MagicNo ) &&
                ( OrderType()        == OrdType ) &&
                ( OrderSymbol()      == _Symbol ) ) // Your EA is already on the correct chart, so use the chart symbol.
            {
               bool UpdateFlag = false;
              
               // The following is not ideal, because it does not consider the minimum STOP-LEVEL or FREEZE-LEVEL ...
               // ... but it is a start so as to help you in the right direction.
               switch( OrdType )
               {
                  case OP_BUY:
                     UpdateFlag = ( NewSL > OrderStopLoss()   ) &&
                                  ( NewSL < OrderClosePrice() ) &&
                                  ( NewTP > OrderClosePrice() );
                     break;
              
                  case OP_SELL:
                     UpdateFlag = ( NewSL < OrderStopLoss()   ) &&
                                  ( NewSL > OrderClosePrice() ) &&
                                  ( NewTP < OrderClosePrice() );
                     break;
               }
              
               if( UpdateFlag )
               {
                  ResetLastError();
                  if( !OrderModify( OrderTicket(), OrderOpenPrice(), NewSL, NewTP, 0, clrNONE ) )
                     Print( "OrderModify Error: ", _LastError ); // You should consider the possible errors and act accordingly.
               }
            }
         }
      }
   }

   return;
}

Please take into account the problematic areas that I have mentioned and follow-up on the research!

EDIT: Please note that this post was reedited and the initial code posted was changed!


I appreciate your help. It is very useful for me

I am having an idea and also finished the code. I have 3 options to close the Buy or Sell orders when the candle is being reversal. Option 1: Close all orders that has profit - Option 2: Close all orders that has lost - Option 3:As default  . Could you please take a look and correct me if any things wrong. Please see attached the code  

Files:
MAHA.mq4 14 kb
Fernando Carreiro
2346
Fernando Carreiro 2016.11.04 13:32  
White Rose:

I appreciate your help. It is very useful for me

I am having an idea and also finished the code. I have 3 options to close the Buy or Sell orders when the candle is being reversal. Option 1: Close all orders that has profit - Option 2: Close all orders that has lost - Option 3:As default  . Could you please take a look and correct me if any things wrong. Please see attached the code  

  1. For starters, your file does not compile because of undeclared identifiers.
  2. When closing orders, you must always count down, just as I have shown you in my previous post correcting your MoveSLTP function. So, get into the habit of ALWAYS counting down when iterating over the Order history.
  3. When the OrderClose fails, verify the reason (the error code) and act accordingly. Don't just try to close it 15 times without regard for the reason.
  4. Don't hard-code the slippage. Let it be an external variable definable by the user.
  5. Instead of using Ask or Bid to close the order, use the OrderClosePrice() instead which will automatically select the Bid or Ask depending on the Order Type (just as I have used in the example code posted before).
  6. Combine your Buy and Sell functions, into the same function, just as I did for you in the MoveSLTP function. This way you only have to maintain one function.
  7. Don't confuse your code by using the "if( !condition ) continue; else {...};" construct. Just use "if( condition ) {...}" instead as I have shown you in my previous example code.
  8. To make your code more maintainable, instead of creating 3 loops (for Winning, Loosing and All orders), rather just create one loop, and check the condition within the loop. This makes the code more compact and easier to maintain (and read) than repeating the whole closing process 3 times.

There are more points, but these should be enough to get you started. You may also notice that many of the points listed, have already be shown to you in my example code in the MoveSLTP function, so you should have taken notice of them and done the research.

On a special note, have a look at the MQL4 Updates so that you keep up with the modern style of MQL4 coding.

Also, I highly recommend that you build up your coding skills and basic coding experience by practicing with "C" coding. Here are a few links for sites that offer tutorials and learning for "C" that can help:

OrderClosePrice - Trade Functions - MQL4 Reference
OrderClosePrice - Trade Functions - MQL4 Reference
  • docs.mql4.com
OrderClosePrice - Trade Functions - MQL4 Reference
12
To add comments, please log in or register