This script is designed to automatically trade on the Forex market using the MetaTrader platform. It works by analyzing the relationship between two Exponential Moving Averages (EMAs) ? one calculated over a shorter period (ShortEma) and another over a longer period (LongEma) ? of the price of a currency pair. Think of EMAs as lines that show the average price over a certain time, giving more weight to recent prices.
Here?s a breakdown of the script?s logic:
-
Initialization: When the script starts, it sets up some initial values, like the amount of money to risk per trade (Lots), how much profit to target (TakeProfit), how much loss to tolerate (StopLoss), and how much the trade should move in your favor before the stop loss starts trailing (TrailingStop). It also defines the periods for the Short and Long EMAs.
-
EMA Calculation: The script constantly calculates the current values of the ShortEma and LongEma.
-
Cross Detection: The core of the script lies in detecting when the ShortEma crosses the LongEma. A cross indicates a potential change in the price trend. A crossover occurs when the value of one EMA passes the other
-
Trading Decisions:
-
No Open Positions: If there are no open trades for the specific currency pair the script is running on, the script checks for an EMA cross.
- If the ShortEma crosses above the LongEma, the script interprets this as a signal to buy (expecting the price to rise). It opens a "buy" order with the specified TakeProfit and StopLoss levels.
- If the ShortEma crosses below the LongEma, the script interprets this as a signal to sell (expecting the price to fall). It opens a "sell" order with the specified TakeProfit and StopLoss levels.
-
Existing Open Positions: If there is an open trade for the currency pair, the script focuses on managing that existing trade. It does not open new trades based on EMA crosses while a trade is already active.
-
-
Trailing Stop Management: If the TrailingStop is set to a value greater than zero, the script adjusts the StopLoss level of an open trade as the price moves favorably. This helps to lock in profits as the price moves in the intended direction. For example, if you set TrailingStop to 20 pips, if the trade moves 20 pips into profit, the StopLoss is automatically moved to the breakeven point, meaning the worst-case scenario is now a break-even trade. If the trade continues to move favorably, the stop loss keeps trailing
In essence, this script is a simple trend-following system. It uses EMA crossovers to identify potential buying or selling opportunities and manages existing trades using a trailing stop to protect profits.
/*-----------------------------+
| |
| Shared by www.Aptrafx.com |
| |
+------------------------------*/
//+------------------------------------------------------------------+
//| EMA_CROSS.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| TODO: Add Money Management routine |
//+------------------------------------------------------------------+
#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"
//---- input parameters
extern double TakeProfit=130;
extern double StopLoss = 100;
extern double Lots=1;
extern double TrailingStop=20;
extern int ShortEma = 12;
extern int LongEma = 20;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
int Crossed (double line1 , double line2)
{
static int last_direction = 0;
static int current_direction = 0;
//Don't work in the first load, wait for the first cross!
static bool first_time = true;
if(first_time == true)
{
first_time = false;
return (0);
}
if(line1>line2)current_direction = 1; //up
if(line1<line2)current_direction = 2; //down
if(current_direction != last_direction) //changed
{
last_direction = current_direction;
return (last_direction);
}
else
{
return (0); //not changed
}
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
int cnt, ticket, total;
double SEma, LEma;
if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(TakeProfit<10)
{
Print("TakeProfit less than 10");
return(0); // check TakeProfit
}
SEma = iMA(NULL,0,ShortEma,0,MODE_EMA,PRICE_CLOSE,0);
LEma = iMA(NULL,0,LongEma,0,MODE_EMA,PRICE_CLOSE,0);
static int isCrossed = 0;
isCrossed = Crossed (LEma,SEma);
total = OrdersTotal();
if(total < 1)
{
if(isCrossed == 1)
{
//ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"EMA_CROSS",12345,0,Green);
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,"EMA_CROSS",12345,0,Green);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
if(isCrossed == 2)
{
//ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"EMA_CROSS",12345,0,Red);
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,"EMA_CROSS",12345,0,Red);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
return(0);
}
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
//OrderPrint();
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) // long position is opened
{
// should it be closed?
/* REMOVED - Trailling stop only close
if(isCrossed == 2)
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
return(0); // exit
}
*/
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// should it be closed?
/* REMOVED - Trailling stop only close
if(isCrossed == 1)
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
return(0); // exit
}
*/
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
return(0);
}
//+------------------------------------------------------------------+
Comments