Here you can download a Metatrader 4 Expert Advisor Template which you can use to start to build your automated system. The template has a lot of tools, all of them works fine (I use it on live), you only have to add the rules for open an close position. I've written this Expert Advisor, some piece of the code are mine, others has been modified from open source EAs I've found on the net.

The template includes a ma croos example for open and close position, it just an example, please don´t use it with real money!!!

Download CyberEA-Template

Check for Signals: The core of your system



This loop, in the code named CheckForSignal() es used to get the singal for open or close a trade.

The loop return the value of two bools, signalBuy and signalSell.
The result of this bools will be used to open or close positions.
Let going to see the example of the Expert Advisor CyberEA-Template.

In the template if signalBuy=true is a buy signal and if signalSell=true is a sell signal.

CyberEA gets the value of slowMA (Slow MA) and fastMA (Fast MA) and if fastMA>slowMA return signalBuy=true so, a buy signal.
This value will be called from check for open and check for close loops, wich we will see in other post, to take action.

Note that the settings of MA are selected from external variables that can be changed after compilation of the code.


void BuscarSenal()
{
if (time_now != Time[0])
{
time_now = Time[0];
slowMA = iMA(NULL,0,SlowMAPeriod,SlowMAShift,SlowMAMode,SlowMAApplyPrice,Bar);
fastMA = iMA(NULL,0,FastMAPeriod,FastMAShift,FastMAMode,FastMAApplyPrice,Bar);
}

signalSell = false;
signalBuy = false;
if (fastMA>slowMA) signalBuy = true;
if (slowMA>fastMA) signalSell=true;
goLong = signalBuy;
goShort = signalSell;
if (goLong || goShort) return;

if (BuscarOrdenes() != 0)
{
goLong = false;
goShort = false;
}
}

Money Management Tool



CyberEA Template has a money management tool integrated. This tool get the lot size for the positions based on risk and stop loss settings.
Extenal variables of MoneyManagement tool:

  • UseMoneyManagement: Set to true if you want to use automatic calculation of lot size.
  • UseMicroLots: Set to true if you are going to trade in 0.01 lots steps. IMPORTANT: Set it to true when you trade in 0.01 step, even if you set UseMoneyManagement=false.
  • MaximumRisk: Enter your max. risk. Example: 5 mean you accept a loss of 5% of your account per trade.
  • FixedLots: Enter the number of lots per trade when UseMoneyManagement=false.

How stoploss affects to automatic calculation of lot size?
I will explain with an example.

If you set an stoploss of 150 pips and a MaximumRisk=5, this mean that if stoploss is hitted the max. loss will be 5% of your balance and the lot size will be calculated based on this. So if you set stoploss of 50 pips the lot size will be greater than if you set 150pips stop loss for the same max risk.

The MoneyManegement code: The loop is a double function that must be called when you need calculated the lot size, for example in OrderSend function you have to write LotsRisk(int sl) instead a number of lots. In our case we set the stop loss with the variable StopLoss so we have to write LotsRisk(StopLoss) when lot size calculation is needed.

double LotsRisk(int sl)
{
if (UseMicroLots == false)
{
if (!UseMoneyManagement)
{
LotSize = NormalizeDouble(FixedLots,1);
if (LotSize < 0.1) LotSize = 0.1;
if (Kumo == 1) Print("Position lot size: " + LotSize);
}
if (UseMoneyManagement)
{
LotSize = NormalizeDouble(AccountFreeMargin() * MaximumRisk / 1000.0 / sl,1);
if (LotSize < 0.1) LotSize = 0.1;
if (Kumo == 1) Print("Position lot size: " + LotSize);
}
}

if (UseMicroLots == true)
{
if (!UseMoneyManagement)
{
LotSize = NormalizeDouble(FixedLots,2);
if (LotSize < 0.01) LotSize = 0.01;
if (Kumo == 1) Print("Position lot size: " + LotSize);
}
if (UseMoneyManagement)
{
LotSize = NormalizeDouble(AccountFreeMargin() * MaximumRisk / 1000.0 / sl,2);
if (LotSize < 0.01) LotSize = 0.01;
if (Kumo == 1) Print("Position lot size: " + LotSize);
}
}
return(LotSize);
}

