Questions from Beginners MQL5 MT5 MetaTrader 5 - page 147

 
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   
   int copied=CopyRates(_Symbol,PERIOD_M1,D'2008.01.01 00:00:00',(datetime)TimeCurrent(),rates);
   Print(Bars(_Symbol,PERIOD_M1,D'2008.01.01',TimeCurrent()));
   if(copied>0)
     {
      Print(copied,"       ",rates[0].time,"  ",rates[copied-1].time);
      ExpertRemove();
     }
     else {Print("Требуется синхронизация с сервером !!!");ExpertRemove();}

I don't understand why the data on the zero bar is not correct, please advise

I get this result

2013.10.27 17:45:26 Core 1 2013.01.01 00:00:00 369878 2012.12.31 19:00:00 2012.01.02 00:00:00

2013.10.27 17:45:26 Core 1 2013.01.01 00:00:00 369878

I forgot to tell the whole thing in the expert.

Or in other words when testing EA from XXX date to YYY date, to what depth from XXX data can be downloaded?????????????????

 

I need advice on the code: I took an adviser from the database, tested it, added it, subtracted it, changed the coefficients to get a good picture, the picture seems to turn out, but nothing works on the demo, it’s the other way around, it’s like evil, I adjust everything as according to the articles taught and charts good for a month by 100% increases. So it’s only for the tester and it’s suitable or should it be tested somehow differently ??? I would also like to remake TreilingParabolikSAR so that not stop losses move along it, but laymen at a given distance from the price, maybe someone will tell you where to get it, so far it has not come across. Here is one of the resulting codes with good graphs - tell me what is wrong, what to fix, although everything may be wrong here ...

 //+------------------------------------------------------------------+
//|                                                EA_CCIT3_1-01.mq5 |
//|                                Copyright © 2012.08.19, Alexander |
//|                        https://www.mql5.com/en/users/Im_hungry |
//|ICQ: 609928564 | email: I-m-hungree@yandex.ru | skype:i_m_hungree |
//Эксперт построен на модифицированных индикаторах CCIT3_Simple_v_2-01 и CCIT3_noReCalc_v_3-01. /
//Открытие позиции на покупку при пересечении нулевой цены снизу-вверх, 
//продажа при пересечении сверху-вниз. Значения индикатора для определения 
//сигнала берутся за предыдущий бар.

//CCIT3_Simple_v_2-01 - модифицированный индикатор CCIT3 1.01, основа 
//расчетов которого базируется на индикаторе CCI с коэффициентом расчета, 
//просчитанным с начала истории. Индикатор имеет ограничение по количеству 
//рассчитываемых баров (Max_bars_calc).
//CCIT3_noReCalc_v_3-01 - упрощенный CCIT3_Simple_v_2-01 - формула 
//расчета которого не учитывает коэффициент пересчитываемого на каждом 
//баре с начала истории. Также имеет ограничение по количеству рассчитываемых 
//баров (Max_bars_calc).
//
//
//+------------------------------------------------------------------+
#property copyright "Copyright © 2012"
#property link        "EA_CCIT3_1-01"

#include <Sample_TrailingStop.mqh> // подключение класса трейлинг стопа

CParabolicStop Trailing; // создание экземпляра класса 

//---
input    string                section_1             =                     "===== Trade options" ;
input    double                Lots                  = 2 ;                 // Lots
input    double                TP                    = 31 ;               // TP
input    double                SL                    = 16 ;                   // SL
input    int                   Slippage               = 65 ;                 // Slippage
input    int                   magic                  = 2012081921 ;           // magic
input    int                   N_modify_sltp= 3 ;                   // N_modify_sltp
input    int                   trail                  = 45 ;                   // trail
input    int                   Max_drawdown           = 10000 ;                   // Max_drawdown
input    bool                  Trade_overturn= true ;               // Trade_overturn
//---
input    string                section_3             =                     "===== Simple CCIT3" ;
input    bool                  use_Simple_CCIT3      = true ;               // use_Simple_CCIT3_Smpl
input    int                   CCI_Period_Smpl       = 285 ;                 // CCI_Period_Smpl
input    ENUM_APPLIED_PRICE    CCI_Price_Type_Smpl   = PRICE_TYPICAL ;       // CCI_Price_Type_Smpl
input    int                   T3_Period_Smpl        = 60 ;                 // T3_Period_Smpl
input    double                Koeff_B_Smpl          = 0.618 ;               // Koeff_B_Smpl
//---
input    string                section_4             =                     "===== noReCalc CCIT3" ;
input    bool                  use_noReCalc_CCIT3    = false ;               // use_noReCalc_CCIT3
input    int                   CCI_Period_OtRng      = 230 ;                 // CCI_Period_OtRng
input    ENUM_APPLIED_PRICE    CCI_Price_Type_OtRng  = PRICE_TYPICAL ;       // CCI_Price_Type_OtRng
input    int                   T3_Period_OtRng       = 170 ;                 // T3_Period_OtRng
input    double                Koeff_B_OtRng         = 1.618 ;               // Koeff_B_OtRng
input double TrailingSARStep    =   0.02 ; // Шаг Parabolic
input double TrailingSARMaximum =   0.2 ; // Максимум Parabolic

