Trailing Stop in EA does not get activated on VPS

To add comments, please log in or register
ryan smith
77
ryan smith  
for (int i = count; i > 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS) == false) continue;
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))
      { 
         if (OrderType() == OP_BUY)
           {
            if (Bma1<Bma2)
               {
               if ((adxBminus1Enter>adxBplus1Enter) && (adxBplus2Enter>adxBminus2Enter) && (adxBmainEnter>adxBMainLEnter))
                  {
             //---------------------------- Close the order ------------------------------------------
                  RefreshRates();
                  if (!OrderClose(OrderTicket(), OrderLots(), Bid, slipS, clrViolet)) Print("Error closing BUY order: ", GetLastError());
                                 
                  return;
                  }
               }
             // ----------------------------check for trailing stop ----------------------------------
              if (TrailingStop> 0)
               {
                RefreshRates();
                if (Bid - OrderOpenPrice() > Point * TrailingStop)
                  {
                  if (OrderStopLoss() < Bid - Point * TrailingStop)
                     {
                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0))
                        Print("Error applying trailing stop: ", GetLastError());
                     return;   
                     }
                  }
               } 
            } 
           //----------------------------------------------------------
           else if (OrderType() == OP_SELL)
            {
            if (ma1>ma2)
               {
                 if ((adxSplus1Enter>adxSminus1Enter>a) && (adxSplus2Enter<adxSminus2Enter) &&(adxSmainEnter>adxSMainLEnter)) 
             //---------------------------- Close the order ------------------------------------------
                  {
                  RefreshRates();
                  if (!OrderClose(OrderTicket(), OrderLots(), Ask, slipB, clrViolet)) Print("Error closing SELL order: ", GetLastError());
                  return;
                  }
               }
             // --------------------------------------Trailing stop----------------------
              if (TrailingStop > 0)  
               {                 
               RefreshRates();
               if (OrderOpenPrice() - Ask > Point * TrailingStop)
                  {
                  if ((OrderStopLoss() > Ask + Point * TrailingStop) || (OrderStopLoss() == 0))
                     {
                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0))
                        Print("Error applying trailing stop: ", GetLastError());
                     return;      
                     }
                  } 
                }  
            }

I am new to MQL4 programming, but have programmed in other languages. After learning the language over the last few months, I have written an EA with trailing stop. In Strategy Tester it works fine, but does not get activated on VPS. (My Internet connection quality is not good, so I rented a VPS for a month for trial purpose.) After moving my EA to a VPS, I have been watching on my local terminal, and have found that trailing stop does not get activated at all, even after the trade is profitable in both BUY and SELL cases . To test it, I have kept T railing Stop at a low value of 25 points. I have copied the code below, which I got from this forum. Any help will be really appreciated. I am using a 5-digit ECN broker for my trading.

Marco vd Heijden
Moderator
12701
Marco vd Heijden  

What was the error in the log ?

The code is incomplete.

ryan smith
77
ryan smith  
#include <stderror.mqh>
#include <stdlib.mqh>

input double Risk=1.0;

//-------------------------- MA Parameters -------------------------
input int period1=1;

input int period2=17;

//-------------------------- Buy Parameters -------------------------
input int slip =22;          
extern int TakeProfit=250;  
input int StopLoss=120;
input int TrailingStop=25;
input int adxBPeriodEnter=14;
input int adxBMainLEnter=25;
input int adxSPeriodEnter=13;
input int adxSMainLEnter=25;                             

int Magic = 215;

bool EachTickMode = False;
int BarCount;
int Current;
bool TickCheck = False;

//+-----------------------------------------------------------------------------------------------------------------+
//|                                              expert initialization function                                     |
//+-----------------------------------------------------------------------------------------------------------------+
int OnInit() {
   
   BarCount = Bars;
   if (EachTickMode) Current = 0; else Current = 1;
   return(INIT_SUCCEEDED);
}
//+-----------------------------------------------------------------------------------------------------------------+
//|                                             expert deinitialization function                                    |
//+-----------------------------------------------------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+-----------------------------------------------------------------------------------------------------------------+
//|                                                begin expert start function                                      |
//+-----------------------------------------------------------------------------------------------------------------+
void OnTick()
  {

//-----    

   // Initial data checks.
   if (Bars < 100)
   {
      Print("Less than 100 bars.");
      return;
   }

//----------------------MA indicator calculation during up/1 trend-----------------------
double ma1=iMA(NULL,0,period1,0,MODE_SMA,PRICE_CLOSE,1);
double ma2=iMA(NULL,0,period2,0,MODE_SMA,PRICE_CLOSE,1);
//----------------------ADX indicator calculation during up/1 trend----------------------
   double adxSmainEnter    = iADX(NULL, 0, adxSPeriodEnter, PRICE_CLOSE, MODE_MAIN, 1);              //to enter sell
   double adxSplus1Enter   = iADX(NULL, 0, adxSPeriodEnter, PRICE_CLOSE, MODE_PLUSDI, 1);
   double adxSplus2Enter   = iADX(NULL, 0, adxSPeriodEnter, PRICE_CLOSE, MODE_PLUSDI, 2);
   double adxSminus1Enter  = iADX(NULL, 0, adxSPeriodEnter, PRICE_CLOSE, MODE_MINUSDI, 1);
   double adxSminus2Enter  = iADX(NULL, 0, adxSPeriodEnter, PRICE_CLOSE, MODE_MINUSDI, 2);
   
   double adxBmainEnter    = iADX(NULL, 0, adxBPeriodEnter, PRICE_CLOSE, MODE_MAIN, 1);               //to enter buy
   double adxBplus1Enter   = iADX(NULL, 0, adxBPeriodEnter, PRICE_CLOSE, MODE_PLUSDI, 1);
   double adxBplus2Enter   = iADX(NULL, 0, adxBPeriodEnter, PRICE_CLOSE, MODE_PLUSDI, 2);
   double adxBminus1Enter  = iADX(NULL, 0, adxBPeriodEnter, PRICE_CLOSE, MODE_MINUSDI, 1);
   double adxBminus2Enter  = iADX(NULL, 0, adxBPeriodEnter, PRICE_CLOSE, MODE_MINUSDI, 2); 
//-----------------------------------------------------
   double order_sl=0, order_tp=0, lots=0;
   int    ticket=0, total;
 //---------------------------------------- 
// --------- get Order total 
   total = OrdersTotal();
   int count = 0;
   for (int i = 0; i < total; i++)
   {
      if (OrderSelect(i, SELECT_BY_POS) == false) continue;
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && ((OrderType() == OP_BUY) || (OrderType() == OP_SELL))) count++;
   }  
   //----------------------------
//+------------------------------------------------------------------------------------+
//|                                 Entry Conditions                                   |
//+------------------------------------------------------------------------------------+
 if (count == 0)                   //--no open order
    {     
//     if ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))            //Bar mode entry
//         { 
      if (ma1>ma2)
      //{
      if ((adxBplus1Enter>adxBminus1Enter) && (adxBplus2Enter<adxBminus2Enter) && (adxBmainEnter>adxBMainLEnter))   //buy signal in up trend
         {
         lots= getLots(Risk);
         RefreshRates();
         if (StopLoss > 0) order_sl = Ask - StopLoss * Point;
         order_tp = Ask + TakeProfit * Point;
         buyOrder(lots, order_sl, order_tp, slip, Magic);
         //return;
         }
        //}
       else if(ma1< ma2)
       //{
       if ((adxSminus1Enter>adxSplus1Enter) && (adxSplus2Enter>adxSminus2Enter) &&(adxSmainEnter>adxSMainLEnter))    //sell signal in up trend
         {
        lots= getLots(Risk);
        RefreshRates();
        if (StopLoss > 0) order_sl = Ask + StopLoss * Point;
        order_tp = Ask - TakeProfit * Point;
        sellOrder(lots, order_sl, order_tp, slip, Magic); 
        //return;
         }
        //}                                                         //end trend=-1 if loop entry conditions                                                                //end trend=0 if loop entry conditions
    }
//+------------------------------------------------------------------------------------+
//|                                 Exit Conditions                                    |
//+------------------------------------------------------------------------------------+
for (i = count; i > 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS) == false) continue;
      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))
      { 
         if (OrderType() == OP_BUY)
           {
            if (ma1<ma2)
               {
               if ((adxBminus1Enter>adxBplus1Enter) && (adxBplus2Enter>adxBminus2Enter) && (adxBmainEnter>adxBMainLEnter))
                  {
             //---------------------------- Close the order ------------------------------------------
                  RefreshRates();
                  if (!OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrViolet)) Print("Error closing BUY order: ", GetLastError());
                                 
                  return;
                  }
               }
             // ----------------------------check for trailing stop ----------------------------------
              if (TrailingStop> 0)
               {
                RefreshRates();
                if (Bid - OrderOpenPrice() > Point * TrailingStop)
                  {
                  if (OrderStopLoss() < Bid - Point * TrailingStop)
                     {
                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0))
                        Print("Error applying trailing stop: ", GetLastError());
                     return;   
                     }
                  }
               } 
            } 
           //----------------------------------------------------------
           else if (OrderType() == OP_SELL)
            {
            if (ma1>ma2)
               {
                 if ((adxSplus1Enter>adxSminus1Enter) && (adxSplus2Enter<adxSminus2Enter) &&(adxSmainEnter>adxSMainLEnter)) 
             //---------------------------- Close the order ------------------------------------------
                  {
                  RefreshRates();
                  if (!OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrViolet)) Print("Error closing SELL order: ", GetLastError());
                  return;
                  }
               }
             // --------------------------------------Trailing stop----------------------
              if (TrailingStop > 0)  
               {                 
               RefreshRates();
               if (OrderOpenPrice() - Ask > Point * TrailingStop)
                  {
                  if ((OrderStopLoss() > Ask + Point * TrailingStop) || (OrderStopLoss() == 0))
                     {
                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0))
                        Print("Error applying trailing stop: ", GetLastError());
                     return;      
                     }
                  } 
                }  
            }
            //----------------------------- 
        }         
    }//---------------end for loop
  //}  //Bar mode entry
  return;
  }
