Toute question des nouveaux arrivants sur MQL4 et MQL5, aide et discussion sur les algorithmes et les codes. - page 480

 
Aide avec un conseiller ne jugez pas strictement j'écris le premier

une fois. Ne veut pas fermer des positions , qu'est-ce qui ne va pas ???

 //+------------------------------------------------------------------+
//|                                                     cjdtnybr.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+


//--- Inputs
extern double Lots          = 0.1 ; // лот
extern int     StopLoss      = 500 ; // лось 
extern int     TakeProfit    = 500 ; // язь
extern int     Profit        = 500 ; // язь в рублях
extern int     Delta         = 100 ; // расстояние от фрактала
extern int     MAPeriod      = 12 ;   // период МА
extern int     Slip          = 30 ;   // проскальзывание
extern int     Shift         = 2 ;   // сдвиг баров назад
extern int     Expiration    = 44 ;   // время истечения в часах
extern int     Count         = 100 ; // количество открываемых ордеров
extern int     Magic         = 123 ; // магик
extern double TrailingStop  =- 10 ; //отрицательные значения для перевода в ордера БУ по достижении
extern bool    SetOnlyZeroValues= true ; //Признак изменения только нулевых значений
extern color   BuyOrderColor=Green;
extern color   SellOrderColor=Red;
int t= 0 ;
//+------------------------------------------------------------------+
int CountTrades()
  {
   int count= 0 ;
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY || OrderType ()== OP_SELL )
               count++;
           }
        }
     }
   return (count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double AllProfit()
  {
   double profit= 0 ;

   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY || OrderType ()== OP_SELL ) profit+= OrderProfit ();
           }
        }
     }
   return (profit);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAll()
  {
   bool cl;
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )       cl= OrderClose ( OrderTicket (), OrderLots (), Bid ,Slip,Blue);
             if ( OrderType ()== OP_SELL )      cl= OrderClose ( OrderTicket (), OrderLots (), Ask ,Slip,Red);
             if ( OrderType ()== OP_BUYSTOP )  cl= OrderDelete ( OrderTicket ());
             if ( OrderType ()== OP_SELLSTOP ) cl= OrderDelete ( OrderTicket ());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ClosePos()
  {
   double up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   double dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   for ( int i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )
              {
               if (up> 0 &&dn== 0 &&Profit> 0 )
                 {
                  CloseAll();
                 }
              }
             if ( OrderType ()== OP_SELL )
              {
               if (dn> 0 &&up== 0 )
                 {
                  CloseAll();
                 }
              }
           }
        }
     }
   return ;
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void OpenPos()
  {
   double up= 0 ,dn= 0 ,ma= 0 ,pr= 0 ,sl= 0 ,tp= 0 ;
   int     res;
//--- get ind
   up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   
//--- sell conditions
   if (up> 0 &&dn== 0 )
     {
      pr= NormalizeDouble (up+Delta* Point , Digits );
       if (StopLoss> 0 ) sl= NormalizeDouble (pr-StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (pr+TakeProfit* Point , Digits );
      res= OrderSend ( Symbol (), OP_BUYSTOP ,Lots,pr,Slip,sl,tp, "" ,Magic, TimeCurrent ()+Expiration* 3600 ,Red);
       return ;
     }
//--- buy conditions
   if (dn> 0 &&up== 0 )
     {
      pr= NormalizeDouble (dn-Delta* Point , Digits );
       if (StopLoss> 0 ) sl= NormalizeDouble (pr+StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (pr-TakeProfit* Point , Digits );
      res= OrderSend ( Symbol (), OP_SELLSTOP ,Lots,pr,Slip,sl,tp, "" ,Magic, TimeCurrent ()+Expiration* 3600 ,Blue);
       return ;
     }
//---
  }                      
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick ()
  {
   double up= 0 ,dn= 0 ,ma= 0 ;
//--- get ind
   up= iFractals ( NULL , 0 , MODE_UPPER ,Shift);
   dn= iFractals ( NULL , 0 , MODE_LOWER ,Shift);
   
   if (CountTrades()<Count && t!= Time [ 0 ])
     {
      OpenPos();
      t= Time [ 0 ];
     }
     
        
   
   
   
   
   
   

   Comment ( "\n  UP Fractal " ,up,
           "\n  DN Fractal " ,dn,
           "\n  Profit: " ,AllProfit());
//---
  

  
//--- check for trailing stop



  
   int cnt,total= OrdersTotal (); double kd;
   if ( Digits == 5 ) kd= 10 ; else kd= 1 ;
   double TP= MathAbs (TakeProfit)*kd;
   double SL= MathAbs (StopLoss)*kd;
   double TS=TrailingStop*kd;
   if (TP< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && TP!= 0 )
     {
       Comment ( "TakeProfit value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
   if (SL< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && SL!= 0 )
     {
       Comment ( "StopLoss value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
// Установка ограничения прибыли и убытка
   for (cnt= 0 ;cnt<total;cnt++)
     {
       if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
       continue ;
       if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
        {
         if ( OrderType ()== OP_BUY )
           {
             if ((( OrderTakeProfit ()== 0 && TP!= 0 ) || ( OrderStopLoss ()== 0 && SL!= 0 )) && !SetOnlyZeroValues)
              {
               if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()- Point *SL, OrderOpenPrice ()+ Point *TP, 0 ,BuyOrderColor))
                   Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderTakeProfit ()== 0 && SetOnlyZeroValues && TP!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderStopLoss (), OrderOpenPrice ()+ Point *TP, 0 ,BuyOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderStopLoss ()== 0 && SetOnlyZeroValues && SL!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()- Point *SL, OrderTakeProfit (), 0 ,BuyOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
           }
         else
           {
             if ((( OrderTakeProfit ()== 0 && TP!= 0 ) || ( OrderStopLoss ()== 0 && SL!= 0 )) && !SetOnlyZeroValues)
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+ Point *SL, OrderOpenPrice ()- Point *TP, 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderTakeProfit ()== 0 && SetOnlyZeroValues && TP!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderStopLoss (), OrderOpenPrice ()- Point *TP, 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
             if ( OrderStopLoss ()== 0 && SetOnlyZeroValues && SL!= 0 )
              {
                 if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+ Point *SL, OrderTakeProfit (), 0 ,SellOrderColor))
                     Print ( "OrderModify error " , GetLastError ());
               
              }
           }
        }
     }
   if ( MathAbs (TS)< MarketInfo ( Symbol (), MODE_STOPLEVEL ) && TS!= 0 )
     {
       Comment ( "Traling stop value too small, must be >= " + DoubleToStr ( MarketInfo ( Symbol (), MODE_STOPLEVEL )/kd, 0 ));
      
     }
//Trailing
   if (TS> 0 )
     {
       for (cnt= 0 ;cnt<total;cnt++)
        {
         if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
         continue ;
         if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( Bid - OrderOpenPrice ()> Point *TS && OrderStopLoss ()< Bid - Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), Bid - Point *TS, OrderTakeProfit (), 0 ,BuyOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
             else
              {
               if ( OrderOpenPrice ()- Ask > Point *TS && OrderStopLoss ()> Ask + Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), Ask + Point *TS, OrderTakeProfit (), 0 ,SellOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
           }
        }
     }
//ZeroTrailing     
   if (TS< 0 )
     {
       for (cnt= 0 ;cnt<total;cnt++)
        {
         if (! OrderSelect (cnt, SELECT_BY_POS , MODE_TRADES ))
         continue ;
         if ( OrderType ()<= OP_SELL && OrderSymbol ()== Symbol ())
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( Bid - OrderOpenPrice ()>- Point *TS && OrderStopLoss ()!= OrderOpenPrice () && OrderStopLoss ()< Bid + Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0 ,BuyOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
             else
              {
               if ( OrderOpenPrice ()- Ask >- Point *TS && OrderStopLoss ()!= OrderOpenPrice () && OrderStopLoss ()> Ask - Point *TS)
                 {
                   if (! OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice (), OrderTakeProfit (), 0 ,SellOrderColor))
                       Print ( "OrderModify error " , GetLastError ());
                  
                 }
              }
           }
        }
     }
   return ;
  }
//+------------------------------------------------------------------+

 
Aleksandr0:
Désolé pour le code, je ne l'ai pas eu tout de suite.

Je n'ai pas vu où vous essayez de fermer les commandes ?

 
void ClosePos()
  {
   double up=iFractals(NULL,0,MODE_UPPER,Shift);
   double dn=iFractals(NULL,0,MODE_LOWER,Shift);
   for(int i=OrdersTotal()-1;i>=0;i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY)
              {
               if(up>0&&dn==0&&Profit>0)
                 {
                  CloseAll();
                 }
              }
            if(OrderType()==OP_SELL)
              {
               if(dn>0&&up==0)
                 {
                  CloseAll();
                 }
              }
           }
        }
     }
   return;
  }
 
