3.1 Your first robot, part 1: settings and indicators
Now we build a whole robot. The strategy is the rulebook from module 1: EMA(10) crosses EMA(30), stop loss 30 pips, take profit 60 pips and at most one position. We start in MetaTrader 5.
Step 1: Create the file
- Open MetaTrader 5 and press F4 to open MetaEditor.
- Choose File → New → Expert Advisor (template) and click Next.
- Call it MaCross, and click Next until you reach Finish.
- Delete all the content in the file. We will write everything ourselves.
Step 2: The top of the file
#property copyright "My name"
#property version "1.00"
#include <Trade\Trade.mqh> // brings in CTrade, which makes sending orders easy
CTrade trade;#include brings in ready-made code from MetaTrader. CTrade is a helper that sends orders, closes positions and moves the stop loss with one line each.
Step 3: The settings
input int InpFastPeriod = 10; // Fast EMA
input int InpSlowPeriod = 30; // Slow EMA
input double InpLots = 0.10; // Size in lots
input double InpStopLossPips = 30; // Stop loss in pips
input double InpTakeProfitPips = 60; // Take profit in pips
input ulong InpMagic = 12345; // Magic numberThe magic number is the robot’s signature. The robot puts it on all its trades, so it only manages its own – not trades you have opened manually.
Step 4: Global variables and OnInit
int hFast, hSlow; // handles to the indicators
datetime lastBarTime = 0; // the time of the last candle we looked at
double pip; // the size of one pip in price
int OnInit()
{
pip = (_Digits == 3 || _Digits == 5) ? 10 * _Point : _Point;
hFast = iMA(_Symbol, _Period, InpFastPeriod, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, InpSlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
{
Print("Could not create the indicators");
return(INIT_FAILED);
}
trade.SetExpertMagicNumber(InpMagic);
trade.SetTypeFillingBySymbol(_Symbol);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
IndicatorRelease(hFast);
IndicatorRelease(hSlow);
}What is a pip in code?
_Point is the smallest price change. On EUR/USD with five decimals it is 0.00001. A pip is ten times as much: 0.0001. The line pip = ... takes care of both 5- and 3-decimal pairs (like USD/JPY) and 4- and 2-decimal pairs.
Compile often
Press Compile (F7) after every step. Then you find the errors while there are few of them. Any errors are listed at the bottom of MetaEditor with a line number.
Try it yourself
Type the settings and indicators from the lesson into the editor and compile. Do you get error messages? Read them carefully.
Key takeaways
- CTrade from Trade.mqh makes sending orders easy.
- Input parameters become settings you can change in the platform.
- Create the indicators once in OnInit, and check that they were created.
65% of retail investor accounts lose money when trading CFDs with this provider.