MQL4 order management

Close all orders in MQL4 without closing the wrong trades

Iterate the open-order pool backward, call OrderSelect before reading each order, exclude pending orders unless deletion is intended, filter by symbol and magic number, refresh prices, and check every OrderClose result. “All” must be defined before any account-wide action.

Open the Coding Agent, then choose MQL4 from the language menu.

CloseFilteredOrders.mq4.mq4
#property strict
#property script_show_inputs

input bool CurrentSymbolOnly = true;
input int  MagicNumber       = -1;
input int  SlippagePoints    = 3;

void OnStart()
  {
   for(int position = OrdersTotal() - 1; position >= 0; position--)
     {
      if(!OrderSelect(position, SELECT_BY_POS, MODE_TRADES))
        {
         Print("OrderSelect failed. Error ", GetLastError());
         continue;
        }

      if(CurrentSymbolOnly && OrderSymbol() != Symbol())
         continue;
      if(MagicNumber >= 0 && OrderMagicNumber() != MagicNumber)
         continue;
      if(OrderType() != OP_BUY && OrderType() != OP_SELL)
         continue;

      RefreshRates();
      double close_price = (OrderType() == OP_BUY) ? Bid : Ask;
      close_price = NormalizeDouble(close_price, Digits);

      if(!OrderClose(OrderTicket(), OrderLots(), close_price,
                     SlippagePoints, clrNONE))
         Print("OrderClose failed for #", OrderTicket(),
               ". Error ", GetLastError());
     }
  }
  • Iterate the order pool backward
  • Select before reading order fields
  • Filter symbol and magic number
  • Log every failed close

Define what close all means on the account

OrdersTotal includes open market orders and pending orders in the trading pool. OrderClose closes an opened market order; pending orders require OrderDelete. Mixing those operations without an explicit rule can remove orders that belong to another strategy.

A production rule should name the symbol scope, magic number, order types, partial-close behavior, slippage in points, and what happens after a rejected close. Manual trades commonly use magic number zero, while an EA should normally own a dedicated number.

FilterWhy it mattersExample choice
OrderSymbolPrevents cross-symbol closureCurrent chart symbol only
OrderMagicNumberSeparates strategy ownershipExact EA magic number
OrderTypeSeparates market and pending ordersOP_BUY and OP_SELL only
OrderLotsControls full or partial closeFull selected volume

Why reverse iteration and fresh selection matter

Closing an order changes the pool. Iterating from OrdersTotal minus one down to zero avoids skipping the next position after removal. Each pass still needs a successful OrderSelect before reading ticket, type, lots, or symbol.

OrderSelect copies order data into the program environment. MetaQuotes recommends selecting again before requesting properties because previously copied values can become stale.

  • Continue after an individual failure only when that policy is intentional
  • Read GetLastError immediately after the failed operation
  • Do not reuse a ticket or lot size from a failed selection
  • Test hedged accounts and partial fills in the target broker environment

Closing code is an account mutation

A syntactically valid loop can still close the wrong exposure. Run the exact filters on a demo account with mixed symbols, manual orders, multiple magic numbers, and pending orders before considering live use.

Broker rules can reject price, volume, or freeze-level conditions. A close-all routine therefore needs logs and a visible completion policy rather than assuming one pass succeeded.

Review the complete example

This script closes market orders only. It defaults to the current chart symbol, supports an optional magic-number filter, skips pending orders, iterates backward, refreshes Bid and Ask, and reports individual failures.

Running this script can close real market orders. Review every filter, compile it locally, and verify it on a demo account containing mixed order types before any live use.

CloseFilteredOrders.mq4.mq4
#property strict
#property script_show_inputs

input bool CurrentSymbolOnly = true;
input int  MagicNumber       = -1;
input int  SlippagePoints    = 3;

void OnStart()
  {
   for(int position = OrdersTotal() - 1; position >= 0; position--)
     {
      if(!OrderSelect(position, SELECT_BY_POS, MODE_TRADES))
        {
         Print("OrderSelect failed. Error ", GetLastError());
         continue;
        }

      if(CurrentSymbolOnly && OrderSymbol() != Symbol())
         continue;
      if(MagicNumber >= 0 && OrderMagicNumber() != MagicNumber)
         continue;
      if(OrderType() != OP_BUY && OrderType() != OP_SELL)
         continue;

      RefreshRates();
      double close_price = (OrderType() == OP_BUY) ? Bid : Ask;
      close_price = NormalizeDouble(close_price, Digits);

      if(!OrderClose(OrderTicket(), OrderLots(), close_price,
                     SlippagePoints, clrNONE))
         Print("OrderClose failed for #", OrderTicket(),
               ". Error ", GetLastError());
     }
  }
Where Pineify fits

Move from the rule to editable MQL4 source

Pineify can generate or revise one self-contained .mq4 file with MQL4-specific reference context. Its independent static checker returns MetaEditor diagnostics so you can repair source issues before testing in your own MT4 environment.

Open MQL4 Coding Agent

Static diagnostics do not prove runtime behavior, backtest results, broker compatibility, or live-trading safety.

Pineify MQL4 Coding Agent with MQL4 selected and an editable MetaTrader 4 code artifact

A practical workflow

  1. 1

    Define ownership

    Choose symbol, magic number, and order types before traversing the pool.

  2. 2

    Select each order

    Iterate backward and skip every position that OrderSelect cannot load.

  3. 3

    Choose the close price

    Refresh rates and use Bid for buys and Ask for sells on the selected symbol.

  4. 4

    Record each result

    Log the ticket and GetLastError value for every rejected close.

Frequently asked questions

How do I close all open orders in MQL4?

Loop from OrdersTotal minus one down to zero, select each MODE_TRADES entry, filter it, and call OrderClose only for OP_BUY or OP_SELL.

Does OrderClose remove pending orders?

No. OrderClose is for opened market orders. Pending orders use OrderDelete and should have a separate explicit rule.

Why loop backward through MQL4 orders?

Closing an order changes the pool. Reverse iteration reduces the risk of skipping a position after removal.

How do I close only one EA’s orders?

Filter OrderMagicNumber and usually OrderSymbol after every successful OrderSelect call.

Can every order close succeed in one pass?

No. Prices, volume rules, connection state, trade context, freeze levels, and broker responses can reject individual operations.

Last verified against the linked official references on . Compile and test the final source in the MetaTrader 4 build, broker, symbol, and account environment you plan to use.

Continue with one reviewable MQL4 file

Define the requirement, inspect the generated source, repair diagnostics, and test the behavior in your own MT4 environment.

Open Coding Agent