ou c'est faux ?
 
si aucun profit supérieur à 0 n'est ajouté, les transactions sont fermées correctement selon la conditionup>0&dn==0mais lorsque le profit est ajouté, tout cesse de fonctionner.
 
Aleksandr0:
ou c'est faux ?

Tous les vélos ont été inventés avant vous - connectez les fonctions intelligemment et c'est tout. Il serait également judicieux de lire un manuel sur les fermetures de commandes.

IMHO.

Торговые функции - Создание обычной программы - Учебник по MQL4
Торговые функции - Создание обычной программы - Учебник по MQL4
  • book.mql4.com
Как правило, обычный эксперт содержит несколько торговых функций. Их можно разделить на две категории - управляющие и исполнительные. В большинстве случаев в эксперте используется всего одна управляющая функция и несколько исполнительных. Торговая стратегия в обычном эксперте реализуется на основе двух функций - функции определения торговых...
 
@Roman Shiredchenko Désolé, j'ai écrit du mieux que j'ai pu en utilisant des livres et internet, je ne comprends pas plus, s'il vous plaît aidez et conseillez moi où j'ai fait une erreur.
 
STARIJ:

Avez-vous essayé mon programme ? Je ne comprends pas bien les 300... Si vous mettez 300 au lieu de 60, est-ce que c'est vrai ? Si vous me dites comment en tirer profit, je regarderai plus attentivement !

Oui, votre programme écrit dans les fichiers toutes les 60 secondes. Mais les heures d'ouverture des positions sont différentes et doivent être comptées à partir des heures d'ouverture de chaque position séparément, c'est-à-dire que l'heure des entrées sera différente, mais il s'avère que les données sont écrites presque simultanément sur toutes les positions. Pendant 300 secondes, on peut voir la différence plus clairement. Profit ?) Peut-être, il est important de savoir à quel moment de l'ouverture de la position le nombre "P" est supérieur à "L", c'est pour BOO.

 

Pouvez-vous me dire comment lire la dernière ligne d'un fichier ?

Изменение Уровней   BlueLine   RedLine
2018.02.26 12:42    1.24140    1.22391
2018.02.26 12:42    1.24919    1.22029
2018.02.26 12:43    1.25471    1.22029
2018.02.26 12:43    1.25395    1.21649
2018.02.26 12:48    1.24539    1.21649
2018.02.26 12:49    1.24368    1.22581

AvecFileReadDouble?

J'ai seulement besoin des valeursBlueLine etRedLine de ladernière ligne. ? ???

Je l'écrivais comme ça :

FileWrite(handle,TimeToStr(TimeCurrent()), "  ",B_level, "  ",R_level);
 
Rewerpool:

Pouvez-vous me dire comment lire la dernière ligne d'un fichier ?

AvecFileReadDouble ?

J'ai seulement besoin des valeursBlueLine etRedLine de ladernière ligne. ? ???

Je l'écrivais comme ça :

Lors de l'ouverture du fichier pour l'écriture, vous avez spécifié TXT ou CSV. Il s'agit d'un fichier texte. Lisez-le comme une chaîne, sélectionnez StringSubstr et convertissez-le en ce dont vous avez besoin.