MQL4 BASICS COURSE

Coding, Testing, and Debugging Your EA

Once you've planned and structured your Expert Advisor (EA), the next steps involve writing the code, testing its functionality, and resolving any errors or bugs. This stage is critical to ensure that your EA functions correctly in real-time trading environments.

1. Start with the Basic Structure

Begin by laying out the foundational structure of your MQL4 Expert Advisor (EA), which includes three core functions:

  1. Initialization Function – OnInit(): This function runs when the EA is first attached to a chart or when the chart's timeframe is changed. It’s typically used to initialize variables, set default parameters, or draw objects on the chart. For example, you might want to set some global settings, create labels, or define initial values here. You can also leave it empty if no setup is required.
  2. Main Function – OnTick(): This is the core of your EA, executed every time a new tick (price update) arrives. Place all logic that should be checked continuously here — such as trade entry conditions, signal evaluations, trailing stops, or order management.

    Example:
    void OnTick() {
      // Your trading logic goes here
    }
  3. Deinitialization Function – OnDeinit(const int reason): This function is triggered when the EA is removed from the chart or the terminal is shut down. It's used for cleanup tasks like deleting chart objects or closing file handles. For instance, you might want to clear all objects created by your EA so the chart stays clean after it's removed.

// MQL4 code example
int OnInit() {
    // Initialization code here
    return(INIT_SUCCEEDED);
}

void OnTick() {
    // Main trading logic here
}

void OnDeinit(const int reason) {
    // Cleanup code here
}

2. Incorporate Trading Logic

Integrate the trading rules and criteria you've defined. Ensure you handle:

3. Implement Error Handling

While coding your EA, you should anticipate potential errors that could arise during its operation. These errors could be due to various reasons, such as server disconnections, rejected orders, or insufficient margin. Proper error handling ensures that your EA can respond gracefully to unexpected situations without crashing or causing unintended behavior.

1. Check for Errors After Trade Operations

Every time your EA tries to place a trade (like a buy or sell order), it uses a function like OrderSend(). This function returns a **ticket number** if the trade was successful.

However, if the trade fails, it returns -1. That means something went wrong — maybe you don't have enough margin, the broker rejected the order, or trading is disabled.

To find out what happened, you can use GetLastError() to get the error code, and ErrorDescription() to print out a human-readable explanation. This makes it much easier to troubleshoot.

// MQL4 code example
double lotSize = 0.1;
int ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 3, 0, 0, "Buy Order", 0, 0, Green);

if (ticket == -1) {
    int lastError = GetLastError();
    Print("❌ OrderSend failed with error (", lastError, "): ", ErrorDescription(lastError));
} else {
    Print("✅ Order placed successfully. Ticket #: ", ticket);
}

Tip: You should always check if ticket == -1 after placing a trade, especially during testing or if your EA is running on a live account.

2. Define Actions in Response to Specific Errors

Once you've identified an error, you should decide how your EA will handle it. Common actions in response to errors include retrying the operation, logging the error, or sending a notification to alert you.

For instance, if an order is rejected because of a temporary issue, your EA might wait for a few seconds and then try again. If the problem persists, it might then send a notification to alert you of the issue.


// MQL4 code example for handling specific errors
int lastError = GetLastError();

switch(lastError) {
    case ERR_SERVER_BUSY:
    case ERR_NO_CONNECTION:
        Print("Temporary issue. Retrying in 5 seconds...");
        Sleep(5000);  // Wait for 5 seconds
        // Retry the operation here
        break;

    case ERR_NOT_ENOUGH_MONEY:
        Print("Insufficient funds to execute the trade.");
        // Send notification or take other actions
        break;

    // Handle other errors as needed...

    default:
        Print("An unknown error occurred: ", lastError);
        // Handle unexpected errors
        break;
}

Proper error handling ensures that your EA remains stable and reliable even under unforeseen circumstances. It's always better to be prepared for potential issues than to be caught off guard.


4. Test in Strategy Tester

MetaTrader 4 offers a built-in Strategy Tester. Here, you can:

After coding your EA, it's essential to test it to ensure it works as expected. MQL4 provides a built-in strategy tester that lets you simulate how your EA would have performed over historical data.

To test your EA:

  1. Open the Strategy Tester panel in MetaTrader 4.
  2. Select your EA from the list.
  3. Choose your desired settings and historical data period.
  4. Click the "Start" button to begin the test.

Once the test is finished, you can analyze the results to see how your EA performed by checking the "journal" tab of the strategy tester.

MT4 STRATEGY TESTER JOURNAL TAB

To check your EA live, check the "Experts" tab at the bottom of the "terminal".

This will show you any errors encountered in the EA and will also show any Printouts you have placed in the EA for problem solving.

The journal tab is the same as the "experts" tab you find at the bottom of the "terminal".


5. Debugging with the MetaEditor

As with all coding projects, you're likely to encounter bugs:

Debugging is the process of finding and resolving any errors or issues in your EA’s code. These can range from syntax errors (which prevent the code from running at all) to logical errors, where the code runs but doesn’t produce the expected results.

The All-Powerful Print(); Function

In MQL4, you can use the Print(); function to output messages to the terminal. This is useful for tracking the flow of your code and for displaying variable values to help diagnose issues.

Anytime you find yourself scratching your head while coding your EA, it’s time to use the Print(); function.

// MQL4 code example for debugging your EA
void OnTick() {
    double RSI = iRSI(NULL, 0, 14, PRICE_CLOSE, 1);
    double CurrentPrice = Close[0];
    double CloseOfBar5 = Close[5];

    if (RSI > 70.0 && CurrentPrice > CloseOfBar5) {
        Print("Current price is: ", CurrentPrice);
        Print("RSI is: ", RSI);
        Print("Close of Bar 5 is: ", CloseOfBar5);
    }

    // Other trading logic here
}

In the example above, you can see multiple uses of the Print(); function. The condition is: if the RSI indicator is greater than 70.0 and the current price is higher than the close of the 5th previous candle, then print the current price, RSI value, and that candle’s close.

Start by writing a simple description inside the quotation marks, within the parentheses:
Print("Write your description here");
You are simply describing what you’re printing — it can be anything helpful.

You can also print variable values by adding them after the description using a comma:
Print("Close of previous candle: ", Close[1]);
This would print the value of the previous candle’s close on every tick.

To make a print function run only under specific conditions, wrap it in an if() statement, like this:
if (condition) { Print(...); }
Just like we did in the example above.

Using the Print(); function is extremely powerful. When something isn't working while coding your EA, break it all down line by line using Print(); to locate the issue.

You can find your output messages (your "printouts") in the:

Remember: the key to successful debugging is to break your code into small, manageable sections and test each one individually. This makes coding your EA much easier — and way less stressful.

6. Optimize for Performance

Once your EA code works correctly, consider performance:

Conclusion

Coding an EA involves a continuous cycle of writing, testing, and refining. As you encounter challenges, remember that each issue you resolve strengthens your EA's reliability and performance in live trading scenarios.

NEXT UP: Deploying the EA on MetaTrader 4