Popular results

Advertisements
$ £ ¥
¥ £ $

Modify Orders with MQL4 OrderModify()

Table of contents

The MQL4 OrderModify() function allows you to modify an order in MetaTrader 4 platform.

From our previous guides, you learned how to open orders, close orders and scan for existing orders in MT4.

As you should already know, orders can also be modified. For example, for pending orders, you might want to change the open price, or, for market orders, you might want to change the stop-loss or take-profit prices.


MQL4 OrderModify() Function

It is quite easy to update an order using MQL4 language. The process is very similar to using the OrderClose() function. To modify an order, MQL4 offers the OrderModify() function.

You will see some examples below of how to modify existing orders using this MQL4 function.


OrderModify() MQL4 Parameters

Here you can see the specification details for this function:

bool  OrderModify(
   int        ticket,      // ticket
   double     price,       // price
   double     stoploss,    // stop loss
   double     takeprofit,  // take profit
   datetime   expiration,  // expiration
   color      arrow_color  // color
   );

The parameters are:

  • ticket to identify the order you want to modify.
  • price is used to change the open price of a pending order.
  • stoploss is the new stop-loss price.
  • takeprofit is the new take-profit price.
  • expiration is to change the expiration date and time for a pending order.
  • arrow_color is to set the color of the "order updated" arrow on the chart or to hide it.

Like when you open a new order, remember to consider that price, stop-loss price, and take-profit price cannot be too close to the current price or the operation will fail.


Why Modify Order?

Why would you want to change an order using MQL4 code? Here are some examples:

  • Trailing stop is, maybe, one of the most popular reasons — you move the stop-loss price when the price moves in the direction of your order.
  • Moving a take-profit price — usually, done together with a trailing stop.
  • Change the expiration date of a pending order to extend it or to set the expiry close to some news event.
  • Change the open price of a pending order in case of a change in market conditions.

MQL4 OrderModify() Example

In this example, you are going to see how a script can set a stop-loss and take-profit price for each order without stop-loss for given a currency pair. Here is the code:

#property copyright "EarnForex.com"
#property link      "https://www.earnforex.com/"
#property version   "1.00"
#property strict

#property show_inputs

extern double Slippage = 3;  // Allowed slippage

extern int TakeProfit = 40;  // Take profit in pips
extern int StopLoss = 20;    // Stop loss in pips

// It is recommended to normalize the digits to properly calculate take-profit and stop-loss.
// This works only for non-exotic currency pairs.
double CalculateNormalizedDigits()
{
   if (Digits <= 3)
   {
      return(0.01);
   }
   else if (Digits >= 4)
   {
      return(0.0001);
   }
   else return(0);
}

// Declare a function UpdateOpenOrders() to return the number of orders that have been updated.
int UpdateOpenOrders()
{
   int TotalUpdated = 0;  // Counter for how many orders have been updated.
   
   double nDigits = CalculateNormalizedDigits();
   
   // Normalization of the slippage.
   if ((Digits == 3 || (Digits == 5))
   {
      Slippage = Slippage * 10;
   }
   
   // Scan all the orders backwards.
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      // Select an order by index i, selecting by position and from the pool of market trades.
      // If the selection is successful, proceed with the update.
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
          {
         // Check if the order is for the current chart's currency pair.
         if (OrderSymbol() == Symbol()){
            double OpenPrice = 0;
            double StopLossPrice = 0;
            double TakeProfitPrice = 0;
            // Get the open price.
            OpenPrice = OrderOpenPrice();
            // Calculate the stop-loss and take-profit price depending on the type of order.
            if (OrderType() == OP_BUY)
                        {
               StopLossPrice = NormalizeDouble(OpenPrice - StopLoss * nDigits, Digits);
               TakeProfitPrice = NormalizeDouble(OpenPrice + TakeProfit * nDigits, Digits);
            }
            if (OrderType() == OP_SELL)
                        {
               StopLossPrice = NormalizeDouble(OpenPrice + StopLoss * nDigits, Digits);
               TakeProfitPrice = NormalizeDouble(OpenPrice - TakeProfit * nDigits, Digits);
            }         
            // Order expiration is a required parameter, so pass the current value via OrderExpiration() function.
                        if (OrderModify(OrderTicket(), OpenPrice, StopLossPrice, TakeProfitPrice, OrderExpiration()))
                        {
               // If the order is updated correctly, increment the counter of updated orders.
                           TotalUpdated++;
            }
            else
                        {
               // If the order fails to get updated, print the error.
                           Print("Order failed to update with error: ", GetLastError());
            }
         }
     }
      // If the OrderSelect() fails, return the cause.
      else
          {
         Print("Failed to select the order: ", GetLastError());
      }  
      
      // You can add delay if execution is too fast. Sleep() will wait X milliseconds before proceeding with the code.
      // Sleep(300);
   }
   // If the loop finishes, it means there were no more open orders for that pair.
   return(TotalUpdated);
}

void OnStart()
{
   Print("How many orders have been modified? ", UpdateOpenOrders());
}

If there are some active orders in different pairs, you can see that only the orders of the same currency pair of where the script is running are modified.

Multiple Orders in Multiple Currency Pairs

If you execute the script, it will show the following input parameters window:

OrderModify() MQL4 Script - Input Parameters

Running it on the EUR/USD chart will produce the following result:

Modifying Two Orders with Script List of Orders After Modification

While on the USD/JPY chart, the results are the following:

Modification of Two USD/JPY Orders with Test Script Resulting Orders with Stop-Loss and Take-Profit

Being able to update orders is usually a fundamental feature for an expert advisor. Moreover, some expert advisors actually exist to only do that. If you take some time to understand the code presented in this guide and test it with your orders, you will do yourself a great favor to prepare for development of more complex trading programs.

 

If you want to save hours of research and coding and if you want to see some professional code, you can have a look at our MT4 Expert Advisor Template. You can even use it to build your own EA!