How to start learning to make EAs (best guide for beginners?)

 

Hi, I started trying to make EAs for the first time just by going through  MQL5 articles like this one:

https://www.mql5.com/en/articles/367


This talked about making a signal script (.mqh) for the EA wizard. They inherit the CExpertSignal baseclass and then override the LongCondition and ShortCondition functions from CExpertSignal.

The goal was to generate signals when two MA lines intersect, but I found that I had little control without using CopyBuffer because it started generating buys and sells 2 or 3 bars after the line intersection and this wasn't effective. So ultimately, it was an unusable EA which mostly causes losses.

I saw that other people inherit the Trade baseclass and do things a completely different way with "trade.Buy()" and "trade.Sell()" directly called in the EA script. I'm really confused now about how to get started, or which is the best approach to take.

If you could give me some advice, or resources to start with, I would appreciate it!

Create Your Own Trading Robot in 6 Steps!
Create Your Own Trading Robot in 6 Steps!
  • www.mql5.com
If you don't know how trade classes are constructed, and are scared of the words "Object Oriented Programming", then this article is for you. In fact, you do not need to know the details to write your own module of trading signals. Just follow some simple rules. All the rest will be done by the MQL5 Wizard, and you will get a ready-to-use trading robot!
 
phade:

Hi, I started trying to make EAs for the first time just by going through  MQL5 articles like this one:

https://www.mql5.com/en/articles/367


This talked about making a signal script (.mqh) for the EA wizard. They inherit the CExpertSignal baseclass and then override the LongCondition and ShortCondition functions from CExpertSignal.

The goal was to generate signals when two MA lines intersect, but I found that I had little control without using CopyBuffer because it started generating buys and sells 2 or 3 bars after the line intersection and this wasn't effective. So ultimately, it was an unusable EA which mostly causes losses.

I saw that other people inherit the Trade baseclass and do things a completely different way with "trade.Buy()" and "trade.Sell()" directly called in the EA script. I'm really confused now about how to get started, or which is the best approach to take.

If you could give me some advice, or resources to start with, I would appreciate it!

Hi there. Its good to hear that you are starting out as a developer, i can give you some tips and examples on how to approach your journey

I understand your confusion, and creating a successful trading EA can be challenging due to the complexities of market behavior and the need for accurate signal generation. Let's break down the different approaches and provide some guidance on how to proceed:

  1. Indicator-based Approach with CopyBuffer :

    • If you're using moving averages (MAs) and want to generate signals when they intersect, an indicator-based approach using CopyBuffer can provide accurate signal generation. This involves creating a custom indicator that calculates the MA values and then using those values to determine the intersections.
    • This method offers more control over the signal generation process and can be optimized to trigger signals precisely when the intersection occurs.
  2. Direct trade.Buy() and trade.Sell() Approach:

    • Some traders prefer to use a more simplified approach by directly using trade.Buy() and trade.Sell() functions within the EA script without relying on custom indicators. This approach can work well for simple strategies and when speed of execution is crucial.
    • However, it may require more manual intervention to handle factors like position sizing, stop loss, take profit, and risk management.

Choosing the best approach depends on your trading strategy, your programming skills, and your understanding of the market. Here are some steps to consider:

  1. Clarify Your Strategy:

    • Understand your trading strategy in detail. Know when you want to enter and exit trades based on the MA intersections. Determine whether you need additional conditions for filtering signals.
  2. Custom Indicator:

    • If accuracy and control are important, consider creating a custom indicator to identify MA intersections. This involves coding the logic for signal generation using CopyBuffer . This approach may require more programming knowledge but can provide accurate results.
  3. Simplified Approach:

    • If you prefer a more straightforward approach, you can use the trade.Buy() and trade.Sell() functions directly in the EA script. This approach might be quicker to implement but may lack the precision of a custom indicator.
  4. Risk Management:

    • Regardless of the approach, ensure you incorporate proper risk management techniques. This includes setting stop-loss and take-profit levels, calculating position sizes based on risk percentage, and considering overall portfolio risk.
  5. Backtesting and Optimization:

    • Whichever approach you choose, thoroughly backtest your strategy on historical data to evaluate its performance. Optimize parameters and test the strategy under various market conditions.
  6. Learning Resources:

    • To get started, you can refer to the MQL documentation and online tutorials. Consider resources like forums, YouTube videos, and courses that cover both indicator-based and direct trading approaches.

Remember that building a successful trading EA takes time and iteration. It's common to experience losses during testing phases, but the goal is to refine and improve your strategy over time. As you gain experience, you'll become more adept at making informed decisions about which coding techniques suit your strategy best.

Here is an example of the functions used in your case.

