Summary: Advanced guide to MQL4 OrderSend function covering slippage management, return code analysis, and automatic retry mechanisms. Includes fail-safe order execution patterns for professional EA development.




The `OrderSend()` function is the heart of any MQL4 trading EA, yet most implementations ignore proper error handling and slippage control. A robust `OrderSend()` wrapper separates professional EAs from amateur ones.

1. Function Signature And Return Value Analysis

```cpp
int OrderSend(
string symbol, // symbol
int cmd, // operation type
double volume, // lot size
double price, // order price
int slippage, // allowed slippage in points
double stoploss, // stop loss level
double takeprofit, // take profit level
string comment, // order comment
int magic, // EA identifier
datetime expiration, // pending order expiration
color arrow_color // arrow color on chart
);
```

Return value: ticket number on success, -1 on failure. Always check `GetLastError()` immediately after.

2. Slippage Control Formula

Maximum allowed price deviation = `Ask ± slippage * Point`. For buy orders:
```cpp
double currentAsk = Ask;
double maxAcceptableAsk = currentAsk + slippage * Point;
if(maxAcceptableAsk >= currentAsk) {
ticket = OrderSend(Symbol(), OP_BUY, lot, currentAsk, slippage, 0, 0, "EA", magic);
}
```

3. Production-Grade OrderSend Wrapper

```cpp
int SendOrderWithRetry(int cmd, double volume, double price, int slippage,
double sl, double tp, int magic, int maxRetries = 3) {
int ticket = -1;
int retryCount = 0;

while(retryCount < maxRetries) {
ticket = OrderSend(Symbol(), cmd, volume, price, slippage, sl, tp,
"SecureEA", magic, 0, clrNONE);
int error = GetLastError();

if(ticket > 0) {
Print("Order placed successfully. Ticket: ", ticket);
return ticket;
}

Print("Attempt ", retryCount + 1, " failed. Error: ", error, " - ", ErrorDescription(error));

// Handle specific errors with different backoff strategies
switch(error) {
case ERR_SERVER_BUSY: // 134
case ERR_NO_CONNECTION: // 134
case ERR_TRADE_CONTEXT_BUSY: // 146
case ERR_PRICE_CHANGED: // 135
Sleep(1000 * (retryCount + 1)); // exponential backoff
RefreshRates(); // update market data
break;
case ERR_INVALID_PRICE: // 138
price = (cmd == OP_BUY) ? Ask : Bid; // recalc price
RefreshRates();
break;
default:
Print("Fatal error, no retry.");
return -1;
}
retryCount++;
}
return -1;
}
```

4. Error Code Reference

| Error Code | Constant | Meaning | Recovery Action |
|------------|----------|---------|-----------------|
| 1 | ERR_NO_RESULT | No error | Continue |
| 2 | ERR_COMMON_ERROR | Generic error | Refresh rates |
| 129 | ERR_INVALID_PRICE | Invalid price | Recalculate |
| 130 | ERR_INVALID_STOPS | Invalid stops | Adjust SL/TP distance |
| 131 | ERR_INVALID_TRADE_VOLUME | Invalid volume | Normalize lot size |
| 134 | ERR_NOT_ENOUGH_MONEY | Insufficient funds | Reduce volume |

5. Normalize Lot Size Function

```cpp
double NormalizeLot(double requestedLot) {
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double stepLot = MarketInfo(Symbol(), MODE_LOTSTEP);

double normalized = MathFloor(requestedLot / stepLot) * stepLot;
normalized = MathMax(minLot, MathMin(maxLot, normalized));

return NormalizeDouble(normalized, 2);
}
```

6. Complete Order Opening Pattern

```cpp
bool OpenBuyOrder(double lot, int slippagePoints, double slPoints, double tpPoints, int magic) {
RefreshRates();
double price = Ask;
double stoploss = (slPoints > 0) ? price - slPoints * Point : 0;
double takeprofit = (tpPoints > 0) ? price + tpPoints * Point : 0;
double normalizedLot = NormalizeLot(lot);

if(stoploss > 0 && price - stoploss < MarketInfo(Symbol(), MODE_STOPLEVEL) * Point) {
Print("Stop loss too close to market price");
return false;
}

int ticket = OrderSend(Symbol(), OP_BUY, normalizedLot, price, slippagePoints,
stoploss, takeprofit, "EA_Buy", magic, 0, clrGreen);

if(ticket < 0) {
Print("OrderSend failed. Error: ", GetLastError());
return false;
}

Print("Buy order opened. Ticket: ", ticket, " Price: ", price);
return true;
}
```

Reference: MQL4 Documentation, "OrderSend" (docs.mql4.com/trading/OrderSend); Kovalyov, Alexander. "MQL4 Programming for Traders," 2019.