Steps for Developing an EA

Basic Structure of an EA

An EA (Expert Advisor) is an automated trading program that runs on MetaTrader. Typically, an EA is composed of the following three main functions:

  • OnInit function: Executed when the EA is initialized.
  • OnDeinit function: Executed when the EA is removed.
  • OnTick function: Executed every time a new tick occurs.

Initial Settings (OnInit Function, OnDeinit Function)

The initial settings of an EA include functions for initialization and termination processes.

OnInit Function

The OnInit function is executed only once when the EA is applied to a chart. This is where initial settings and global variable initialization are performed.

//MQL4
int OnInit() {
    // Initialization code
    Print("EA Initialized");
    return INIT_SUCCEEDED;
}

OnDeinit Function

The OnDeinit function is executed only once when the EA is removed from the chart. This is where resource release and termination processes are performed.

//MQL4
void OnDeinit(const int reason) {
    // Termination code
    Print("EA Deinitialized");
}

Implementation of Trade Logic (OnTick Function)

The OnTick function is the main function that is executed every time a new tick occurs. This is where the trade logic is written.

//MQL4
void OnTick() {
    // Trade logic
    double ma = iMA(NULL, 0, 14, 0, MODE_SMA, PRICE_CLOSE, 0);
    double price = Close[0];

    if (price > ma) {
        OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0, "Buy Order", 0, 0, Blue);
    } else if (price < ma) {
        OrderSend(Symbol(), OP_SELL, 0.1, Bid, 3, 0, 0, "Sell Order", 0, 0, Red);
    }
}

Compilation and Testing

After creating the EA, compile the code to check for errors and then use the Strategy Tester to backtest and verify the EA’s performance.

Compilation

After editing the code in MetaEditor, click the “Compile” button on the toolbar to compile the code. If there are any errors, they will be displayed in the error log for correction.

Testing

  1. Launch the Strategy Tester: Select “Strategy Tester” from the MetaTrader toolbar.
  2. Test Settings: Set the EA, currency pair, period, initial capital, etc., to be tested.
  3. Execute Backtest: Click the “Start” button to begin the test and check the results.

Notes

  • For Educational Purposes: This sample code is provided for understanding the basics of MQL4 programming.
  • Disclaimer: The site and the author are not responsible for any damages arising from the use of this code.
  • Prohibition of Use on Real Accounts: Use the sample code only in a test environment (demo account) and avoid using it on real accounts.