LiteForex Metatrader Broker



LiteForex is a Metatrader Forex Broker that support accounts in cents, so is one of the best for testing Expert Advisor with just 1 or 5 five dollars.

LiteForex has a minimum deposit of 1$ and you can use a lot of ways to funds your account.

Visit LiteForex.

  • You can start to trade with a little 1$.
  • Spreads: 3 pips on EUR/USD and 4 on GBP/USD.
  • Stocks and metals available for trade
  • Demo accounts for practice purpose.
  • Monthly interest over the balance directly on your account.
  • Daily analisis and news alerts sevice.
  • 3 dedicated servers.
  • Metatrader trading platform.
  • Leverage: 1:100 or 1:200.
  • Make a fund on your account or withdraw through wire tranfer, WebMoney, MoneyBookers, e-Bullion, USD credit card, etc.
  • Fast execution, no dealing desk.
  • Part of Straighthold Investment Group, independent Market Maker.
  • Regulated by International Business Authority of Seychelles, reference ID 036925.
  • On line since 2004.

Visit LiteForex - Open an account with LiteForex

InstaForex, Metatrader Forex Broker


InstaForex, Metatrader Forex Broker.

  • Minimum deposit: 10$
  • Leverage: from 1:1 to 1 :500
  • Minimum lot size: 0.01
  • Spreads: 3 pips on EUR/USD, GBP/USD, USD/CHF and USD/JPY
  • 32 currencies crosses and CFD's
  • Accounts with zero spreads available, you will pay a 0.02-0.07% comission per trade
  • On line since 2008
  • 6% annual interest rate on deposit
  • Deposit via Paypal, wire transfer, credit card, e-gold, WebMoney, e-Bullion and RuPay


Visit InstaForex - Open an account with InstaForex

FXCast Metatrader Forex Broker

  • Minimum deposit: 10USD
  • Leverage from 1:25 to 1:400.
  • Minimum lot per trade: 0.01.
  • Spreads: 3 pips in EUR/USD and GBP/USD.
  • Demo accounts available.
  • Customer supprot 24 hours per day.
  • On line since 2005.
  • Trading platform: Metatrader
  • Funds and withdraws through wire transfer, credit card, e-bullion, e-gold, c-gold, webmoney, liberty reserve and e-dinar .

Visit FXCast - Open an account with FXCast

Start() function



The start() is the only one that is needed in order to work. This function is executed every tick is recieved in Metatrader. So you must set in this function all parameters and variables that have to be calculate at each tick and call the others functions based on it.
In CyberEA-Template, all function calls is envolved into trading hours variables.

void start(){
First piece of code of the loop: check for trade stratus and trade context:
bool tradeallowed=IsTradeAllowed();
if(!tradeallowed){
Print("Trade not allowed");
}
bool contextbusy=IsTradeContextBusy();
if (contextbusy){
Print("Trade context is busy");
}
Next part: On each tick CyberEA take the current time as value of the local variable named hour. Based on the value of hour we set the next action. On this way, if it's time to trade (we are set the trading hours in the external varialbes) . In this way if hour is equal to expiration hour the function Clean() (for close all orders) is called. If hour is between start and end hour the function CheckForSignal() (check for signal) is called. Also is called the function SearhPositions() (check for orders) and if SearchPositons() is not equal to zero the EA will call CheckForClose() (check for close). If SearchPositions() is equal to zero CheckForOpen() function (check for open) is called. Also I have to comment that TrailStop and BreakEven function will be called only if hour is between trading hours and if we have set it to true in the external variables.
int hour = Hour(); if (hour == Expiration) Clean(); if ((StartHour <= hour) && (EndHour >= hour)) {
CheckForSignal();
if (SearchPositions() != 0)
CheckForClose(); else CheckForOpen();
if (SearchPositions() != 0) {
if (UseTrailingStop == true) TrailStop();
if (UseBreakEven == true) BreakEven();
}
}

Commenting(); Commenting function is called on each tick.
}

