Back to course
Lesson 17Bots and automationAdvanced135 min

Build your first demo-only Expert Advisor

Create a simple demo-only moving-average EA with safety checks so you learn the workflow without pretending it is a profitable strategy.

Lesson outcomes

  • Create a basic EA file in MetaEditor.
  • Use handles and CopyBuffer for moving averages.
  • Block the EA from running on live accounts.

Workshop lab

Complete the demo, notebook, platform, or code task before treating the lesson as finished.

Evidence pack

Keep screenshots, exports, logs, calculations, or code versions in a dated learning folder.

Pass standard

You should be able to explain the failure modes, show your work, and name the stop rule.

Free education, not signals. This lesson is part of EarnSouthAfrica's free forex course. It does not tell you what to buy or sell, it does not promise income, and it should be practised on a demo account before any real-money decision.

This lesson is about workflow, not strategy. The moving-average example below is not a recommended trading system. It exists so you can learn how an EA is structured, compiled, attached to a chart, and tested safely.

The code includes a demo-account check. Keep it. If you remove safety checks before understanding the EA, you are not learning automation; you are increasing risk.

What you should be able to do after this lesson

  • Create a basic EA file in MetaEditor.
  • Use handles and CopyBuffer for moving averages.
  • Block the EA from running on live accounts.

Demo-only moving-average EA

#include <Trade/Trade.mqh>
CTrade trade;

input double Lots = 0.01;
input int FastMAPeriod = 10;
input int SlowMAPeriod = 30;
input int StopLossPoints = 300;
input int TakeProfitPoints = 600;

int fastHandle;
int slowHandle;

datetime lastBarTime = 0;

int OnInit()
{
   if(AccountInfoInteger(ACCOUNT_TRADE_MODE) != ACCOUNT_TRADE_MODE_DEMO)
   {
      Print("Demo only. This EA is blocked on live accounts.");
      return INIT_FAILED;
   }

   fastHandle = iMA(_Symbol, _Period, FastMAPeriod, 0, MODE_EMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, _Period, SlowMAPeriod, 0, MODE_EMA, PRICE_CLOSE);

   if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
   {
      Print("Could not create indicator handles.");
      return INIT_FAILED;
   }

   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   IndicatorRelease(fastHandle);
   IndicatorRelease(slowHandle);
}

void OnTick()
{
   datetime currentBar = iTime(_Symbol, _Period, 0);
   if(currentBar == lastBarTime) return;
   lastBarTime = currentBar;

   double fast[3];
   double slow[3];
   ArraySetAsSeries(fast, true);
   ArraySetAsSeries(slow, true);

   if(CopyBuffer(fastHandle, 0, 0, 3, fast) < 3) return;
   if(CopyBuffer(slowHandle, 0, 0, 3, slow) < 3) return;

   bool bullishCross = fast[1] <= slow[1] && fast[0] > slow[0];
   bool bearishCross = fast[1] >= slow[1] && fast[0] < slow[0];

   if(PositionsTotal() > 0) return;

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);

   if(bullishCross)
   {
      trade.Buy(Lots, _Symbol, ask, ask - StopLossPoints * point, ask + TakeProfitPoints * point, "Demo MA buy");
   }

   if(bearishCross)
   {
      trade.Sell(Lots, _Symbol, bid, bid + StopLossPoints * point, bid - TakeProfitPoints * point, "Demo MA sell");
   }
}

What the code does

  • Blocks live accounts by checking account trade mode.
  • Creates two exponential moving-average handles.
  • Checks once per new bar instead of firing repeatedly on every tick.
  • Looks for a simple crossover.
  • Opens only one position at a time.
  • Adds stop-loss and take-profit points.

Why this is not enough for live trading

The code does not calculate lot size from account risk, does not check spread, does not handle partial fills, does not manage broker stop-level rules deeply, does not filter news, and does not prove the strategy has an edge. It is a learning EA, not a money machine.

Academy-grade study plan

Automation is software engineering under financial pressure. The lesson standard is not 'the code compiles'; it is that the logic, risk controls, logs, tests, and failure states are explicit before the EA is trusted even on demo.

Course elementWhat you must produce
Primary artifactEA design specification
Lesson focusBuild your first demo-only Expert Advisor
Working environmentDemo account, notebook, exported platform data, or local code sandbox. Never live funds for first practice.
Completion standardYou can explain the concept, reproduce the exercise, identify failure modes, and show evidence without relying on a seller's claims.

Instructor workflow

Use this workflow as if an instructor were marking the lesson. The important question is not whether the topic sounds familiar. The question is whether your notes, screenshots, calculations, logs, or code prove that you can apply build your first demo-only expert advisor under controlled conditions.

  • Write the strategy and safety rules in plain language before opening MetaEditor.
  • Separate signal generation, position sizing, order execution, trade management, logging, and emergency stop logic.
  • Use magic numbers, symbol filters, spread limits, max-trade limits, and daily-loss limits from the first prototype.
  • Treat every code change as a new version that needs a new demo test record.

Worked case study: EA opens repeated trades on every tick

A beginner EA compiles and appears to work, but it opens several positions because the entry condition remains true across many ticks. The paid-course response is to add state management: new-bar checks, open-position checks, magic-number filtering, max-trade limits, and logs that explain why a trade was allowed or rejected.

After reading the scenario, write the decision you would make before checking the suggested workflow above. Then compare your decision with the operating model. The gap between those two answers is the part of the lesson that deserves another demo repetition.

Professional template

Complete this template in your own notebook. A paid course would normally hide this kind of operating document behind worksheets; here it is part of the free lesson.

FieldStandard
RequirementPlain-language rule that a non-programmer could review.
MQL5 componentFunction, event handler, class, or input used to implement the rule.
Safety gateCondition that prevents oversized, duplicated, stale, or forbidden trades.
Test evidenceCompiler result, Strategy Tester report, forward-demo log, and versioned settings file.

Failure-mode lab

Paid courses often sell confidence. A serious course teaches you how the idea breaks. Before continuing, test the failure modes below on demo, paper, or code review. If you cannot describe the failure, you are not ready to trust the concept.

  • Confusing a compiling EA with a tested EA.
  • Forgetting that OnTick can fire many times while the same condition remains true.
  • Hard-coding risk, symbol names, or trade volume without receiver/account context.
  • Removing logs because they look messy, then being unable to explain behaviour later.

Evidence pack and pass standard

Do not mark this lesson complete because you read it. Mark it complete only when you can show the evidence below. Keep the files in a dated folder so your learning history survives platform updates, memory gaps, and sales pressure.

  • A one-page note explaining build your first demo-only expert advisor without sales language or copied definitions.
  • A screenshot, export, calculation, log, or code file that proves the practical work was completed on demo.
  • A written stop rule that says when this topic must not be used with real money.
  • A versioned EA specification with inputs, risk gates, and known limitations.
  • A demo test folder with compiled file, settings, report, journal logs, and change notes.

Assessment rubric

LevelWhat it looks like
Not readyYou can repeat the vocabulary but cannot complete the demo task, calculate the risk, explain the failure mode, or show evidence.
Course passYou can complete the practical task on demo, explain the decision rules, show evidence, and name the conditions where the idea must not be used.
Strong passYou can teach the concept to someone else, find edge cases, document a rejected example, and improve the template without weakening risk controls.

Advanced homework

  • Add one safety gate, then create a test that proves the gate blocks a bad trade.
  • Refactor one EA idea into signal, risk, execution, and logging sections.
  • Write an incident report for a demo EA failure as if it happened in production.

Practical drill

Do this lesson as a controlled exercise, not as a reason to trade live. Open a demo account or notebook, write the lesson title, and record what you changed, clicked, calculated, or checked. If the lesson includes code, compile it only in a demo environment and keep the original version unchanged so you can compare edits safely.

  • Write a one-paragraph explanation of build your first demo-only expert advisor in your own words.
  • Take one screenshot or note that proves you completed the platform, maths, research, or code task.
  • Record one risk rule that would stop you from using this idea with real money.
  • If anything feels unclear, repeat the lesson before moving to the next module.

How scammers misuse this topic

Scammers often take real concepts and wrap them in urgency. They may use platform jargon, bot screenshots, copied profit charts, or official-sounding language to make a paid offer feel safe. A real concept is not the same as a safe offer. Before paying anyone, ask whether you can verify the provider, reproduce the calculation, test the claim on demo, understand the risk, and walk away without pressure.

Checkpoint before continuing

  • The EA compiles without errors.
  • It refuses to load on a live account.
  • You can explain every input and safety check before changing anything.

Official references

These lessons are written as free education. When platform features or rules matter, verify against the official source before using real money.

Risk note: leveraged forex and contracts for difference can lose money quickly. EarnSouthAfrica is an educational publisher, not a broker, adviser, signal provider, or money manager.

Keep exploring

Read the latest guides, take the side-hustle quiz, or contact the editorial desk if you spot a correction.