// Define input parameters
input int fastMAPeriod = 10;  // Fast Moving Average period
input int slowMAPeriod = 20;  // Slow Moving Average period

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Add fast and slow MAs to the chart
   iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
   iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
   
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Remove MAs from the chart
   ObjectsDeleteAll();
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   double fastMA = iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
   double slowMA = iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
   
   // Check for intersection
   if (fastMA > slowMA)
     {
      // Place a buy order
      double lotSize = 0.1;  // Set your desired lot size
      double stopLoss = 50;  // Set your desired stop loss distance in pips
      double takeProfit = 100;  // Set your desired take profit distance in pips
      
      trade.Buy(lotSize, NULL, Ask, stopLoss, takeProfit, "Buy Order", 0, 0, clrNONE);
     }
   else if (fastMA < slowMA)
     {
      // Place a sell order
      double lotSize = 0.1;  // Set your desired lot size
      double stopLoss = 50;  // Set your desired stop loss distance in pips
      double takeProfit = 100;  // Set your desired take profit distance in pips
      
      trade.Sell(lotSize, NULL, Bid, stopLoss, takeProfit, "Sell Order", 0, 0, clrNONE);
     }
  }

If i can break it down for you, IF this will help you to understand the structure.

These lines define the input parameters for the EA. you can set the periods for the fast and slow moving averages when attaching the EA to a chart.

input int fastMAPeriod = 10;
input int slowMAPeriod = 20;

Next we have the Initialization function

int OnInit()
{
    iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
    iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    
    return(INIT_SUCCEEDED);
}

Then set out next is the DeInit() function.  This function is called when the EA is removed from the chart. It removes any graphical objects that were added to the chart, such as the moving average lines in this case.

void OnDeinit(const int reason)
{
    ObjectsDeleteAll();
}

Lastly we have the tick function, 

This function is called on each tick of the price data. It calculates the current values of the fast and slow moving averages using the same iMA function. Then, it checks whether the fast moving average is above the slow moving average ( fastMA > slowMA ) or below it ( fastMA < slowMA ).

  • If the fast moving average is above the slow moving average, the code inside the if block is executed. This code generates a buy order using the trade.Buy() function.
  • If the fast moving average is below the slow moving average, the code inside the else if block is executed. This code generates a sell order using the trade.Sell() function.
void OnTick()
{
    double fastMA = iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
    double slowMA = iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    
    if (fastMA > slowMA)
    {
        // Buy order code
    }
    else if (fastMA < slowMA)
    {
        // Sell order code
    }
}
I hope this helps. Have a nice day.
 

Hi, thanks for your post, just to say - I have a few years experience with software programming so I'm well aware of class structure, variable types and so on. I also programmed my own MT5 indicator, but I'm very new to MQL5 and have never approached making an EA from scratch yet.

I like the simplified approach you posted, I guess it is better for this use case than using .mqh signal script? Perhaps the article I found was just to reveal how to construct a signal script, and not so much about the best way to make this kind of EA. The EA I made with the EA wizard didn't work well in the strategy tester

 
Nardus Van Staden #:
int OnInit()
  {
   // Add fast and slow MAs to the chart
   iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
   iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
void OnTick()
  {
   double fastMA = iMA(Symbol(), 0, fastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 0);
   double slowMA = iMA(Symbol(), 0, slowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
   
   // ...
      
      trade.Buy(lotSize, NULL, Ask, stopLoss, takeProfit, "Buy Order", 0, 0, clrNONE);

What are you doing it for? Why are you posting garbage that chatgpt generated for you here? What you are doing is confusing people, not helping.

You can post anything you want. But, if you publish generated garbage, then at least warn about it: "Here is what chatgpt answered your question:"

 
phade:

Hi, I started trying to make EAs for the first time just by going through  MQL5 articles like this one:

https://www.mql5.com/en/articles/367


This talked about making a signal script (.mqh) for the EA wizard. They inherit the CExpertSignal baseclass and then override the LongCondition and ShortCondition functions from CExpertSignal.

The goal was to generate signals when two MA lines intersect, but I found that I had little control without using CopyBuffer because it started generating buys and sells 2 or 3 bars after the line intersection and this wasn't effective. So ultimately, it was an unusable EA which mostly causes losses.

I saw that other people inherit the Trade baseclass and do things a completely different way with "trade.Buy()" and "trade.Sell()" directly called in the EA script. I'm really confused now about how to get started, or which is the best approach to take.

If you could give me some advice, or resources to start with, I would appreciate it!

Perhaps you will find something useful here:

https://www.mql5.com/en/forum/212020

 
Vladislav Boyko #:

Perhaps you will find something useful here:

https://www.mql5.com/en/forum/212020

Thanks

Reason: