Questions des débutants 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();}

Je ne comprends pas pourquoi les données de la barre de zéro ne correspondent pas à la réalité.

J'obtiens ce résultat

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

J'ai oublié de tout raconter à l'expert.

Ou en d'autres termes, lorsque l'on teste l'EA de la date XXX à la date YYY, jusqu'à quel point les données de XXX peuvent être téléchargées ?????????????????.

 

J'ai besoin de conseils sur le code: j'ai pris un conseiller de la base de données, je l'ai testé, ajouté, soustrait, changé les coefficients pour obtenir une bonne image, l'image semble s'avérer, mais rien ne fonctionne sur la démo, c'est l'autre moyen autour, c'est comme le mal, j'ajuste tout en fonction des articles enseignés et des graphiques bons pour un mois par 100% d'augmentations. Donc, c'est seulement pour le testeur et c'est approprié ou devrait-il être testé différemment ??? Je voudrais également refaire TreilingParabolikSAR afin que les pertes ne s'arrêtent pas, mais les profanes à une distance donnée du prix, peut-être que quelqu'un vous dira où l'obtenir, jusqu'à présent, il n'a pas été rencontré. Voici l'un des codes résultants avec de bons graphiques - dites-moi ce qui ne va pas, ce qu'il faut corriger, même si tout peut être faux ici ...

 //+------------------------------------------------------------------+
//|                                                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(); // обрабатываем торговое событие
  }
//+------------------------------------------------------------------+
 

Test d'une certaine valeur, au-delà de laquelle une transaction est ouverte.

Paramètres d'entrée :

bool Sell_Condition = (signal >= sgl);

Je choisis la valeur de la variable sgl dans le testeur :

input double sgl=0.003;

variable de type "signal" double.

En exécutant un seul test, je vois qu'avec sgl=0.003 l'entrée est effectuée à 0.0024, 0.0027, 0.0015, etc.

La logique de déclenchement est correcte, mais la précision d'exécution ne l'est pas.

Comment puis-je améliorer la précision de l'exécution ?

 
forexman77:

...

Comment améliorez-vous la précision de vos performances ?

Essayez-le :

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

Existe-t-il un moyen relativement simple de convertir une date d'un format de chaîne "non standard" en datetime ou au moins en un format de chaîne facilement convertible ?

En particulier, si le mois dans la chaîne est Jan/Jeb/..., comment puis-je le transmettre au script ? Je veux dire, seulement en choisissant manuellement le mois dans la chaîne, en le remplaçant par le nombre approprié dans 12 variations ? Ou bien est-ce que je ne sais pas comment spécifier le format pour StringToTime etc ?

J'ai une construction comme celle-ci qui s'en occupe en ce moment :

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;

...mais quelque part, je n'aime pas ça, bien que ça fonctionne de manière conventionnelle.

 
Création d'un EA basé sur trois moyennes mobiles.

MA_1_t - petite période, MA_2_t - moyenne période, MA_3_t - grande période.

Si je fais les conditions suivantes :

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

puis les transactions sont ouvertes.

Les conditions sont inversées :

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

Pas un seul échange. Quelle pourrait être la raison ?

Code EA :

#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 - petite période, MA_2_t - moyenne période, MA_3_t - grande période.

Si je fais les conditions suivantes :

puis les transactions sont ouvertes.

Les conditions sont inversées :

Pas un seul échange. Quelle pourrait être la raison ?

Code EA :

Pour obtenir une valeur d'indicateur, vous devez créer un handle d'indicateur dans OnInit, puis copier la valeur dans un tableau en utilisant CopyBuffer dans OnTick. L'article Opérations de trading dans MQL5 vous montre simplement comment écrire un code plus simple pour ouvrir/fermer une position/un ordre.
 
paladin800:
Pour obtenir la valeur de l'indicateur, vous devez créer un handle d'indicateur dans OnInit, puis dans OnTick vous copiez la valeur dans un tableau en utilisant CopyBuffer. L'article Trading Operations in MQL5 montre simplement comment écrire un code plus simple pour ouvrir/fermer une position/un ordre.
Merci ! C'est très différent dans MQL4, c'est plus simple. Mais MQL5 est plus rapide et plus précis, à mon avis.
 

Pouvez-vous me dire comment fermer un ordre en attente qui n'a pas été ouvert ? J'essaie de le faire de cette façon :

.......................
    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);                      // отсылаем ордер
     }
  }
  
Ou dans la ligne mrequest.price=NormalizeDouble(Bid-(SL-45) *_Point,_Digits) ; dois-je écrire d'autres informations ? Merci.
 
Crucian:

Pouvez-vous me dire comment fermer un ordre en attente qui n'a pas été ouvert ? J'essaie de le faire de cette façon :

Ou dans la ligne mrequest.price=NormalizeDouble(Bid-(SL-45) *_Point,_Digits) ; dois-je écrire d'autres informations ? Merci.
Il suffit de lire "Modifier et supprimer les commandes" dans MQL5. Vous y trouverez peut-être la réponse. Je vous recommande de lire l'article en entier.
Raison: