Error 4756 (ERR_TRADE_SEND_FAILED) using "Instant Execution" requests

 

I'm trying to buy and sell at market value with the "Instant Execution" method (see here https://www.mql5.com/en/docs/constants/structures/mqltraderequest).

I have filled the required properties of the request, but OrderCheck returns error code 4756, from the docs: 

ERR_TRADE_SEND_FAILED

4756

Trade request sending failed

 

I googled the error but couldn't find anything. I am using a demo acount and the strategy tester so there is no broker involved.

 

Note 1: The first buy and the first sell work. 

Note 2: If I remove the OrderCheck() calls, I all buy orders work successfully but sells still fail, it' doesn't make any sense.

Below the code : 


void OnTimer()

{

MqlTick curTick;

if(!SymbolInfoTick(Symbol(), curTick)) return;

if(...){ //true when I need to buy, false when I need to sell

Request request;

         request.action = TRADE_ACTION_DEAL;

         request.symbol = Symbol();

         request.volume = 1;

         request.price = curTick.ask;

         request.sl = 0;

         request.tp = 0;

         request.deviation = 0;

         request.type = ORDER_TYPE_BUY;

         request.type_filling = ORDER_FILLING_FOK;

 

   MqlTradeCheckResult checkResult;

         bool success = OrderCheck(request, checkResult);

         if(!success) Print("OrderCheck failed error: ", GetLastError());


         MqlTradeResult tradeResult;

         bool successTrade = OrderSend(request, tradeResult);

         if(!successTrade) Print("OrderSend (buy) failed error: ", GetLastError());


}else{

MqlTradeRequest request;

         request.action = TRADE_ACTION_DEAL;

         request.symbol = Symbol();

         request.volume = 1;

         request.price = curTick.bid;

         request.sl = 0;

         request.tp = 0;

         request.deviation = 0;

         request.type = ORDER_TYPE_SELL;

         request.type_filling = ORDER_FILLING_FOK;

 MqlTradeCheckResult checkResult;

         bool success = OrderCheck(request, checkResult);

         if(!success)Print("OrderCheck failed error: ", GetLastError());


         MqlTradeResult tradeResult;

         bool successTrade = OrderSend(request, tradeResult);

         if(!successTrade)Print("OrderSend (sell) failed error: ", GetLastError()); 

}

 

I am properly checking that trading is allowed :

 

int OnInit()

  {

      Print("SYMBOL_TRADE_EXEMODE= ", SymbolInfoInteger(Symbol(), SYMBOL_TRADE_EXEMODE));

      Check_SYMBOL_ORDER_MODE(Symbol());

      

   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)) 

      Alert("Automated trading is not allowed in the terminal settings!");

   

   if(!MQLInfoInteger(MQL_TRADE_ALLOWED))

      Alert("Automated trading is forbidden in the program settings for ",__FILE__);

         

   if(!AccountInfoInteger(ACCOUNT_TRADE_EXPERT))

      Alert("Automated trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN)," at the trade server side");     

   

   if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED))

      Comment("Trading is forbidden for the account ",AccountInfoInteger(ACCOUNT_LOGIN),

            ".\n Perhaps an investor password has been used to connect to the trading account.",

            "\n Check the terminal journal for the following entry:",

            "\n\'",AccountInfoInteger(ACCOUNT_LOGIN),"\': trading has been disabled - investor mode.");

                  

   EventSetTimer(10);//10sec

   return(INIT_SUCCEEDED);

  }

 

 
Everything works fine now without changing anything, I guess the demo servers had some issues.
 

request.type_filling = ORDER_FILLING_FOK

have a try ,change the ORDER_FILLING_FOK.because the symbol it's own ORDER_FILLING mode.

i'm not sure it's changeable.

i'm get a prolem when a use the CTrade  PositionOpen.some symbol can but some not with no error.now ,it's ok after the FILLING Mode changed.

 
Hello

Please check my expert

error 4756

thank you


//+------------------------------------------------------------------+

//|                                                       rrrr.mq5 |

//|                        Copyright 2018, MetaQuotes Software Corp. |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Copyright 2018, MetaQuotes Software Corp."

#property link      "https://www.mql5.com"

#property version   "1.00"

//--- input parameters

input int      StopLoss=50;

input int      TakeProfit=100;

input int      MOMENTUM_H=100;



input int      MOMENTUM_Period=14;

input int      ADX_Period=14;



input int      EA_Magic=12345;   // EA Magic Number

input double   Adx_Min=22.0;     // Minimum ADX Value

input double   Lot=0.1;          // Lots to Trade



input double   STOCHASTIC_Min=25;

input double   STOCHASTIC_Max=75;





//--- Other parameters



int StochasticHandle;  // handle for our STOCH indicator

int momentumHandle;  // handle for our MOMENTUM indicator

int adxHandle;  // handle for our ADX indicator





double signal[],StochasticVal[]; //  STOCH values for each bars

double momentumVal[]; //  MOMENTUM values for each bars

double plsDI[],minDI[],adxVal[]; // Dynamic arrays to hold the values of +DI, -DI and ADX values for each bars



double p_close; // Variable to store the close value of a bar

int STP, TKP;   // To be used for Stop Loss & Take Profit values

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//--- Do we have enough bars to work with

   if(Bars(_Symbol,_Period)<60) // if total bars is less than 60 bars

     {

      Alert("We have less than 60 bars, EA will now exit!!");

      return(-1);

     }



//--- Get handle for STOCH indicator

   StochasticHandle=iStochastic(NULL,PERIOD_CURRENT,5,3,3,MODE_EMA,STO_CLOSECLOSE);

//--- Get handle for MOMENTUM indicator

   momentumHandle=iMomentum(NULL,PERIOD_CURRENT,MOMENTUM_Period,PRICE_CLOSE);

//--- Get handle for ADX indicator

   adxHandle=iADX(NULL,0,ADX_Period);

;

//--- What if handle returns Invalid Handle

   if(adxHandle<0 ||  StochasticHandle<0 || momentumHandle<0 )

     {

      Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!!");

      return(-1);

     }

//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4

   STP = StopLoss;

   TKP = TakeProfit;

   if(_Digits==5 || _Digits==3)

     {

      STP = STP*10;

      TKP = TKP*10;

     }

   return(0);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//--- Release our indicator handles

   IndicatorRelease(adxHandle);



   

   IndicatorRelease(StochasticHandle);

   IndicatorRelease(momentumHandle);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

// We will use the static Old_Time variable to serve the bar time.

// At each OnTick execution we will check the current bar time with the saved one.

// If the bar time isn't equal to the saved time, it indicates that we have a new tick.



   static datetime Old_Time;

   datetime New_Time[1];

   bool IsNewBar=false;



// copying the last bar time to the element New_Time[0]

   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);

   if(copied>0) // ok, the data has been copied successfully

     {

      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time

        {

         IsNewBar=true;   // if it isn't a first call, the new bar has appeared

         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);

         Old_Time=New_Time[0];            // saving bar time

        }

     }

   else

     {

      Alert("Error in copying historical times data, error =",GetLastError());

      ResetLastError();

      return;

     }



//--- EA should only check for new trade if we have a new bar

   if(IsNewBar==false)

     {

      return;

     }

 

//--- Do we have enough bars to work with

   int Mybars=Bars(_Symbol,_Period);

   if(Mybars<60) // if total bars is less than 60 bars

     {

      Alert("We have less than 60 bars, EA will now exit!!");

      return;

     }



//--- Define some MQL5 Structures we will use for our trade

   MqlTick latest_price;      // To be used for getting recent/latest price quotes

   MqlTradeRequest request;  // To be used for sending our trade requests

   MqlTradeResult result;    // To be used to get our trade results

   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar

/*

     Let's make sure our arrays values for the Rates, ADX Values and MA values 

     is store serially similar to the timeseries array

*/



// the ADX values arrays

   ArraySetAsSeries(adxVal,true);



// the Stochastic arrays

   ArraySetAsSeries(StochasticVal,true);

// the momentum values arrays

   ArraySetAsSeries(momentumVal,true);

// the MA-8 values arrays

   ArraySetAsSeries(mrate,true);

   

//--- Get the last price quote using the MQL5 MqlTick Structure

   if(!SymbolInfoTick(_Symbol,latest_price))

     {

      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");

      return;

     }



//--- Get the details of the latest 3 bars

   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)

     {

      Alert("Error copying rates/history data - error:",GetLastError(),"!!");

      ResetLastError();

      return;

     }   

     

     

     

//--- Copy the new values of our indicators to buffers (arrays) using the handle

    

   if(CopyBuffer(StochasticHandle,0,0,3,StochasticVal)<0 || CopyBuffer(StochasticHandle,1,0,3,signal)<0)

     {

      Alert("Error copying STOCH indicator Buffers - error:",GetLastError(),"!!");

      ResetLastError();

      return;

     }

   if(CopyBuffer(momentumHandle,0,0,3,momentumVal)<0)

     {

      Alert("Error copying MOMENTUM indicator Buffers - error:",GetLastError(),"!!");

      ResetLastError();

      return;

     }

   if(CopyBuffer(adxHandle,0,0,3,adxVal)<0 || CopyBuffer(adxHandle,1,0,3,plsDI)<0

      || CopyBuffer(adxHandle,2,0,3,minDI)<0)

     {

      Alert("Error copying ADX indicator Buffers - error:",GetLastError(),"!!");

      ResetLastError();

      return;

     }



//--- we have no errors, so continue

//--- Do we have positions opened already?

   bool Buy_opened=false;  // variable to hold the result of Buy opened position

   bool Sell_opened=false; // variables to hold the result of Sell opened position



   if(PositionSelect(_Symbol)==true) // we have an opened position

     {

      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)

        {

         Buy_opened=true;  //It is a Buy

        }

      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)

        {

         Sell_opened=true; // It is a Sell

        }

     }



// Copy the bar close price for the previous bar prior to the current bar, that is Bar 1

   p_close=mrate[1].close;  // bar 1 close price





/*

    1. Check for a long/Buy Setup : MA-8 increasing upwards, 

    previous price close above it, ADX > 22, +DI > -DI

*/

//--- Declare bool type variables to hold our Buy Conditions



 

   bool Buy_Condition_2=(momentumVal[0]>MOMENTUM_H) ; // momentum Increasing upwards

  

   bool Buy_Condition_3 = (adxVal[0]>Adx_Min);          // Current ADX value greater than minimum value (22)

   bool Buy_Condition_4 = (plsDI[0]>minDI[0]);          // +DI greater than -DI



   bool Buy_Condition_5 = (StochasticVal[0]<STOCHASTIC_Max);          // 

   bool Buy_Condition_6 = (signal[0]<STOCHASTIC_Max);          //



//--- Putting all together   

   if(Buy_Condition_2)

     {

      if(Buy_Condition_3 && Buy_Condition_4 )

        {

          if(Buy_Condition_5 && Buy_Condition_6)

            {

 

                 

                      // any opened Buy position?

                      if(Buy_opened)

                        {

                         Alert("We already have a Buy Position!!!");

                         return;    // Don't open a new Buy Position

                        }

                      request.action = TRADE_ACTION_MODIFY;                                  // immediate order execution

                      request.price = NormalizeDouble(latest_price.ask,_Digits);           // latest ask price

                      request.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits); // Stop Loss

                      request.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits); // Take Profit

                      request.symbol = _Symbol;                                            // currency pair

                      request.volume = Lot;                                                 // number of lots to trade

                      request.magic = EA_Magic;                                             // Order Magic Number

                      request.type = ORDER_TYPE_BUY;                                        // Buy Order

                      request.type_filling = ORDER_FILLING_FOK;                             // Order execution type

                      request.deviation=100;                                                // Deviation from current price

                      //--- send order

                     

                        

                        OrderSend(request,result);

                      

                      // get the result code

                      if(result.retcode==10009 || result.retcode==10008) //Request is completed or order placed

                        {

                         Alert("A Buy order has been successfully placed with Ticket#:",result.order,"!!");

                        }

                      else

                        {

                         Alert("The Buy order request could not be completed -error:",GetLastError());

                         ResetLastError();           

                         return;

                        }

                   

                

              }

            }

       }                 

/*

    2. Check for a Short/Sell Setup : MA-8 decreasing downwards, 

    previous price close below it, ADX > 22, -DI > +DI

*/

//--- Declare bool type variables to hold our Sell Conditions

 

   bool Sell_Condition_1 =  (momentumVal[0]<MOMENTUM_H); // momentum Increasing upwards

   

   bool Sell_Condition_2 = (adxVal[0]>Adx_Min);                         // Current ADX value greater than minimum (22)

   bool Sell_Condition_3 = (plsDI[0]<minDI[0]);                         // -DI greater than +DI

 

   bool Sell_Condition_4 = (StochasticVal[0]>STOCHASTIC_Min);          // 

   bool Sell_Condition_5 = (signal[0]>STOCHASTIC_Min);          //





//--- Putting all together

   if(Sell_Condition_1 )

     {

      if(Sell_Condition_2 && Sell_Condition_3 )

        {

          if(Sell_Condition_4 && Sell_Condition_5)

            

                

                     {

                      // any opened Sell position?

                       if(Sell_opened)

                         {

                           Alert("We already have a Sell position!!!");

                           return;    // Don't open a new Sell Position

                         }

                       request.action=TRADE_ACTION_MODIFY;                                // immediate order execution

                       request.price = NormalizeDouble(latest_price.bid,_Digits);           // latest Bid price

                       request.sl = NormalizeDouble(latest_price.bid + STP*_Point,_Digits); // Stop Loss

                       request.tp = NormalizeDouble(latest_price.bid - TKP*_Point,_Digits); // Take Profit

                       request.symbol = _Symbol;                                          // currency pair

                       request.volume = Lot;                                              // number of lots to trade

                       request.magic = EA_Magic;                                          // Order Magic Number

                       request.type= ORDER_TYPE_SELL;                                     // Sell Order

                       request.type_filling = ORDER_FILLING_FOK;                          // Order execution type

                       request.deviation=100;                                             // Deviation from current price

                       //--- send order

                       OrderSend(request,result);

                       // get the result code

                       if(result.retcode==10009 || result.retcode==10008) //Request is completed or order placed

                         {

                           Alert("A Sell order has been successfully placed with Ticket#:",result.order,"!!");

                         }

                       else

                         {

                           Alert("The Sell order request could not be completed -error:",GetLastError());

                           ResetLastError();

                           return;

                         }

                      }

                    

                

              }

          }

   return;

  }

//+------------------------------------------------------------------+

 
Hello
Good time
I wrote the following code in mql5, when I test it, it gives error 4756
Please guide me

In some cases, executes the purchase order successfully


#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "httpswww.mql5.com"
#property version   "1.00"

#include <Expert\Expert.mqh>
//--- available signals
#include <Expert\Signal\SignalAMA.mqh>
//--- available trailing
#include <Expert\Trailing\TrailingNone.mqh>
//--- available money management
#include <Expert\Money\MoneyFixedLot.mqh>
#include <Trade\Trade.mqh>




input int EMASMA=9;         //    EMASMA_number
input int EMASMA_SHIFT=6;   //   shift 

int magicbuy=1241;
int magicsell=1242;

int tick_num;
int closs_Order;
double ema[],sma[];
int ema1,sma1;
CTrade trade1;
double ask1,bid1,point1;
int digits1;


input ENUM_TIMEFRAMES periodha;                 //       Time frame
input ENUM_APPLIED_PRICE Price_Mode;            //        price mode 

 int OnInit()
  {
ema1=iMA(NULL,periodha,EMASMA,EMASMA_SHIFT,MODE_EMA,Price_Mode);
sma1=iMA(NULL,periodha,EMASMA,EMASMA_SHIFT,MODE_SMA,Price_Mode);
    return(0);
  }
    

/*+------------------------------------------------------------------+
 Tick event handler function                                    
+------------------------------------------------------------------+*/
void OnTick()
  {
  
   MqlTradeRequest buyreq,sellreq;
   MqlTradeResult  res1,res2;
   
   
   
ask1=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
bid1=SymbolInfoDouble(_Symbol,SYMBOL_BID); 
point1=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
digits1=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);

buyreq.type=ORDER_TYPE_BUY;
buyreq.symbol=_Symbol;
buyreq.magic=magicbuy;
buyreq.volume=0.01;
buyreq.sl=NormalizeDouble((bid1-50*point1),digits1);
buyreq.tp=NormalizeDouble((bid1+50*point1),digits1);
buyreq.price=bid1;
buyreq.action=TRADE_ACTION_DEAL;
buyreq.type_filling=ORDER_FILLING_FOK;
buyreq.deviation=500;


sellreq.type=ORDER_TYPE_SELL;
sellreq.symbol=_Symbol;
sellreq.magic=magicsell;
sellreq.volume=0.01;
sellreq.sl=NormalizeDouble((ask1+50*point1),digits1);
sellreq.tp=NormalizeDouble((ask1-50*point1),digits1); 
sellreq.price=ask1;
sellreq.action=TRADE_ACTION_DEAL;   
sellreq.type_filling=ORDER_FILLING_FOK;
sellreq.deviation=500;
  
if(crossMA()=="Cross_Up") {
close(magicsell);
if(PositionsTotal()==0)tick_num=OrderSend(buyreq,res1);
} 
if(crossMA()=="Cross_Down") {
close(magicbuy);
if(PositionsTotal()==0)closs_Order=OrderSend(sellreq,res2);
} 


Comment("cross signal =",crossMA(),"____",res1.retcode,"____",GetLastError()) ; 
 } 


 string crossMA()
 {
 
CopyBuffer(ema1,0,0,10,ema);
ArraySetAsSeries(ema,true);

CopyBuffer(sma1,0,0,10,sma);
ArraySetAsSeries(sma,true);
     
if      (ema[1]>sma[1]&&ema[2]<sma[2])
     return ("Cross_Up");
else if (ema[1]<sma[1]&&ema[2]>sma[2])
     return ("Cross_Down");
else return ("No_Cross");  
 }

  

//---------------------------- --------------------------------------

void close(int Magic)
{
    for (int i = PositionsTotal()-1; i >= 0; i--)
    {
        if (PositionGetTicket(i))
        {
            if (PositionGetInteger(POSITION_MAGIC)== Magic)
                bool yccb = trade1.PositionClose(PositionGetTicket(i));
        }
    }
}
 
Zohreh Tajmirriyahi:

Do not double post!

I have deleted your duplicate post!

 

Hi,

I'm having the same issue. The EA worked fine in the strategy tester, but now that i'm trying to run it in real time in the demo account i'm receiving error 4756. Does anyone knows why is this happening?

 
R3za1361 #:
Hello

Please check my expert

error 4756

thank you


Put:

MqlTradeRequest request={};

MqlTradeResult  result={};

before each request definition.


Reason: