Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 480

 
Ayuda con un asesor no juzgues estrictamente te escribo el primero

una vez. No quiere cerrar posiciones , que pasa???

 //+------------------------------------------------------------------+
//|                                                     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:
Perdón por el código, no lo entendí de inmediato.

¿No ha visto dónde está tratando de cerrar los pedidos?

 
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;
  }
 
¿o está mal?
 
si no se añaden beneficios superiores a 0, las operaciones se cierran correctamente según la condiciónup>0&dn==0pero cuando se añaden beneficios, todo deja de funcionar
 
Aleksandr0:
¿o está mal?

Todas las bicicletas se han inventado antes que tú: conecta las funciones de forma inteligente y ya está. También sería una buena idea leer un libro de texto sobre el cierre de pedidos.

EN MI OPINIÓN.

Торговые функции - Создание обычной программы - Учебник по MQL4
Торговые функции - Создание обычной программы - Учебник по MQL4
  • book.mql4.com
Как правило, обычный эксперт содержит несколько торговых функций. Их можно разделить на две категории - управляющие и исполнительные. В большинстве случаев в эксперте используется всего одна управляющая функция и несколько исполнительных. Торговая стратегия в обычном эксперте реализуется на основе двух функций - функции определения торговых...
 
@Roman Shiredchenko Lo siento, escribí lo mejor que pude usando libros e internet, no entiendo más, por favor ayuda y aconséjame donde me equivoqué.
 
STARIJ:

¿Has probado mi programa? No entiendo muy bien los 300... Si pones 300 en lugar de 60, ¿es cierto? Si me dices cómo sacarle provecho, lo miraré con más atención.

Sí, su programa escribe en los archivos cada 60 segundos. Pero las horas de apertura de las posiciones son diferentes y deberían contarse a partir de las horas de apertura de cada posición por separado, es decir, la hora de las entradas será diferente, pero resulta que los datos se escriben casi simultáneamente en todas las posiciones. Durante 300 segundos, la diferencia se puede ver más claramente. Beneficio...) Tal vez, es importante saber en qué momento de la apertura de la posición el número "P" es mayor que "L", es para BOO.

 

¿Puede decirme cómo leer la última línea de un archivo?

Изменение Уровней   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

ConFileReadDouble?

Sólo necesito los valoresBlueLine yRedLine dela última línea. ????

Lo escribía así:

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

¿Puede decirme cómo leer la última línea de un archivo?

¿ConFileReadDouble?

Sólo necesito los valoresBlueLine yRedLine dela última línea. ????

Lo estaba escribiendo así:

Al abrir el archivo para la escritura se especificó TXT o CSV. Se trata de un archivo de texto. Léalo como una cadena, seleccione StringSubstr y conviértalo en lo que necesite

Razón de la queja: