Help me with EA trailing stop please..

 
#property strict

#define __STRATEGY_MAGIC 1001000000
#define __SLEEP_AFTER_EXECUTION_FAIL 400

//Input variables
input int _Magic_Index = 200;            // Magic Index
input double _USD = 0;            // USD
input double _EUR = 1;            // EUR
input double _Lot_Size = 0.1;            // Lot Size
input int _SL = 5000;            // SL

//Global declaration
double _CCFP_AddCurrency;
double _CCFP_Currency;
double _M5Scalper_Buy;
double _M5Scalper_Sell;
double _ATR_Sup;
double _ATR_Res;
bool _Currency_Up;
bool _AddCurrency_Up;
bool _CCFPClose_Sell;
bool _CCFPClose_Buy;
double _Price_Value_Buy = 0;
double _Price_Value_Sell = 0;
bool _Sell_Signal;
bool _Buy_Signal;

int init() {

   return(0);
}

int start() {

   
   //Local declaration
   bool _Trailing_Stop_Buy = false;
   bool _Trailing_Stop_Sell = false;
   bool _Close_All_Long_Trades = false;
   bool _Close_All_Short_Trades = false;
   bool _Sell = false;
   bool _Buy = false;
   _CCFP_AddCurrency = iCustom(Symbol(), 60, "CCFP", _USD, 1);
   _CCFP_Currency = iCustom(Symbol(), 60, "CCFP", _EUR, 1);
   _M5Scalper_Buy = iCustom(Symbol(), 0, "M5Scalper", 0, 0, 1);
   _M5Scalper_Sell = iCustom(Symbol(), 0, "M5Scalper", 0, 1, 1);
   _Trailing_Stop_Buy = Universal_Trailing_Stop(_Magic_Index, _Price_Value_Buy, 0, 0);
   _Trailing_Stop_Sell = Universal_Trailing_Stop(_Magic_Index, _Price_Value_Sell, 0, 0);
   _ATR_Sup = iCustom(Symbol(), 0, "ATRStop", 0, 1);
   _ATR_Res = iCustom(Symbol(), 0, "ATRStop", 1, 1);
   _Currency_Up = (_CCFP_Currency > iCustom(Symbol(), 60, "CCFP", _EUR, 12));
   _AddCurrency_Up = (_CCFP_AddCurrency > iCustom(Symbol(), 60, "CCFP", _USD, 12));
   _CCFPClose_Sell = (_Currency_Up &&
   !_AddCurrency_Up);
   _CCFPClose_Buy = (_AddCurrency_Up &&
   !_Currency_Up);
   if( (__isBuy(_Magic_Index, Symbol()) &&
   (_ATR_Sup > __OpenPrice( _Magic_Index, Symbol()))) ) _Price_Value_Buy = _ATR_Sup;
   if( _CCFPClose_Buy ) _Close_All_Long_Trades = Close_All_Long_Trades(_Magic_Index);
   if( (__isSell(_Magic_Index, Symbol()) &&
   (_ATR_Res < __OpenPrice( _Magic_Index, Symbol()))) ) _Price_Value_Sell = _ATR_Res;
   _Sell_Signal = ((_CCFP_Currency < 0.008) &&
   (_CCFP_AddCurrency > -0.008) &&
   _AddCurrency_Up &&
   !_Currency_Up &&
   ((_M5Scalper_Sell < 1000) &&
   (_M5Scalper_Sell > 0)));
   _Buy_Signal = ((_CCFP_Currency > -0.008) &&
   (_CCFP_AddCurrency < 0.008) &&
   _Currency_Up &&
   !_AddCurrency_Up &&
   ((_M5Scalper_Buy < 1000) &&
   (_M5Scalper_Buy > 0)));
   if( _CCFPClose_Sell ) _Close_All_Short_Trades = Close_All_Short_Trades(_Magic_Index);
   if( _Sell_Signal ) _Sell = Sell(_Magic_Index, _Lot_Size, 0, _SL, 0, 0, 0, 1, 5, "");
   if( _Buy_Signal ) _Buy = Buy(_Magic_Index, _Lot_Size, 0, _SL, 0, 0, 0, 1, 5, "");

   return(0);
}



bool __selectOrderByMagic(int magic, string symbol)
{
   for(int i = 0; i < OrdersTotal(); i++)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == __STRATEGY_MAGIC + magic && OrderSymbol() == symbol)
         return(true);
   }
   return(false);
}



double __OpenPrice(int magic, string symbol)
{
   if(!__selectOrderByMagic(magic, symbol))
      return(0);
   return(OrderOpenPrice());
}



bool __isSell(int magic, string symbol)
{
   if(!__selectOrderByMagic(magic, symbol))
      return(false);
   return(OrderType() == OP_SELL || OrderType() == OP_SELLLIMIT || OrderType() == OP_SELLSTOP);
}



bool __isBuy(int magic, string symbol)
{
   if(!__selectOrderByMagic(magic, symbol))
      return(false);
   return(OrderType() == OP_BUY || OrderType() == OP_BUYLIMIT || OrderType() == OP_BUYSTOP);
}



bool Close_All_Long_Trades(int MagicIndex)
{
   int total = OrdersTotal();
   bool result = true;

   for(int i=total-1;i>=0;i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      if(OrderType() != OP_BUY) continue;
      if(!OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red )){
         result = false;
         Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
      }
   }
   return(result);
}


bool Sell(int MagicIndex, double Lots, int StopLossMethod, double StopLossPoints, int TakeProfitMethod, double TakeProfitPoints, int Slippage, int MaxOpenTrades,
          int MaxFrequencyMins, string TradeComment)
{
   static double pipSize = 0;   
   if(pipSize == 0) pipSize = Point * (1 + 9 * (Digits == 3 || Digits == 5));

   double sl = 0, tp = 0;
   double stopLossPoints = 0, takeProfitPoints = 0;

   int numberOfOpenTrades = 0;
   
   for(int i=OrdersTotal()-1;i>=0;i--){
      if(!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      numberOfOpenTrades ++;    
   }   

   if(MaxOpenTrades > 0 && numberOfOpenTrades >= MaxOpenTrades) return(false);  
       
   if(MaxFrequencyMins  > 0)
   {   
      int recentSeconds = MaxFrequencyMins * 60;

      for(int i=OrdersTotal()-1;i>=0;i--){
         if(!OrderSelect(i, SELECT_BY_POS)) continue;
         if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
         if(TimeCurrent() - OrderOpenTime() < recentSeconds) return(false);
      }  

      int hstTotal=OrdersHistoryTotal();
   
      for(int i=hstTotal-1;i>=0;i--)
      {  
         if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
         if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;      
         if(TimeCurrent() - OrderOpenTime() < recentSeconds) return(false);
         break;            
      }  
   }
   
   if(Lots < MarketInfo(Symbol(),MODE_MINLOT)) return(false);
   
   if(AccountFreeMarginCheck(Symbol(), OP_SELL,Lots) <= 0) {
      Print("Sell order error: insufficient capital");
      return(false);
   }         
   
   if (StopLossPoints > 0)
   {
      if(StopLossMethod == 0)
      {
         sl = NormalizeDouble(Bid + StopLossPoints * Point, Digits);
         stopLossPoints = StopLossPoints;
      }
      else if(StopLossMethod == 1)
      {
         sl = NormalizeDouble(Bid + StopLossPoints * pipSize, Digits);
         stopLossPoints = StopLossPoints * (1 + 9 * (Digits == 3 || Digits == 5));
      }
      else
      {
         sl = StopLossPoints;
         stopLossPoints = (sl - Bid)/Point;         
      }
   }
 
   if (TakeProfitPoints > 0)
   {
      if(TakeProfitMethod == 0)
      {
         tp = NormalizeDouble(Bid - TakeProfitPoints * Point, Digits);
         takeProfitPoints = TakeProfitPoints;
      }
      else if (TakeProfitMethod == 1)
      {
         tp = NormalizeDouble(Bid - TakeProfitPoints * pipSize, Digits);
         takeProfitPoints = TakeProfitPoints * (1 + 9 * (Digits == 3 || Digits == 5));
      }
      else
      {
         tp = TakeProfitPoints;
         takeProfitPoints = (Bid - tp)/Point;
      }
   }     
      
   double stopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD);
   
   if( (sl > 0 && stopLossPoints <= stopLevel) || (tp > 0 && takeProfitPoints <= stopLevel) )
   {
      Print("Cannot Sell: Stop loss and take profit must be at least "
      + DoubleToStr(MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD),0)
      + " points away from the current price");
      return (false);
   }
      
   RefreshRates();
    int result = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, sl, tp, "FxProQuant" + "(" + WindowExpertName() + ") " + TradeComment,__STRATEGY_MAGIC + MagicIndex);

    if (result == -1){
       Print("Failed to Sell: " + IntegerToString(GetLastError()));
       Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
       return(false);
    }
    
   return(true);    
}


