Module 01 · How an EA works · Lesson 04
Orders, positions and magic numbers
How an EA sends trades with CTrade, why every EA needs its own magic number, and what netting vs hedging accounts change.
6 minute read
Orders become deals become positions
In MT5 you send an order (a request). When it fills, the broker records a deal. Deals open, add to or close a position. Your EA mostly cares about positions: what is open, in which direction, with which stop.
The standard library class CTrade wraps the low-level OrderSend call and fills in the request for you.
#include <Trade/Trade.mqh>
CTrade trade;
int OnInit()
{
trade.SetExpertMagicNumber(260001); // this EA's signature
trade.SetDeviationInPoints(10); // max slippage accepted
return(INIT_SUCCEEDED);
}
// later, with a stop loss (sl) and optional take profit (tp):
if(!trade.Buy(lots, _Symbol, 0.0, sl, tp, "my rules"))
PrintFormat("Buy failed: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
The magic number
Every order an EA sends can carry a number of your choosing. When the EA later counts or closes "its" positions, it filters by symbol and magic number, so it never touches your manual trades or another EA's positions. Two EAs with the same magic number on the same symbol will fight over each other's trades.
Netting or hedging account?
On a netting account there is one position per symbol; a sell against an open buy reduces it. On a hedging account each trade is its own position, and buys and sells can coexist. Code that counts positions must work on the account type your broker gives you — check it with AccountInfoInteger(ACCOUNT_MARGIN_MODE).
Always check the result
Orders get rejected: market closed, not enough margin, stop too close to price, volume not a multiple of the lot step. An EA that ignores the return value of trade.Buy will believe it is in a trade it never opened.
Takeaways
- CTrade is the standard way to send orders in MQL5.
- Give each EA its own magic number and filter by it.
- Check every trade result; rejections are normal.
Primary references
Your rules, our teaching. MarketPanda provides no strategy, no settings that “work” and no signals. Everything here is education; nothing is a recommendation to trade.
Content source: Bundled MarketPanda content.