Head and global variables



Head and global vaiables are the first piece of code of the expert advisor where you must set the copyright information, the variables that you are going to use in some functions and the externs variables that you are going to use in some functions and you want to be able for after compile changes.

Let go to comment this piece of code:

Head with copyright information:
#property copyright "Copyright 2008, http://cablebot.blogspot.com/"
#property link "http://cablebot.blogspot.com/"

stdlib library call:
#include <stdlib.mqh>

external variables:
extern string Version = "CyberEA"; This is a comment asociate to all orders open by this expert advisor. This comment can be used to identify all orders from the EA.
extern string Settings="Settings"; Here start the external variables that you can chage in the experts properties window at the time of use. Set the default values before compile.

Trading hours:
extern int StartHour = 0;
extern int EndHour = 24;
extern int Expiration = 24;

Slippage:
extern int Slippage = 5;

Order take profit and stoploss:
extern double TakeProfit =450;
extern double StopLoss = 150;

Trainling stop:
extern bool UseTrailingStop = false;
extern int TrailingStart = 80;
extern int TrailingStop =100;

BreakEven or Profit Protect variables:
extern bool UseBreakEven = false;
extern int ProfitProtectStart1 = 60;
extern int ProfitToProtect1 =30;
extern int ProfitProtectStart2 = 120;
extern int ProfitToProtect2 =60;
extern int ProfitProtectStart3 = 180;
extern int ProfitToProtect3 =90;
extern int ProfitProtectStart4 = 240;
extern int ProfitToProtect4 =120;

Money Management tool:
extern string MM = "Money Management";
extern bool UseMoneyManagement=true;
extern bool UseMicroLots = false;
extern int MaximumRisk = 5;
extern string FixedLot = "Fixed Lots";
extern double FixedLots = 0.1;

Magic Number: This number is used to identify singles orders from the EA, be sure that is different for each chart and for each currencies pair you trade.
extern int MagicNumber = 852745962;

Indicators settings:
extern int FastMAPeriod = 57;
extern int FastMAShift = 2;
extern int FastMAMode = MODE_EMA;
extern int FastMAApplyPrice = PRICE_CLOSE;
extern int SlowMAPeriod = 19;
extern int SlowMAShift = 12;
extern int SlowMAMode = MODE_EMA;
extern int SlowMAApplyPrice = PRICE_CLOSE;
extern int Bar = 1;

Others global variables the EA use to calculate some parameters in several loops of the automated system.The next variables can not been change after compilation.
int Number = 20;
int Kumo = 1;
bool signalBuy;
bool signalSell;
bool goShort;
bool goLong;
int ordersent;
int Arko;
int time_now;
double fastMA;
double slowMA;
int conditionalcheck = 0;
double LotSize;

If you want to change the name of some variables you can do but make sure you change it every time the same variable appear in the expert advisor code.

In the next posts I will comment all the loops and functions of the EA line by line.

CyberEA-Template Overview



CyberEA-Template is an Expert Avsisor for Metatrader, this is, an automated trading program. Please note that I've not said system, the system must be added to the Template. As an example the cyberEA has a MA cross simple rules.

CyberEA include a lot of tools, all of them works fine: I can say that because I use the exact same code for my live trading without errors, obviously with differents rules for open and close position.

Head and global variables

Head: copyriht, owner link, etc.
Global variables: In this piece of the code we set all variables that we are going to use in several function of CyberEA. I prefer not inlcude here variables that are only used in one function, in this case the variable will be generated at he specific loop.

Start() Function

This function is the only one that is executed every tick that CyberEA recieve from the broker.
Every time this function is executed all the parameters in this loop are calculated and based on the result others function can be called.

Money Management: LotRisk()
In this loop CyberEA will calculate the lot size for the orders.

