All Playbooks
Playbook

Debugging Common EA Errors

When your EA doesn't work, systematic debugging finds the problem. Here's how to fix the most common issues.

12 min read
Intermediate

Common OrderSend Errors

OrderSend error 130 - Invalid stops

Cause: Stop loss or take profit too close to current price

// Check minimum stop level
double minStop = MarketInfo(Symbol(), MODE_STOPLEVEL) * Point;
if (MathAbs(price - sl) < minStop) {
  sl = price - minStop; // Adjust stop
}

Prevention: Always check MODE_STOPLEVEL before placing orders

OrderSend error 131 - Invalid volume

Cause: Lot size outside allowed range or wrong step

// Normalize lot size
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
lots = MathFloor(lots / lotStep) * lotStep;
lots = MathMax(minLot, MathMin(maxLot, lots));

Prevention: Always normalize lots before OrderSend

OrderSend error 134 - Not enough money

Cause: Insufficient margin for the trade

// Check margin before trading
double marginRequired = MarketInfo(Symbol(), MODE_MARGINREQUIRED) * lots;
if (AccountFreeMargin() < marginRequired * 1.5) {
  Print("Insufficient margin");
  return;
}

Prevention: Calculate margin requirements before every trade

OrderSend error 138 - Requote

Cause: Price changed during order processing

// Retry with new price
int retries = 3;
while (retries > 0) {
  RefreshRates();
  if (OrderSend(...) > 0) break;
  retries--;
  Sleep(100);
}

Prevention: Implement retry logic with RefreshRates()

OrderSend error 145 - Modification denied

Cause: Trying to modify at same price or too close

// Check if modification actually needed
if (MathAbs(newSL - currentSL) < Point) {
  return; // No change needed
}

Prevention: Compare old and new values before modifying

Array out of range

Cause: Accessing indicator buffer with invalid index

// Always check array size
if (ArraySize(buffer) > index && index >= 0) {
  value = buffer[index];
}

Prevention: Validate indices before array access

Journal Message Reference

MessageMeaningFix
Trade is disabledAutoTrading button is off or EA not allowedEnable AutoTrading, check EA properties 'Allow live trading'
Trade context is busyAnother operation in progressAdd Sleep(100) and retry, or use trade queue
Market is closedAttempting trade outside market hoursAdd time filter: if(Hour() >= 22 || Hour() < 1) return;
Off quotesPrice not available or too oldRefreshRates() before trading, check if market is open
Invalid priceRequested price doesn't match bid/askUse Bid for sell, Ask for buy, refresh before using
No connectionLost connection to trade serverCheck IsConnected(), implement reconnection handling

Debugging Techniques

Strategic Print Statements

Add logging at key decision points

Print("Signal Check: ", signalBuy, " / ", signalSell);
Print("Spread: ", MarketInfo(Symbol(), MODE_SPREAD));
Print("Account Free Margin: ", AccountFreeMargin());
Print("Attempting order: ", lots, " lots at ", Ask);

Error Logging Function

Centralized error handling with context

void LogError(string location) {
  int error = GetLastError();
  if (error != 0) {
    Print("ERROR in ", location, ": ", error, 
          " - ", ErrorDescription(error));
  }
}

State Machine Logging

Track EA state transitions

enum EAState { WAITING, SIGNAL, ENTRY, MANAGING, EXIT };
EAState currentState = WAITING;

void SetState(EAState newState) {
  Print("State: ", EnumToString(currentState), 
        " -> ", EnumToString(newState));
  currentState = newState;
}

Trade Verification

Confirm trades executed correctly

int ticket = OrderSend(...);
if (ticket > 0) {
  if (OrderSelect(ticket, SELECT_BY_TICKET)) {
    Print("Trade confirmed: ", OrderSymbol(), 
          " @ ", OrderOpenPrice());
  }
} else {
  Print("Trade failed: ", GetLastError());
}

Troubleshooting Flow

1

Check Experts tab

Look for error messages and Print() output

2

Check Journal tab

See order execution and system messages

3

Verify AutoTrading enabled

Green button in toolbar, not red

4

Check EA properties

Allow live trading, Allow DLL if needed

5

Verify chart setup

Correct symbol, timeframe, EA attached with smiley face

6

Check market hours

Is market open for this symbol?

7

Verify connection

Connection status in bottom right corner

8

Test with Print()

Add logging to identify where code stops

Error Prevention Checklist

Error checking after every order operationCritical
Lot size normalized to broker requirementsCritical
Stop levels validated against minimum distanceCritical
Margin checked before placing trades
Retry logic for requotes implemented
Market hours filter if needed
Strategic Print() statements for debugging
Connection status checking

Common Debugging Mistakes

Not checking GetLastError() after operations

Why: Errors fail silently. You don't know what went wrong.

Fix: Call GetLastError() after every OrderSend, OrderModify, OrderClose.

Using hardcoded values for stops and lots

Why: Different brokers have different requirements. Works on one, fails on another.

Fix: Always use MarketInfo() to get broker-specific limits.

Not handling requotes and retries

Why: Single attempt fails, EA gives up. Trade never executes.

Fix: Implement retry loop with RefreshRates() and small delay.

Ignoring the Experts log tab

Why: All errors and Print() statements go there. Missing critical info.

Fix: Check Experts tab first when debugging. It's your primary tool.

Build Error-Resistant EAs

Create trading bots with proper error handling built-in from the start.

Start Building