Invalid request

 
Hi I have copy this functions in order to create a trailing stop but I am getting and Invalid request error thanks for any help
void TrailingSL() {
   double StopLossTemp;



//-----Get the opening time----------------


datetime Open_Trade_Time=PositionGetInteger(POSITION_TIME);

Print("Open_Trade_Time:",Open_Trade_Time);

double ht[], lt[];
MqlDateTime dt;
TimeCurrent(dt);
datetime TradeTimeCurrent=TimeCurrent();



 CopyHigh(_Symbol,PERIOD_M30,Open_Trade_Time,TradeTimeCurrent,ht);
 CopyLow(_Symbol,PERIOD_M30,Open_Trade_Time,TradeTimeCurrent,lt);
 
int highTradeIndex = ArrayMaximum(ht,0,WHOLE_ARRAY);

//Print("highIndex:",highIndex);

double highestTradeValue=ht[highTradeIndex];
Print("highestTradeValue:",highestTradeValue);

int lowTradeIndex = ArrayMinimum(lt,0,WHOLE_ARRAY);

//Print("lowIndex:",lowIndex);

double lowestTradeValue=lt[lowTradeIndex];
Print("lowestTradeValue:",lowestTradeValue);
 
 
 


//-----Get the opening time----------------


   
int i;   
   
   for(i = 0; i < PositionsTotal(); i++)
   {      
      if(Symbol()==PositionGetSymbol(i))
      {
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
         {
            if(PositionGetDouble(POSITION_PRICE_CURRENT) > PositionGetDouble(POSITION_PRICE_OPEN)) {
               
               StopLossTemp = highestTradeValue - trailing_stop;
               ChangePosition(StopLossTemp);
            }
         }
   
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         {
            if(PositionGetDouble(POSITION_PRICE_CURRENT) < PositionGetDouble(POSITION_PRICE_OPEN)) {
               StopLossTemp = lowestTradeValue + trailing_stop;
               ChangePosition(StopLossTemp);
            }
         }
      }
   }
}

void ChangePosition(double StopLossTemp) {

   MqlTradeRequest request;  // To be used for sending our trade requests
   MqlTradeResult result;    // To be used to get our trade results
   MqlTradeCheckResult checkresult;

   request.action = TRADE_ACTION_SLTP;
   request.symbol = Symbol();
   request.sl = NormalizeDouble(StopLossTemp,Digits());
   Print("StopLossTemp:",StopLossTemp);
   
   
   
   if(result.retcode==10009 || result.retcode==10008) //Request is completed or order placed
           {
            Alert("An order has been successfully placed with Ticket#:",result.order,"!!");
           }
         else
           {
            Alert("The order request could not be completed -error:",GetLastError()," with trade return code ",result.retcode);
            ResetLastError();
            return;
           }
 
     
   OrderSend(request,result);
}
 

Hi,

I have one suggestion and one question 

Suggestion: the

 OrderSend(request,result);

 should be putted before the check of the return code.

 Question: do you use the M30 chart ?

 
Thanks for the suggestion and yes I am using the M30 chart
 

Another suggestion is to check

if the stop loss is lower that the current price for the buy position

and higher that the current price for the sell position.

Something like this:

                if(posType == POSITION_TYPE_BUY)
                {
                        bidPrice = SymbolInfoDouble(pSymbol,SYMBOL_BID);
                        currentProfit = bidPrice - posOpenPrice;
                        if(pTrailPrice > currentStopLoss + step && currentProfit >= minProfit) 
                        {
                                request.sl = pTrailPrice;
                        }
                        else
                        {
                           //Print("TrailingStop, buy -> No conditions");
                           return(false);
                        }
                }
                else if(posType == POSITION_TYPE_SELL)
                {
                        askPrice = SymbolInfoDouble(pSymbol,SYMBOL_ASK);
                        currentProfit = posOpenPrice - askPrice;
                        if(pTrailPrice < currentStopLoss - step && currentProfit >= minProfit)
                        {
                                request.sl = pTrailPrice;
                        }
                        else
                        {
                           //Print("TrailingStop, sell -> No conditions");
                           return(false);
                        }
                }
Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Trade Constants / Order Properties - Documentation on MQL5
 
Thanks for the suggestion the first order in the tester is a buy and there is the proper distance 35pips between the bid price and the stoploss the error still remains as Invalid Request
 

For buy, you should also check that your sl are always below the imposed stop level 

   double currPrice = SymbolInfoDouble(pSymbol, SYMBOL_BID);
   double point     = SymbolInfoDouble(pSymbol, SYMBOL_POINT);
   double stopLevel = SymbolInfoInteger(pSymbol, SYMBOL_TRADE_STOPS_LEVEL) * point;
   double stopPrice = currPrice - stopLevel;

   
   if(pPrice < stopPrice)
   {
      // StopLossTemp remains unchanged
   }
   else
   {
      StopLossTemp = stopPrice;
   }
 
ZeroMemory(mrequest);
         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);           // latest ask price
         mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                            // currency pair
         mrequest.volume = Lot;                                                 // number of lots to trade
         mrequest.magic = EA_Magic;                                             // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                        // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                             // Order execution type
         mrequest.deviation=100;                                                // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
        }
     }
/*
 
Moreover I try to set up a stoploss and a take profit but it seems that they aren't setted up properly I am not getting any error and the trade opens
 

This is another problem, which I've just answer in another topic here

https://www.mql5.com/en/forum/12282

meaning that you need to send 2 orders:

1. for position opening

2. for setting the sl and tp

I can not place Stop Loss and not Take Profit to open an order.
I can not place Stop Loss and not Take Profit to open an order.
  • www.mql5.com
I can not place Stop Loss and not Take Profit to open an order.
 
Thanks again I just check and the stoplevel=0.0
 

When you use CopyXXX function, you have to check returned value, there is no garantie that the copy is done.

 int copyht = CopyHigh(_Symbol,PERIOD_M30,Open_Trade_Time,TradeTimeCurrent,ht);
 int copylt = CopyLow(_Symbol,PERIOD_M30,Open_Trade_Time,TradeTimeCurrent,lt);
 if (copyht<1 || copylt <1) return;

You have to initialize the value of your structure, try to add :

ZeroMemory(request);
request.action = TRADE_ACTION_SLTP;

You have also to follow the advice of launic, as there is no garantie that your stoploss value is valid.

If still that doesn't work, please post the log.

Reason: