Skip to content

Module 02 · Idea to live, in order · Lesson 07

From rules to code: the shape of a clean EA

Inputs at the top, handles in OnInit, a short OnTick that reads like your rule list, one helper per job.

6 minute read

Make the code read like the rules

A good EA's OnTick reads almost like your written rules: is it a new bar? has the daily loss limit been hit? are we in session? are the entry rules met? how many positions are open? then size and send. Each question is a small helper function you can test and read on its own.

MQL5
void OnTick()
{
   if(!IsNewBar())          return;   // closed-bar logic
   if(DailyLossReached())   return;   // risk first
   if(!InSession())         return;
   if(SpreadTooWide())      return;

   int dir = RulesDirection();        // +1 long rules met, -1 short, 0 none
   if(dir == 0)             return;
   if(CountMyPositions() >= InpMaxPositions) return;

   OpenWithRisk(dir);                 // stop first, then size, then send
}

Inputs are your dials

Everything you might change — periods, thresholds, risk, sessions, magic number — becomes an input variable. Inputs appear in the EA's settings window and in the Strategy Tester's optimisation tab. Fewer inputs means fewer ways to fool yourself.

Fail safe, not silent

If a CopyBuffer call fails, if the lot size rounds below the broker minimum, if a stop would be too close — do nothing and Print why. An EA that guesses when data is missing is an EA that eventually guesses wrong with real money.

Takeaways

  • OnTick should read like your rule list.
  • Every adjustable number is an input.
  • When something is missing, skip the trade and log why.
Check your understanding

One-question check

CopyBuffer returns 0 values for your RSI. What should the EA do?

Your rules, our teaching. MarketPanda provides no strategy, no settings that “work” and no signals. Everything here is education; nothing is a recommendation to trade.

Content source: Bundled MarketPanda content.