Check for Orders: BuscarOdernes()
CyberEA use this one for find orders from the Expert Advisors and return a certain value for a variable that will be use later in other functions and loops.

Check for Signal: BuscarSenal()
This is the core of the EA. Here is where you must write the indicators an rules for open and close position.

Check for Open: BuscarAbrir()
When this loop is executed the EA will take action based on the result of BuscarSenal(): The EA will send orders to the broker.

Check for Close: BuscarCierre()
Like BuscarAbrir() this loop will take action based on the result of BuscarSenal(), in this case for close position, not for open.

TrailStop():
I think all of you know what means trailstop ;))

BreakEven():
Loop used for modifiying orders and move stoploss to a certain levels.

Read carefully details of each function and start to code your BuscarSenal() loop with your indicators and rules.

Before starting


What are you going to programming?
Before you start to write the automated system you have to have a full and clear description of your system. Let take an example with a MA cross system:

Overview: signals for open and close position are going to be generated by a fast and low MA croos. If fast MA cross up slow MA open buy and close sell if there is some one.

This is easy but you are going to programming the rules so you have to take into consideration all variables:

- Type of MA? Simple, exponential, linear, ...

- Period?

- Apply price? The value are going to be calculated for close price of bar, open , high, low, middle, ...

- When the system are going to take action: a MA cross can happen in the current bar several times so maybe you want to wait to the current bar be completed.

- Are you going to use others indicators for confirmation?

- Which time frame are the system going to work?

All of this questions and others have to be answer before programming. Anyway you can set this variables as external variable for modify them later and try several configuration, so if this questions have no answer at the first moment they must be taken into consideration. If you download the CyberEA-Template you can see that all variables of the Fast and Slow MA are externals variables, so is easy change the configuration after compilation on the properties of the expert advisor.

Message Board

Do you have questions or comments? Use comments of this post to make them.

Privacy

We are strongly committed to protecting your privacy while interacting with Shikle. Our goal is to provide you with a satisfying experience while allowing you to control your privacy and to give you a means to voice any questions or concerns you may have.

Cablebot blog use blogger service. You should read Blogger's privacy policy at: http://www.blogger.com/privacy.

Our third-party advertising partners may place cookies on your browser in combination with web beacons in their ads for the purposes of analyzing or auditing the effectiveness of the ads that they serve. A cookie is a small text file containing a string of characters that a website sends your computer. It records information necessary for certain website functions, such as remembering your preferences or settings. A cookie will not allow us or any third-party to learn any personally identifiable information that you have not otherwise disclosed. The use of cookies is an industry standard, and they are currently used on most major websites. Most browsers are initially set up to accept cookies, but you change your browser's cookie settings to refuse all cookies or to indicate when a cookie is being sent. Some features and services may not function properly if your cookies are disabled. A web beacon is a small image file that is placed on a web page and used in conjunction with cookies to accurately count the number of unique users who have visited a specific page or viewed a specific advertisement. Any image file on a Web page can act as a Web beacon.

Google, as associate ads provider, uses DART cookie from doubleclick. You can get more information about this cookie following this link: http://www.doubleclick.com/privacy/faq.aspx.

If you want to view ads about your interest you can edit your preferences on http://www.google.com/ads/preferences. Those preferences is based on websites you have visited recently.

The users can disable the use of DART cookie (http://www.google.com/privacy_ads.html) through Google Ads. In order to completely keep DART cookies disable you can install this complement for your browser: http://www.google.com/privacy_ads.html. This plugin keeps your preferences even in case of erasing all cookies.

We use Google Analytics for monitoring trafic on the website, you should read privacy policy from Google: http://www.google.com/intl/en_ALL/privacypolicy.html

Please note that this Privacy Policy may change from time to time. We expect most such changes will be minor. We will post any Policy changes on this page and, if the changes are significant, we will provide a more prominent notice. Each version of this Policy will be identified at the bottom of the page by its effective date.

Last update: April 02 2009