Classic MQL4 trade API

MQL4 order functions and the selection model

Classic MQL4 order properties are read from the order most recently loaded by OrderSelect. Select a position or ticket successfully before calling OrderTicket, OrderType, OrderLots, or other property functions, and reselect before acting on data that may have changed.

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

InspectOpenOrders.mq4.mq4
#property strict

void OnStart()
  {
   int total = OrdersTotal();
   Print("Open and pending orders: ", total);

   for(int position = 0; position < total; position++)
     {
      if(!OrderSelect(position, SELECT_BY_POS, MODE_TRADES))
        {
         Print("OrderSelect failed at position ", position,
               ". Error ", GetLastError());
         continue;
        }

      PrintFormat("ticket=%d symbol=%s type=%d lots=%.2f magic=%d",
                  OrderTicket(), OrderSymbol(), OrderType(),
                  OrderLots(), OrderMagicNumber());
     }
  }
  • OrdersTotal counts the active trade pool
  • OrderSelect loads an order snapshot
  • OrderSend returns a ticket or minus one
  • Every mutation needs result handling

OrderSelect controls every property read

SELECT_BY_POS interprets the first argument as a pool position. SELECT_BY_TICKET interprets it as the unique ticket and ignores the pool argument. MODE_TRADES contains open and pending orders; MODE_HISTORY contains closed and deleted orders.

Property functions do not accept a ticket parameter because they read the selected order snapshot. Reselect before using price, lots, stops, or expiration in a later operation.

FunctionPrimary resultFailure handling
OrdersTotalActive market and pending countDo not assume stable positions after mutation
OrderSelectLoads one order snapshotSkip all property reads on false
OrderSendNew ticket or -1Read GetLastError and broker constraints
OrderModifytrue or falseCheck changed values and freeze rules
OrderClosetrue or falseLog ticket, price, lots, and error

OrderType separates market and pending behavior

OP_BUY and OP_SELL are opened market orders. OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, and OP_SELLSTOP are pending orders. A management loop must branch by type before choosing Bid, Ask, OrderClose, OrderModify, or OrderDelete.

Order ownership also needs OrderSymbol and OrderMagicNumber filters. Account-wide code without those filters can act on manual trades or another EA.

  • Select before every group of property reads
  • Do not depend on SELECT_BY_POS sorting
  • Iterate backward when deleting or closing entries
  • Check trade permission, price, stop, and volume constraints

Trade return codes are part of the implementation

OrderSend returning a ticket does not prove the strategy is correct, and a false mutation result should not be silently retried. Record the error, decide which failures are retryable, refresh market data when relevant, and prevent duplicate requests.

A complete EA test covers order rejection, requotes, disconnection, symbol suffixes, lot steps, stop levels, and terminal restart state.

Review the complete example

The script is read-only. It counts the active pool, selects each position, and reads properties only after selection succeeds. The server does not guarantee a sorted SELECT_BY_POS sequence.

The example only inspects orders. Adding trade mutations changes account state and requires explicit ownership filters, broker constraints, and demo validation.

InspectOpenOrders.mq4.mq4
#property strict

void OnStart()
  {
   int total = OrdersTotal();
   Print("Open and pending orders: ", total);

   for(int position = 0; position < total; position++)
     {
      if(!OrderSelect(position, SELECT_BY_POS, MODE_TRADES))
        {
         Print("OrderSelect failed at position ", position,
               ". Error ", GetLastError());
         continue;
        }

      PrintFormat("ticket=%d symbol=%s type=%d lots=%.2f magic=%d",
                  OrderTicket(), OrderSymbol(), OrderType(),
                  OrderLots(), OrderMagicNumber());
     }
  }
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

    Choose the pool

    Use MODE_TRADES for active orders or MODE_HISTORY for account history.

  2. 2

    Select and filter

    Load the order, then check symbol, magic number, close time, and type.

  3. 3

    Perform one operation

    Call the matching send, modify, close, or delete function with normalized parameters.

  4. 4

    Handle the returned result

    Log failures and apply a bounded retry policy only where justified.

Frequently asked questions

What does OrderSelect do in MQL4?

OrderSelect loads one order’s data into the program environment so property functions can read that selected snapshot.

What is the difference between SELECT_BY_POS and SELECT_BY_TICKET?

SELECT_BY_POS uses a pool position. SELECT_BY_TICKET uses the unique order ticket and ignores the pool argument.

What does OrdersTotal include?

OrdersTotal counts both opened market orders and pending orders in the active trading pool.

How do I tell whether an MQL4 order is pending?

After successful selection, inspect OrderType. Values other than OP_BUY and OP_SELL in MODE_TRADES are pending types.

Why should I reselect an order before modifying it?

Selected properties are copied values that may become stale. Reselect to obtain the current order snapshot before acting.

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