MQL5 & MetaTrader core

Placing orders and managing positions

5 min

An EA acts on the market by sending trade requests. In MQL5 the simplest and safest way is the standard-library CTrade class, which wraps the lower-level request structures.

Using CTrade

#include <Trade/Trade.mqh>
CTrade trade;

void OpenLong()
{
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double sl  = ask - 200 * _Point;   // stop loss
    double tp  = ask + 400 * _Point;   // take profit
    trade.Buy(0.10, _Symbol, ask, sl, tp);
}

Buy and Sell open positions; PositionClose closes them; PositionModify adjusts stop loss and take profit. Always check the return value — a request can be rejected for many reasons.

Market vs pending orders

  • Market order — execute now at the current price (Buy / Sell).
  • Pending order — execute later when price reaches a level: BuyLimit, SellLimit, BuyStop, SellStop.

The netting vs hedging trap

MT5 accounts use one of two position models:

  • Netting — one net position per symbol. A buy on top of a short reduces or flips the existing position.
  • Hedging — multiple independent positions per symbol are allowed.

Your EA's logic must match the account mode, or a second order will not do what you expect. Always check before assuming you can hold opposing positions.

Things that bite real EAs

  • Stops level — brokers reject stops placed too close to price (SYMBOL_TRADE_STOPS_LEVEL).
  • Lot constraints — volume must respect the symbol's min, max and step.
  • Requotes and slippage — the fill price can differ from what you requested; never assume an exact fill.
  • Error handling — inspect trade.ResultRetcode() and react, rather than firing orders blindly. A robust EA assumes requests can fail and handles it.
Finished reading?
Risk disclaimer

This content is for educational and informational purposes only and is not investment, financial, tax or legal advice. Trading and investing carry risk, including the possible loss of capital. Any performance shown by third-party tools is hypothetical and not a promise of future results. Do your own research and consider professional advice before making any decision.