//+------------------------------------------------------------------+
//| global parameters                                                |
//+------------------------------------------------------------------+
double CCIT3[ 2 ],Trail_stop; int handle_CCIT3; datetime _time;
int STP,TKP;

#include <ExpertAdvisor.mqh>
#include <Trade\DealInfo.mqh>

input double LotKoef= 1 ; // множитель для лота при убытке
input int Dist= 60 ;       // расстояние до стоплоса и тейкпрофита
//---
class CMartiEA : public CExpertAdvisor
  {
protected :
   double             m_lots;       // Лот
   double             m_lotkoef;     // множитель для лота при убытке
   int                m_dist;       // расстояние до стоплоса и тейкпрофита
   CDealInfo         m_deal;       // последняя сделка
   bool               m_first;       // флаг открытия первой сделки

public :
   void CMartiEA() { }
   void ~CMartiEA() { }
   virtual bool       Init( string smb, ENUM_TIMEFRAMES tf); // инициализация
   virtual void       OpenPosition();
   virtual void       CheckPosition();
  };
//------------------------------------------------------------------    Init
bool CMartiEA::Init( string smb, ENUM_TIMEFRAMES tf)
  {
   if (!CExpertAdvisor::Init( 0 ,smb,tf)) return ( false ); // инициализация родительского класса
   m_lots=Lots; m_lotkoef=LotKoef; m_dist=Dist;       // скопировали параметры
   m_deal.Ticket( 0 ); m_first= true ;
   m_bInit= true ; return ( true );                         // "торговля разрешена"
  }
//------------------------------------------------------------------    OnTrade
void CMartiEA::OpenPosition()
  {
   if (!CExpertAdvisor::Main()) return ;                       // вызов родительской функции
   if (!m_first) return ;                                       // если уже открывали начальную позицию
   ulong deal=DealOpen( ORDER_TYPE_BUY ,m_lots,m_dist,m_dist)|| // открыли начальную позицию
              DealOpen( ORDER_TYPE_SELL ,m_lots,m_dist,m_dist); // открыли начальную позицию

   if (deal> 0 ) { m_deal.Ticket(deal); m_first= false ; }         // если позиция существует
  }
//------------------------------------------------------------------    OnTrade
void CMartiEA::CheckPosition()
  {
   if (!CExpertAdvisor::Main()) return ; // вызов родительской функции
   if (m_first) return ;                 // если еще не открыли начальную позицию
   if ( PositionSelect (m_smb)) return ;   // если позиция существует

                                       // проферяем профит предыдущей позиции
   double lot=m_lots;                       // начальный лот
   long dir=m_deal.Type();                   // предыдущее направление
   if (CountProfitByDeal(m_deal.Ticket())< 0 ) // если был убыток
     {                                     //здесь убрал строку умножения все равно умножает и не переварачивает
      dir=ReversType(m_deal.Ticket());             // перевернули позицию
     }
   ulong deal=DealOpen(dir,lot,m_dist,m_dist); // открыли позицию
   if (deal> 0 ) m_deal.Ticket(deal);             // запомнили тикет
  }

CMartiEA ea; // экземпляр объекта
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
   ea.Init( Symbol (), Period ()); // инициализируем эксперт
//--- Инициализация (установка основных параметров)
   Trailing.Init( _Symbol , PERIOD_CURRENT , true , true , false );
//--- Установка параметров используемого типа трейлинг стопа
   if (!Trailing.SetParameters(TrailingSARStep,TrailingSARMaximum))
     {
       Alert ( "trailing error" );
       return (- 1 );
     }
   Trailing.StartTimer(); // Запуск таймера
   Trailing.On();         // Включение


   if ((use_Simple_CCIT3 && use_noReCalc_CCIT3) || (!use_Simple_CCIT3 && !use_noReCalc_CCIT3))
     {
       Alert ( "Wrong Settings : choose one of use_Simple_CCIT3/use_noReCalc_CCIT3" );
       Alert ( "Expert Removed" );
       ExpertRemove ();
     }
   if (use_Simple_CCIT3)
     {
      handle_CCIT3= iCustom ( Symbol (), NULL , "CCIT3_Simple_v_2-01" ,CCI_Period_Smpl,CCI_Price_Type_Smpl,T3_Period_Smpl,Koeff_B_Smpl, 100000 );
       if (handle_CCIT3== INVALID_HANDLE )
        {
         Print ( "Error in loading CCIT3_Simple_v_2-01. Error : " , GetLastError ());
         return (- 1 );
        }
     }
   if (use_noReCalc_CCIT3)
     {
      handle_CCIT3= iCustom ( Symbol (), NULL , "CCIT3_noReCalc_v_3-01" ,CCI_Period_OtRng,CCI_Price_Type_OtRng,T3_Period_OtRng,Koeff_B_OtRng, 100000 );
       if (handle_CCIT3== INVALID_HANDLE )
        {
         Print ( "Error in loading Outrunning CCIT3_noReCalc_v_3-01. Error : " , GetLastError ());
         return (- 1 );
        }
     }
//---
   return ( 0 );
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTimer ()
  {
   Trailing.Refresh();
  }