//+------------------------------------------------------------------------------------+
//|                                 getLots function                                   |
//+------------------------------------------------------------------------------------+
double getLots(double risk)
   {
   double acctBal, margin, lotincrement,lotDigits, numLots;
   
   acctBal=AccountFreeMargin(); 
   margin=MarketInfo(Symbol(),MODE_MARGINREQUIRED); 
   lotincrement=MarketInfo(Symbol(), MODE_LOTSTEP);
   
   if (lotincrement==0.01) lotDigits=2;
   else 
   {
   if (lotincrement==0.1)lotDigits=1;
   else lotDigits=0;                                  //for lotincrement=1
   }

   numLots=NormalizeDouble((acctBal*risk)/(margin*100),lotDigits);
   
   int    ordersTotal=OrdersHistoryTotal();
   if (ordersTotal<1) {numLots=MarketInfo(Symbol(), MODE_MINLOT);}
   
   return(numLots);
   }
//+---------------------------------end: getLots function------------------------------+
//+------------------------------------------------------------------------------------+
//|                                 buyOrder function                                  |
//+------------------------------------------------------------------------------------+
int buyOrder(double lots, double orderSL, double orderTP, int slipB, int magic)
   {  
            RefreshRates();
            int ticket=OrderSend(Symbol(),OP_BUY,lots,Ask,slipB,orderSL,orderTP,"ADX Self Signal M5",magic,0,clrWhiteSmoke);
            if(ticket<=0) Print("Error = ",ErrorDescription(GetLastError()));
            else Print("ticket = ",ticket); 
            return(0);
  }
//+-----------------------------end: buyOrder function---------------------------------+

//+------------------------------------------------------------------------------------+
//|                                 sellOrder function                                 |
//+------------------------------------------------------------------------------------+
   int sellOrder(double lots, double orderSL, double orderTP, int slipS, int magic)
   {
            RefreshRates();
            int ticket=OrderSend(Symbol(),OP_SELL,lots,Bid,slipS,orderSL,orderTP,"ADX Self Signal M5",magic,0,clrWhiteSmoke);
            if(ticket<=0) Print("Error = ",ErrorDescription(GetLastError()));
            else Print("ticket = ",ticket); 
            return(0);
  }
//+-----------------------------end: sellOrder function--------------------------------+
//+------------------------------------------------------------------+
Marco vd Heijden
:

What was the error in the log ?

The code is incomplete.

Thanks much, Marco, for your help. I posted the code only for the Trailing Stop part. Here is the complete code for the EA. There was no error in the log. In fact, the log shows that no modification to any order was ever made in the VPS expert journal.

Marco vd Heijden
Moderator
12701
Marco vd Heijden  

Your problem is here

int count = 0;

This value doesnt change and as a result of that

for (i = count; i > 0; i--)

i is never > 0

Mostafa Moujezi Zarandi
11841
Mostafa Moujezi Zarandi  

Use this for youy loop


for (int i = OrdersTotal() - 1; i >= 0; i--)
{
 //
}
ryan smith
77
ryan smith  
Marco vd Heijden:

Your problem is here

This value doesnt change and as a result of that

i is never > 0


Marco, I cannot thank you enough for pinpointing the problem and helping me out. I did run a little debugging process by inserting "Alert("count1=", count);" just after the "for (int i = 0; i < total; i++) { //}" loop. The log entries show that value of count does change after an order is placed. However, the "for (int i = count; i > 0; i--) {//}" loop never gets executed. It gives me a starting point to work on the problem. So, much appreciated.

ryan smith
77
ryan smith  
Mostafa Moujezi Zarandi:

Use this for youy loop


Thanks much, Mostafa, for helping me out. I do have a question, though. If OrdersTotal()=1, then if I start "for (int i = OrdersTotal()-1; i >= 0; i--) {//}" loop, it will not get executed because i=OrdersTotal()-1=1-1=0. Should not I start this for-loop at i=OrdersTotal() instead?

William Roeder
20208
William Roeder  
ryan smith: If OrdersTotal()=1, then if I start "for (int i = OrdersTotal()-1; i >= 0; i--) {//}" loop, it will not get executed because i=OrdersTotal()-1=1-1=0. Should not I start this for-loop at i=OrdersTotal() instead?

I equals zero and therefor "i >= 0" is true.

ryan smith
77
ryan smith  
William Roeder:

I equals zero and therefor "i >= 0" is true.

Thanks much, William. You are absolutely right! I forgot about ">". Much appreciated.

To add comments, please log in or register