EMATrailingStop_v1a
Download scriptThis script is designed to automate the management of your open trades by dynamically adjusting "Stop Loss" levels. Its primary goal is to protect your profits and manage risk automatically as the market price moves in your favor.
How the Logic Works
The system operates by constantly monitoring your active trades and comparing the current market price against a specific moving average indicator (the EMA). Here is the step-by-step breakdown of its behavior:
1. Trade Monitoring The script first scans your open positions to identify active trades on the specific currency pair or asset you are currently viewing. It specifically looks for "Buy" and "Sell" orders to determine which protection rules to apply.
2. Dynamic Stop Loss Calculation Instead of leaving your Stop Loss at a fixed price, the script uses a technical indicator (the Exponential Moving Average) as a moving target:
- For Buy Positions: The script attempts to place or move the Stop Loss to follow the position of the moving average. As the market trends upward and the average moves higher, the Stop Loss "trails" behind it.
- For Sell Positions: The script tracks the moving average from above. As the market trends downward and the average drops, the Stop Loss follows down accordingly.
3. Initial Protection When you first open a trade, the script provides an initial safety net. If you have configured a specific "Initial Stop" distance, it will set the first protection level based on that fixed gap. Once the trade is active and moving, it then transitions into the automated trailing logic mentioned above.
4. Safety and Compliance Checks The script includes built-in "smart" checks to ensure it doesn't conflict with the broker's rules:
- Minimum Distance: It checks the broker's minimum allowed movement (Stop Level) to ensure the Stop Loss isn't placed too close to the current price, which would cause a transaction error.
- One-Way Movement: The script is programmed to only move the Stop Loss in the direction that locks in profit. It will not move a Stop Loss "backward" into a zone of higher risk; it only moves forward as the market moves favorably for you.
5. Automatic Execution The process repeats continuously. Every time the market price updates, the script recalculates the position of the moving average and instantly sends an update command to the broker to move your Stop Loss to the new, safer position. This removes the need for manual monitoring, allowing the protection level to "glide" with the trend in real-time.
//+------------------------------------------------------------------+
//| EMATrailingStop_v1.mq4 |
//| Copyright 2006, Forex-TSD.com |
//| Written by IgorAD,igorad2003@yahoo.co.uk |
//| http://finance.groups.yahoo.com/group/TrendLaboratory |
//+------------------------------------------------------------------+
#property copyright "Copyright 2006, Forex-TSD.com "
#property link "http://www.forex-tsd.com/"
//---- input parameters
extern int EMATimeFrame = 0;
extern int Price = 0;
extern int EMAPeriod = 89;
extern int EMAShift = 20;
extern int InitialStop = 20;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
return(0);
}
// ---- Stepped Stops
void TrailStop()
{
double BuyStop, SellStop;
double minstop = MarketInfo(Symbol(),MODE_STOPLEVEL);
double ask = MarketInfo(Symbol(),MODE_ASK);
double bid = MarketInfo(Symbol(),MODE_BID);
double ema = iMA(Symbol(),EMATimeFrame,EMAPeriod,0,MODE_EMA,Price,EMAShift);
for (int cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
if ( OrderSymbol()==Symbol())
{
if (mode==OP_BUY)
{
if(OrderStopLoss() == 0)
{
if( InitialStop>0 ) BuyStop = Bid-InitialStop*Point; else BuyStop = ema;
}
else
BuyStop = ema;
if((bid - BuyStop) < minstop*Point) BuyStop = bid - minstop*Point;
Print("MA=",ema," BuyStop=",BuyStop);
if (BuyStop > OrderStopLoss() || OrderStopLoss()==0)
{
bool result = OrderModify(OrderTicket(),OrderOpenPrice(),
NormalizeDouble(BuyStop, Digits),
OrderTakeProfit(),0,LightGreen);
if( !result )
{
Print("BUY: OrderModify failed with error");
GetLastError();
}
return(0);
}
}
// - SELL Orders
if (mode==OP_SELL)
{
if (OrderStopLoss()==0)
{
if (InitialStop > 0) SellStop = ask+InitialStop*Point; else SellStop = ema;
}
else
SellStop = ema;
if((SellStop-ask) < minstop*Point) SellStop = ask + minstop*Point;
Print("MA=",ema," SellStop=",SellStop);
if( OrderStopLoss() > SellStop || OrderStopLoss()==0)
{
OrderModify(OrderTicket(), OrderOpenPrice(),
NormalizeDouble(SellStop, Digits),
OrderTakeProfit(),0,DarkOrange);
if( !result )
{
Print("SELL: OrderModify failed with error");
GetLastError();
}
return(0);
}
}
}
}
}
// ---- Scan Trades
int ScanTrades()
{
int total = OrdersTotal();
int numords = 0;
for(int cnt=0; cnt<total; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderSymbol() == Symbol() && OrderType()<=OP_SELL)
numords++;
}
return(numords);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
if (ScanTrades()<1) return(0);
else
if (EMAPeriod > 0) TrailStop();
return(0);
}//int start
//+------------------------------------------------------------------+
Comments