bool Buy(int MagicIndex, double Lots, int StopLossMethod, double StopLossPoints, int TakeProfitMethod, double TakeProfitPoints, int Slippage, int MaxOpenTrades,
         int MaxFrequencyMins, string TradeComment)
{
   static double pipSize = 0;   
   if(pipSize == 0) pipSize = Point * (1 + 9 * (Digits == 3 || Digits == 5));

   double sl = 0, tp = 0;
   double stopLossPoints = 0, takeProfitPoints = 0;
   
   int numberOfOpenTrades = 0;
   
   for(int i=OrdersTotal()-1;i>=0;i--){
      if(!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      numberOfOpenTrades ++;    
   }   

   if(MaxOpenTrades > 0 && numberOfOpenTrades >= MaxOpenTrades) return(false);       
 
   if(MaxFrequencyMins  > 0)
   {   
      int recentSeconds = MaxFrequencyMins * 60;

      for(int i=OrdersTotal()-1;i>=0;i--){
         if(!OrderSelect(i, SELECT_BY_POS)) continue;
         if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
         if(TimeCurrent() - OrderOpenTime() < recentSeconds) return(false);
      }  

      int hstTotal=OrdersHistoryTotal();
   
      for(int i=hstTotal-1;i>=0;i--)
      {  
         if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
         if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;      
         if(TimeCurrent() - OrderOpenTime() < recentSeconds) return(false);
         break;            
      }  
   }
   
   if(Lots < MarketInfo(Symbol(),MODE_MINLOT)) return(false);
   
   if(AccountFreeMarginCheck(Symbol(), OP_SELL,Lots) <= 0) {
      Print("Buy error: insufficient capital");
      return(false);
   }   

   if (StopLossPoints > 0)
   {
      if(StopLossMethod == 0)
      {
         sl = NormalizeDouble(Ask - StopLossPoints * Point, Digits);
         stopLossPoints = StopLossPoints;
      }
      else if (StopLossMethod == 1)
      {
         sl = NormalizeDouble(Ask - StopLossPoints * pipSize, Digits);
         stopLossPoints = StopLossPoints * (1 + 9 * (Digits == 3 || Digits == 5));
      }
      else
      {
         sl  = StopLossPoints;
         stopLossPoints = (Ask - sl)/Point;
      }
   }
   
   if (TakeProfitPoints > 0)
   {
      if(TakeProfitMethod == 0)
      {
         tp = NormalizeDouble(Ask + TakeProfitPoints * Point, Digits);
         takeProfitPoints = TakeProfitPoints;
      }
      else if (TakeProfitMethod == 1)
      {
         tp = NormalizeDouble(Ask + TakeProfitPoints * pipSize, Digits);
         takeProfitPoints = TakeProfitPoints * (1 + 9 * (Digits == 3 || Digits == 5));
      }
      else
      {
         tp = TakeProfitPoints;
         takeProfitPoints = (tp - Ask)/Point;
      }
   }  
   
   double stopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD);
   
   if( (sl > 0 && stopLossPoints <= stopLevel) || (tp > 0 && takeProfitPoints <= stopLevel) )
   {
      Print("Cannot Buy: Stop loss and take profit must be at least "
      + DoubleToStr(MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD),0)
      + " points away from the current price");
      return (false);
   }
          
   RefreshRates();
    int result = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, sl, tp, "FxProQuant" + "(" + WindowExpertName() + ") " + TradeComment, __STRATEGY_MAGIC + MagicIndex);
    
    if (result == -1){
        Print("Failed to Buy: " + IntegerToString(GetLastError()));
        Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
       return(false);
    }
    
   return(true);
}


bool Close_All_Short_Trades(int MagicIndex)
{
   int total = OrdersTotal();
   bool result = true;

   for(int i=total-1;i>=0;i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      if(OrderType() != OP_SELL) continue;
      if(!OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red )){
         result = false;
         Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
      }
   }
   return(result);
}


bool Universal_Trailing_Stop (int MagicIndex, double Price, int ExtraDeviationPoints, int MinAdjustmentPoints)
{
   if(Price == 0 || Price == EMPTY_VALUE) return (true);

   double price, sl, tp;
   double point = MarketInfo(Symbol(),MODE_POINT);
   int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD));  
   int cmd;
      
   bool result = true;   
   double newSl;
   
   int total = OrdersTotal();
      for(int i=total-1;i>=0;i--){
      if (!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      
      cmd = OrderType();      
      sl = NormalizeDouble(OrderStopLoss(),Digits);
      tp = OrderTakeProfit();
       
      if (OrderType() == OP_BUY)
      {
         newSl = NormalizeDouble(Price - ExtraDeviationPoints*point,Digits);
         price = MarketInfo(Symbol(),MODE_BID);   
         if(((tp - price)/point) < stopLevel && tp != 0) continue;         
         if(((price - newSl)/point) < stopLevel)continue;        
         if (sl + MinAdjustmentPoints*point>= newSl) continue;       
         
         if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, tp, 0))
         {
            printf("Error: Failed to modify trade. Ticket #%i, error code: %i", OrderTicket(), GetLastError());
            result = false;
            Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
         }
      }  
      else if (OrderType() == OP_SELL)
      {
         newSl = NormalizeDouble(Price + ExtraDeviationPoints*point,Digits);
         price = MarketInfo(Symbol(),MODE_ASK);
         if(((price - tp)/point) < stopLevel) continue;
         if(((newSl - price)/point) < stopLevel) continue;   
         if (sl - MinAdjustmentPoints*point <= newSl && sl != 0) continue;
         
         if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, tp, 0))
         {
            printf("Error: Failed to modify trade. Ticket #%i, error code: %i", OrderTicket(), GetLastError());
            result = false;
            Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
         }         
       }      
   }   
   return(result);
}

first order is fine

after that they put sl randomly i don't know why

i want to modify sl on profit open price only

is something wrong with Universal_Trailing_Stop?

Can some one help me, please

Files:
Wrong.jpg  33 kb
 

Forum on trading, automated trading systems and testing trading strategies


Hello,

Please use the SRC button when you post code. Thank you.


This time, I edited it for you.


 
thank to src button post trik Alain Varleyen