//+------------------------------------------------------------------+
//| deinitialization function                                        |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
   IndicatorRelease (handle_CCIT3);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
   ea.OpenPosition(); // обрабатываем тик - открываем первый одрера
   Trailing.DoStoploss();

   datetime Now_time[ 1 ];
   int coptTime= CopyTime ( Symbol (), NULL , 0 , 1 ,Now_time);
   if (Now_time[ 0 ]>_time && coptTime!=- 1 )
     {
      _time=Now_time[ 0 ];
       int copy1= CopyBuffer (handle_CCIT3, 0 , 1 , 2 ,CCIT3);
       if (copy1<= 0 ) return ;
       if (! PositionSelect ( Symbol ()))
        {
         if (CCIT3[ 0 ]<= 0 && CCIT3[ 1 ]> 0 ) open( 0 );
         if (CCIT3[ 0 ]>= 0 && CCIT3[ 1 ]< 0 ) open( 1 );
        }
       else
        {
         if (Trade_overturn)
           {
             int type=( int ) PositionGetInteger ( POSITION_TYPE );
             if (type== 0 && CCIT3[ 0 ]>= 0 && CCIT3[ 1 ]< 0 )
               if (close()) open( 1 );
             if (type== 1 && CCIT3[ 0 ]<= 0 && CCIT3[ 1 ]> 0 )
               if (close()) open( 0 );
           }
        }
     }
   if (trail> 0 )
     {
       if ( PositionSelect ( Symbol ()) && PositionGetDouble ( POSITION_PROFIT )> 0 )
        {
         int type=( int ) PositionGetInteger ( POSITION_TYPE );
         double Price= 0 ;
         if (type== 0 )
           {
            Price= SymbolInfoDouble ( Symbol (), SYMBOL_BID )-trail* Point ();
           }
         if (type== 1 )
           {
            Price= SymbolInfoDouble ( Symbol (), SYMBOL_ASK )+trail* Point ();
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Open trade function                                              |
//+------------------------------------------------------------------+
void open( int type)
  {
   double pr_open= 0.0 ,_sl= 0.0 ,_tp= 0.0 ,_nLt=Lots;
   if (Max_drawdown> 0 )
     {
      _nLt= NormalizeDouble ((Lots* AccountInfoDouble ( ACCOUNT_BALANCE )/Max_drawdown), 2 );
       if ( SymbolInfoDouble ( Symbol (), SYMBOL_VOLUME_MAX )<_nLt)
        {
         _nLt= SymbolInfoDouble ( Symbol (), SYMBOL_VOLUME_MAX );
         Alert ( "Exceed the maximum Lot Volume. Will be installed the limit: " ,_nLt);
        }
     }
   MqlTradeRequest mrequest; MqlTradeResult mresult;
   ZeroMemory (mrequest);
   mrequest.action    = TRADE_ACTION_DEAL ;
   mrequest.symbol    = Symbol ();
   mrequest.volume    = _nLt;
   mrequest.magic     = magic;
   mrequest.deviation = Slippage;
   if (type== 0 )
     {
      mrequest.type= ORDER_TYPE_BUY ;
      mrequest.price= SymbolInfoDouble ( Symbol (), SYMBOL_ASK );
       if (SL> 0 ) _sl=mrequest.price-(SL* Point ());
       if (TP> 0 ) _tp=mrequest.price+(TP* Point ());
     }
   if (type== 1 )
     {
      mrequest.type= ORDER_TYPE_SELL ;
      mrequest.price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
       if (SL> 0 ) _sl=mrequest.price+(SL* Point ());
       if (TP> 0 ) _tp=mrequest.price-(TP* Point ());
     }
//---
   if (! OrderSend (mrequest,mresult))
       Print ( "error Opened order    __FUNCTION__" , __FUNCTION__ , ": " ,mresult.comment, " answer code " ,mresult.retcode);
   else
     {
      Trail_stop= 0 ;
       if (SL> 0 || TP> 0 )
        {
         for ( int k= 0 ; k<=N_modify_sltp; k++)
           {
             int minD=( int ) SymbolInfoInteger ( Symbol (), SYMBOL_TRADE_STOPS_LEVEL );
             MqlTradeRequest          prequest;
             MqlTradeResult           presult;
             ZeroMemory (prequest);
            prequest.action       = TRADE_ACTION_SLTP ;
            prequest.symbol       = Symbol ();
            prequest.sl           = NormalizeDouble (_sl, Digits ());
            prequest.tp           = NormalizeDouble (_tp, Digits ());
             if (! OrderSend (prequest,presult))
              {
               Print ( "error modif order = " , __FUNCTION__ , ": " ,presult.comment, " answer code " ,presult.retcode);
               Sleep ( 1000 );
              }
             else
              {
               Print ( "successful modify order = " , __FUNCTION__ , ": " ,presult.comment, " answer code " ,presult.retcode);
               return ;
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Close trade function                                             |
//+------------------------------------------------------------------+
bool close()
  {
   MqlTradeRequest mrequest;
   MqlTradeResult mresult;
   ZeroMemory (mrequest);
   if ( PositionSelect ( Symbol ()))
     {
      mrequest.action= TRADE_ACTION_DEAL ;
       if ( PositionGetInteger ( POSITION_TYPE )== POSITION_TYPE_BUY )
         mrequest.price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
       if ( PositionGetInteger ( POSITION_TYPE )== POSITION_TYPE_SELL )
         mrequest.price= SymbolInfoDouble ( Symbol (), SYMBOL_ASK );
      mrequest.symbol  = Symbol ();
      mrequest.volume  = PositionGetDouble ( POSITION_VOLUME );
      mrequest.magic   = PositionGetInteger ( POSITION_MAGIC );
       if ( PositionGetInteger ( POSITION_TYPE )== POSITION_TYPE_BUY )
         mrequest.type= ORDER_TYPE_SELL ;
       if ( PositionGetInteger ( POSITION_TYPE )== POSITION_TYPE_SELL )
         mrequest.type= ORDER_TYPE_BUY ;
      mrequest.deviation=Slippage;
       if (! OrderSend (mrequest,mresult)) { GetLastError (); return ( false );}
       else return ( true );
     }
   return ( false );
  }
//------------------------------------------------------------------    OnTrade
void OnTrade ()
  {
   ea.CheckPosition(); // обрабатываем торговое событие
  }
//+------------------------------------------------------------------+
 

Testing a certain value, above which a trade is opened.

Parameters for entry:

bool Sell_Condition = (signal >= sgl);

I choose the value of variable sgl in the tester:

input double sgl=0.003;

variable type "signal" double.

When running a single test I see that with sgl=0.003 the entry is performed at 0.0024, 0.0027, 0.0015, etc.

The triggering logic is correct, but the execution accuracy is not.

How can I improve the execution accuracy?

 
forexman77:

...

How do you improve the accuracy of your performance?

Try it:

bool Sell_Condition = (signal >= sgl)? true : false;
 

Is there a relatively easy way to convert a date from a "non-standard" string format to datetime or at least an easily convertible string format?

In particular, if the month in the string is Jan/Jeb/..., how do I feed it to the script? I mean, only by manually picking the month from the string, by replacing it with the appropriate number in 12 variations? Or am I missing somewhere how to specify the format for StringToTime etc?

I've got a construction like this handling it right now:

int nmonth = buff[1]=="Jan"?01:buff[1]=="Feb"?02:buff[1]=="Mar"?03:buff[1]=="Apr"?04:buff[1]=="May"?05:buff[1]=="Jun"?06:
             buff[1]=="Jul"?07:buff[1]=="Aug"?08:buff[1]=="Sep"?09:buff[1]=="Oct"?10:buff[1]=="Nov"?11:buff[1]=="Dec"?12:01;

...but somehow I don't like it, although it works conventionally.

 
Made an EA based on three moving averages.

MA_1_t - small period, MA_2_t - medium period, MA_3_t - large period.

If I do the following conditions:

bool Buy_Condition_1=(MA_1_t < MA_2_t && MA_2_t < MA_3_t);

then trades are opened.

The conditions are reversed:

bool Buy_Condition_1=(MA_1_t > MA_2_t && MA_2_t > MA_3_t);

Not a single trade. What could be the reason?

EA code:

#property copyright ""
#property link      ""
#property version   "1.00"
//--- input parameters
input ushort      StopLoss=600;
input ushort      TakeProfit=450;
input int      EA_Magic=12345;   // Magic Number советника
input uchar ma_period_1=5;
input uchar ma_period_2=15;
input uchar ma_period_3=30;
input double   Lot=0.01;
//--- глобальные переменные
int STP,TKP;    // будут использованы для значений Stop Loss и Take Profit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Для работы с брокерами, использующими 5-ти значные котировки,
//--- умножаем на 10 значения SL и TP
   STP = StopLoss;
   TKP = TakeProfit;   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
double MA_1_t = iMA(NULL,0,ma_period_1,0,MODE_EMA,PRICE_CLOSE);
double MA_2_t = iMA(NULL,0,ma_period_2,0,MODE_EMA,PRICE_CLOSE);
double MA_3_t = iMA(NULL,0,ma_period_3,0,MODE_EMA,PRICE_CLOSE);
//---
MqlTick latest_price;       // Будет использоваться для текущих котировок
MqlTradeRequest mrequest;    // Будет использоваться для отсылки торговых запросов
MqlTradeResult mresult;      // Будет использоваться для получения результатов выполнения торговых запросов
MqlRates mrate[];           // Будет содержать цены, объемы и спред для каждого бара
ZeroMemory(mrequest);       // Инициализация полей структуры mrequest
//--- Получить текущее значение котировки в структуру типа MqlTick
   if(!SymbolInfoTick(_Symbol,latest_price))
     {
      Alert("Ошибка получения последних котировок - ошибка:",GetLastError(),"!!");
      return;
     }
//--- есть ли открытые позиции?
   bool Buy_opened=false;  // переменные, в которых будет храниться информация 
   bool Sell_opened=false; // о наличии соответствующих открытых позиций

   if(PositionSelect(_Symbol)==true) // есть открытая позиция
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //это длинная позиция
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // это короткая позиция
        }
     }
bool Buy_Condition_1=(MA_1_t > MA_2_t && MA_2_t > MA_3_t);
//--- собираем все вместе
if(Buy_Condition_1)
        {
           // есть ли в данный момент открытая позиция на покупку?
         if(Buy_opened)
           {
            Alert("Уже есть позиция на продажу!!!");
            return;    // не добавлять к открытой позиции на продажу
           }
         mrequest.action = TRADE_ACTION_DEAL;                                  // немедленное исполнение
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);           // последняя цена ask
         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;                                            // символ
         mrequest.volume = Lot;                                                // количество лотов для торговли
         mrequest.magic = EA_Magic;                                            // Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                       // ордер на покупку
         mrequest.type_filling = ORDER_FILLING_FOK;                            // тип исполнения ордера - все или ничего
         mrequest.deviation=100;                                               // проскальзывание от текущей цены
         //--- отсылаем ордер
         OrderSend(mrequest,mresult);
         // анализируем код возврата торгового сервера
         if(mresult.retcode==10009 || mresult.retcode==10008) //запрос выполнен или ордер успешно помещен
           {
            Alert("Ордер Buy успешно помещен, тикет ордера #:",mresult.order,"!!");
           }
         else
           {
            Alert("Запрос на установку ордера Buy не выполнен - код ошибки:",GetLastError());
            return;
           }
        }
     }
 
forexman77:

MA_1_t - small period, MA_2_t - medium period, MA_3_t - large period.

If I do the following conditions:

then trades are opened.

The conditions are reversed:

Not a single trade. What could be the reason?

EA code:

To get an indicator value, you need to create an indicator handle in OnInit, and then copy the value into an array using CopyBuffer in OnTick. The article Trading Operations in MQL5 just shows you how to write easier code to open/close a position/order.
 
paladin800:
To get the value of the indicator you need to create an indicator handle in OnInit, and then copy the value into an array using CopyBuffer in OnTick. The article Trading Operations in MQL5 just shows how to write easier code for opening/closing a position/order.
Thank you! It's quite different in MQL4, it's simpler. But MQL5 is faster and more accurate, in my opinion.
 

Can you tell me how to close a pending order that did not open? I am trying to do it this way:

.......................
    if((PositionsTotal()<1) && PositionSelect(_Symbol))          // Закрываем отложный ордер Buy
    {                                               
     BuyStopPositionClose();
     }
 
 if((PositionsTotal()<1) && PositionSelect(_Symbol))          // Закрываем отложный ордер Sell
    {                                               
     SellStopPositionClose();
     }
...............................

//+------------------------------------------------------------------+
//| Закрытие Buy stop переворотной позиции                                         |
//+------------------------------------------------------------------+
void BuyStopPositionClose()
  {
 
   ZeroMemory(mrequest);
   ZeroMemory(mresult);

   double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);   // лучшее предложение на покупку
   double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);   // лучшее предложение на продажу

 
     {
      mrequest.action = TRADE_ACTION_REMOVE;             // Удаление выставленного ордера
       mrequest.symbol = _Symbol;
         mrequest.volume = Lot*2;
         mrequest.price=NormalizeDouble(Ask+(SL-45) *_Point,_Digits);
         mrequest.sl = NormalizeDouble(mrequest.price - SL2*_Point,_Digits);
         mrequest.tp = NormalizeDouble(mrequest.price + TP2*_Point,_Digits);
         mrequest.deviation=0;
          mrequest.magic = Mag2; 
         mrequest.type=ORDER_TYPE_BUY_STOP;
         mrequest.type_filling=ORDER_FILLING_FOK;
                   
            OrderSend(mrequest,mresult);                  // отсылаем ордер
     }
  }
  
  //+------------------------------------------------------------------+
//| Закрытие Sell stop переворотной позиции                                         |
//+------------------------------------------------------------------+
void SellStopPositionClose()
  {


   ZeroMemory(mrequest);
   ZeroMemory(mresult);

   double Ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);   // лучшее предложение на покупку
   double Bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);   // лучшее предложение на продажу

 
     {
      mrequest.action = TRADE_ACTION_REMOVE;              // Удаление выставленного ордера
      mrequest.symbol = _Symbol;
         mrequest.volume = Lot*2;
         mrequest.price=NormalizeDouble(Bid-(SL-45) *_Point,_Digits);
         mrequest.sl = NormalizeDouble(mrequest.price + SL2*_Point,_Digits);
         mrequest.tp = NormalizeDouble(mrequest.price - TP2*_Point,_Digits);
         mrequest.deviation=0;
         mrequest.magic = Mag2;
         mrequest.type=ORDER_TYPE_SELL_STOP;
         mrequest.type_filling=ORDER_FILLING_FOK;    
      OrderSend(mrequest,mresult);                      // отсылаем ордер
     }
  }
  
Or in line mrequest.price=NormalizeDouble(Bid-(SL-45) *_Point,_Digits); should I write other information? Thank you.
 
Crucian:

Can you tell me how to close a pending order that has not opened? I am trying to do it this way:

Or in line mrequest.price=NormalizeDouble(Bid-(SL-45) *_Point,_Digits); should I write other information? Thank you.
Just read "Modify and Delete Orders" in MQL5. You may find the answer there. I recommend to read the entire article.
Reason: