MQL4 - automated forex trading   /  

Code Base

Code Base  Expert Advisors  Simple FX To post a new code, please log in or register

This Expert Advisor is for
MetaTrader 4
Download MT 4 - 5.5 Mb

Mobile trading!
Buy a license and be mobile in your trading!

Name:
Simple FX [ ru ]
Author: RobinHood (2007.12.01 11:02)
Rating: 2
Downloaded: 13725
Download:
 simplefx2.mq4 (13.7 Kb) View

Simple FX free expert advisor automatically trades the Forex market using moving averages. 
The two moving averages can be changed to the period, method and type. Also order settings
can be changed lot size, slippage and magic number.  The expert advisor can trade any pair
and any mt4 broker.Simple FX trades best attached to the daily D1 chart time frame.

The latest version of Simple FX is simplefx2.mq4. Changes include:

  • Added optional s/l and t/p
  • Bug fix in s/l and t/l code
  • Now waits for first MA cross
  • If s/l or t/p is used and order reaches s/l or t/p it will wait for the next MA cross
  • Important variables are automatically saved to a file





How it works

Its simple (pun intended). When the short moving average is above the long moving average
the trend is considered up or bullish. The expert advisor closes its sell order (if one is open)
and opens a buy order. When the short moving average is below the long moving average
the trend is considered down or bearish. The expert advisor closes its buy order (if one is open)
and opens a sell order. So, the expert advisor stays in the market riding the trend up and down.

Quick overview of variables

Stop_Loss and Take_Profit

Stop_Loss and Take_Profit variables are optional, meaning the values can be left at zero and the EA
will still trade correctly. If you would like more control over the expert advisor you can change one or more
of the values. For example to have the EA open positions with a take profit of 20 pips you would simply change
Take_Profit value to 20.


Long_MA_Method and Short_MA_Method

  • Simple moving average (SMA) = 0
  • Exponential moving average (EMA) = 1
  • Smoothed moving average (SMMA) = 2
  • Linear weighted moving average (LWMA) = 3

Long_MA_Applied_Price and Short_MA_Applied_Price

  • Close price = 0
  • Open price = 1
  • High price = 2
  • Low price = 3
  • Median price = 4 (default value)
  • Typical price = 5
  • Weighted close price = 6



Best regards,
Glenn Bacon (RobinHood)





39 comments: 1 2 3 4   To post a new comment, please log in or register

When I see at 'TrendDetection' function :

It's only detect if a short_MA > long_MA for bull trend, I think it should also check wheter the direction of MA line is UP (short_MA0>short_MA1 && long_MA0>long_MA1)

22.10.2009 18:18 rizky

This EA works very perfectly on GBP/USD H1 with Take Profit=100 and Stop Loss= 100. 20 Long and 10 Short. THANKS

16.06.2009 20:03 awise303

As for a simple MA cross EA, this EA definitely too crowded and too complicated. Well.. that's just my opinion.


10.06.2009 22:30 devilian1899

In the Trailing Stop i see +0.5 such as "if(Bid - OrderOpenPrice() > Point*(TrailingStop+0.5))"

Whats the +0.5 used for?

because i saw another EA example by MetaQuotes they doesn't add anything (eg. if(Bid - OrderOpenPrice() > Point*TrailingStop))

30.05.2009 12:40 AdamN
pengwu96 wrote:
There are mistakes in the stoploss, I modified it and also add trailingstop function.
I think the values of stoploss and stopprofit and trailingstop should be optimized. Do anyone have ideas about this?
Here is the code:
//+------------------------------------------------------------------+
//| simplefx2.mq4 |
//| Copyright ?? 2007, GLENNBACON.COM LLC |
//| http://www.GetForexSoftware.com |
//+------------------------------------------------------------------+
/*
Simple FX source code, expert advisor and user manual are property of
GLENNBACON.COM LLC and may not be altered, used or sold in commercial
products. The Simple FX source code itself may be altered and used in personal
projects as long as the name GLENNBACON.COM LLC and
http://www.GetForexSoftware.com URL are left entacted and visible.

Programmer: Glenn Bacon
Note: Every programmer has their own style and format of writing code. I try
to make the code as readable as possible by using indenting and tab nested code.
There are comments throughout the source explaining what each block/line of code does.

I always use brackets {} to contain my if else and for conditional statements. Some
programmers use shortcuts I do not. I think more programmers should always use
brackets because it makes the code more readable. (bored reading this yet?)

I also only create and use a couple of my own functions because if you create dozens of functions it
makes the code more difficult to read.

If you're not a programmer and have questions about the code do not email me about
the code or what it does. If you are a programmer and have questions about this
code I can be contacted by going to http://www.GetForexSoftware.com and navigate to our
Customer Service page, it has a contact form.
*/

#property copyright "Copyright ?? 2007, GLENNBACON.COM LLC"
#property link "http://www.GetForexSoftware.com"

// Shift of moving average
#define Shift 1

// Trend Detection function
#define BULL 111111
#define BEAR 222222

// Input variables
extern string comment2 = "*** Order Options ***";
extern double Lots = 0.10;
extern int Stop_Loss = 21;
extern int Take_Profit = 987;
extern int TrailingStop = 10;
extern int Slippage = 5;
extern string Order_Comment = "Simple FX";
extern int Magic = 112607;
extern color Order_Arrow_Color = Green;


extern string comment3 = "*** Moving Average Options ***";
extern int Long_MA_Period = 200;
extern int Long_MA_Method = 0;
extern int Long_MA_Applied_Price = 4;

extern int Short_MA_Period = 50;
extern int Short_MA_Method = 0;
extern int Short_MA_Applied_Price = 4;

// Global variables
int Total_Open_Orders = 1; // we only want to open one order at a time and only manage the one order
int cnt = 0; // counter variable, used in for() loops
bool init_variables; // init variable when program starts
datetime PreviousBar; // record the candle/bar time


int init()
{
init_variables = true; // Allows us to init variables in the start function because
// we cannot do this in the init function because the variables
// use values from the chart
return(0);
}
int deinit()
{
// clear chart when EA is removed
ObjectsDeleteAll();
return(0);
}

int start()
{

// moving average only run expert advisor if there is enough candle/bars in history
if(Bars < Long_MA_Period+1)
{
if(IsTesting()==false)
{
Comment("Long moving average does not have enough Bars in history to open a trade!\n",
"Must be at least ",Long_MA_Period, " bars to perform technical analysis.");
}
else
{
Comment("Back testing currently Long moving average does not have enough Bars to open a trade.\n",
"Must be at least ",Long_MA_Period, " bars to perform technical analysis.\n",
"Please be patient and wait...\n",
"Bars in history ",Bars);
}
return(0);
}

// make sure trader has set Lots to at least the minimum lot size of the broker and
// we will normalize the Lots variable so we can properly open an order
if(MarketInfo(Symbol(),MODE_MINLOT) == 0.01)
{
Lots = NormalizeDouble(Lots,2);
if(Lots < 0.01)
{
Comment("The variable Lots must be 0.01 or greater to open an order. ");
return(0);
}
}
if(MarketInfo(Symbol(),MODE_MINLOT) == 0.1)
{
Lots = NormalizeDouble(Lots,1);
if(Lots < 0.1)
{
Comment("The variable Lots must be 0.1 or greater to open an order. ");
return(0);
}
}
if(MarketInfo(Symbol(),MODE_MINLOT) == 1)
{
Lots = NormalizeDouble(Lots,0);
if(Lots < 1)
{
Comment("The variable Lots must be 1 or greater to open an order. ");
return(0);
}
}

// init variables when the expert advisor first starts running
if(init_variables == true)
{
PreviousBar = Time[0]; // record the current canle/bar open time

// place code here that you only wnat to run one time

init_variables = false; // change to false so we only init variable once
}

// perform analysis and open orders on new candle/bar
if(NewBar() == true)
{
// only perform analysis and close order if we only have one order open
if(TotalOpenOrders() == Total_Open_Orders && SelectTheOrder() == true)
{
if(OrderType() == OP_BUY && TrendDetection() == BEAR)
{
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Order_Arrow_Color);
}
if(OrderType() == OP_SELL && TrendDetection() == BULL)
{
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Order_Arrow_Color);
}
if(OrderType() == OP_BUY && TrendDetection() != BEAR)
{
// check for trailing stop
if(TrailingStop > 0)
{
if(Bid - OrderOpenPrice() > Point*(TrailingStop+0.5))
{
if(OrderStopLoss() < Bid - Point*(TrailingStop+0.5))
{
OrderModify(OrderTicket(), OrderOpenPrice(),
Bid - (Point*TrailingStop),
OrderTakeProfit(), 0, Green);
return(0);
}
}
}
}
if(OrderType() == OP_SELL && TrendDetection() != BULL)
{
// check for trailing stop
if(TrailingStop > 0)
{
if((OrderOpenPrice() - Ask) > (Point*(TrailingStop+0.5)))
{
if((OrderStopLoss() > (Ask + Point*(TrailingStop+0.5))) ||
(OrderStopLoss() == 0))
{
OrderModify(OrderTicket(), OrderOpenPrice(),
Ask + (Point*TrailingStop),
OrderTakeProfit(), 0, Red);
return(0);
}
}
}
}
}

// only perform analysis and open new order if we have not reached our Total_Open_Orders max
if(TotalOpenOrders() < Total_Open_Orders)
{
// open buy
if(TrendDetection() == BULL)
{
// open order
OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,(Ask-(Stop_Loss*Point)),(Ask+(Take_Profit*Point)),
Order_Comment,Magic,0,Order_Arrow_Color);
}

// open sell
if(TrendDetection() == BEAR)
{
// open order
OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,(Bid+(Stop_Loss*Point)),(Bid-(Take_Profit*Point)),
Order_Comment,Magic,0,Order_Arrow_Color);
}
}

// when back testing only display chart info every candle/bar so we do not slow down back tests
if(IsTesting() == true)
{
Display_Info();
}
}

// when not back testing display chart info every tick
if(IsTesting() == false)
{
Display_Info();
}

return(0);
}

/////////////////////////////////////////////////////////////////////////
// Common functions //
///////////////////////////////////////////////////////////////////////

// This function returns the total amount of orders the expert advisor has open
int TotalOpenOrders()
{
cnt=OrdersTotal();
int TotalOpenOrders = 0;

if(cnt==0)
{
return(0);
}
else
{
for(;cnt>=0;cnt--)
{
RefreshRates();
OrderSelect(cnt,SELECT_BY_POS);
if(OrderMagicNumber()==Magic)
{
TotalOpenOrders++;
}
}
}
return(TotalOpenOrders);
}

// This function finds the open order and selects it
int SelectTheOrder()
{
cnt=OrdersTotal();

if(cnt==0)
{
return(false);
}
else
{
for(;cnt>=0;cnt--)
{
RefreshRates();
OrderSelect(cnt,SELECT_BY_POS);
if(OrderMagicNumber()==Magic)
{
return(true);
}
}
}
return(false);
}

// This function return the value true if the current bar/candle was just formed
bool NewBar()
{
if(PreviousBar<Time[0])
{
PreviousBar = Time[0];
return(true);
}
else
{
return(false);
}
return(false); // in case if - else statement is not executed
}

// is trend up/bullish or is it down/bearish
int TrendDetection()
{
// BULL trend
if(iMA(NULL,0,Short_MA_Period,0,Short_MA_Method,Short_MA_Applied_Price,0) > iMA(NULL,0,Long_MA_Period,0,Long_MA_Method,Long_MA_Applied_Price,0) && iMA(NULL,0,Short_MA_Period,0,Short_MA_Method,Short_MA_Applied_Price,1) > iMA(NULL,0,Long_MA_Period,0,Long_MA_Method,Long_MA_Applied_Price,1))
{
return(BULL);
}

// BEAR trend
if(iMA(NULL,0,Short_MA_Period,0,Short_MA_Method,Short_MA_Applied_Price,0) < iMA(NULL,0,Long_MA_Period,0,Long_MA_Method,Long_MA_Applied_Price,0) && iMA(NULL,0,Short_MA_Period,0,Short_MA_Method,Short_MA_Applied_Price,1) < iMA(NULL,0,Long_MA_Period,0,Long_MA_Method,Long_MA_Applied_Price,1))
{
return(BEAR);
}

// flat no trend return 0
return(0);
}

void Display_Info()
{
Comment("Simple FX ver 1.0\n",
"Copyright ?? 2007, GlennBacon.com, LLC\n",
"Visit: www.GetForexSoftware.com\n",
"Forex Account Server:",AccountServer(),"\n",
"Account Balance: $",AccountBalance(),"\n",
"Lots: ",Lots,"\n",
"Symbol: ", Symbol(),"\n",
"Price: ",NormalizeDouble(Bid,4),"\n",
"Pip Spread: ",MarketInfo(Symbol(),MODE_SPREAD),"\n",
"Date: ",Month(),"-",Day(),"-",Year()," Server Time: ",Hour(),":",Minute(),":",Seconds(),"\n",
"Minimum Lot Size: ",MarketInfo(Symbol(),MODE_MINLOT));
return(0);
}

I used the above code and I get the compiliation error "TrendDetection variable not defined"


14.04.2009 10:41 SpacePro99

Glenn,

Simplefx2 looks well documented, however the user manual would be helpful. So far I have been unable to find it. Can you tell me where it is located?

Regards,

William

19.03.2009 16:34 wbunn
art59 wrote:
I have tried other EA and they seem to work, this one does not work at all, even if I move the time parameters down to 1 minute there is no trade activated. I have managed to get alerts and EAs from other subscribers so I must be missing something, I have gone through the steps time and time again, but it just wont open a trade long or short.

Simple FX runs best on the Daily chart.  Also make sure the moving averages are not too close together (i.e. 3 and 9). Another common mistake trades make is setting the Lot size to large and trades being rejected from the brokers server because there is not enough leverage or money for the order.

Tip: Try running a strategy test using the default settings then tweak the settings to your liking.


Best regards,

Glenn Bacon

12.06.2008 21:34 RobinHood
I have tried other EA and they seem to work, this one does not work at all, even if I move the time parameters down to 1 minute there is no trade activated. I have managed to get alerts and EAs from other subscribers so I must be missing something, I have gone through the steps time and time again, but it just wont open a trade long or short.
12.06.2008 15:25 art59
How do i add a shift of 2 to the Long_MA?
17.04.2008 02:12 edwinodus
dollarsat wrote:

hi

i use this EA with mt4 demo and i attach with eurusa daily chart but not trad start i dont no why i am new i this filld plz tell me what i do thx

It can take a long time for the EA to open its first trade. Try attaching the two moving averages to the chart and you will see that the trend for the EURUSD is bullish. When will it enter its first order? After the short moving average crosses the long moving average which will signal a bearish move then the EA will open a sell order. There is no telling how long this could take because no one can predict when the EUR will change direction but, when it does Simple FX should open a position and follow the new trend.


20.03.2008 07:35 RobinHood