EMATrailingStop_v1

Download script
Author: Copyright 2006, Forex-TSD.com
EMATrailingStop_v1

This script is designed to automate the management of active trades by dynamically adjusting "Stop Loss" levels. Its primary goal is to protect your profits as the market moves in your favor, using a moving average indicator as the benchmark for these adjustments.

Core Functionality

The tool monitors your open positions and automatically moves the stop loss price based on a specific technical indicator (the Exponential Moving Average). Instead of letting a trade sit with a static risk level, this script "trails" the price, attempting to lock in gains while keeping the trade active.

How it Works Logically:

1. Monitoring Active Trades The script constantly scans your open positions. It identifies trades that match the specific currency pair or asset you are currently viewing. If no active trades are found, the script remains idle.

2. Determining the Target Price The script calculates a "target" stop loss price based on the following hierarchy:

  • Moving Average Reference: The primary logic uses an Exponential Moving Average (EMA). The script looks at where this average is currently positioned on the chart to decide where the new stop loss should be.
  • Initial Protection: If a trade is newly opened and does not yet have a stop loss assigned, the script applies a pre-defined "Initial Stop" distance based on your settings.
  • Broker Safety Limits: The script includes a safety check to ensure that any price it tries to set isn't too close to the current market price, which prevents errors caused by broker restrictions (minimum stop levels).

3. Execution Logic for Buy and Sell Positions

  • For Buy Orders: The script looks to place the stop loss below the current market price. It will only move the stop loss upward if the new calculated price (based on the Moving Average) is higher than your existing stop loss and remains below your entry price. This ensures that as the trend moves up, your protection moves up with it.
  • For Sell Orders: The logic is inverted. It looks to place the stop loss above the current market price. It will move the stop loss downward if the Moving Average indicates a lower price than your current stop loss, effectively "locking in" profit as the price drops.

Summary for the User

In simple terms, this script acts like an automated security guard. Once you enter a trade, it watches the market trend. As the market moves into a profitable direction, the script automatically pulls your "safety net" (the stop loss) along with the price. This helps to secure profits automatically without requiring you to manually update your trades every time the market fluctuates.

Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicator
12 Views
0 Downloads
0 Favorites
EMATrailingStop_v1
//+------------------------------------------------------------------+
//|                                           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 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)
         {
			double BuyStop = ema;
			if(OrderStopLoss() == 0 && InitialStop>0 ) BuyStop = Bid-InitialStop*Point; 
			if((bid - BuyStop) < minstop*Point) BuyStop = bid - minstop*Point;

			Print("MA=",ema," BuyStop=",BuyStop);
			   if ((OrderOpenPrice() <= BuyStop && 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)
         {
         double SellStop = ema;  
         if (OrderStopLoss()==0 && InitialStop > 0) SellStop = ask+InitialStop*Point;
         if((SellStop-ask) < minstop*Point)  SellStop = ask + minstop*Point; 
         Print("MA=",ema," SellStop=",SellStop);  
            if( (OrderOpenPrice() >= SellStop && 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