Quaisquer perguntas de recém-chegados sobre MQL4 e MQL5, ajuda e discussão sobre algoritmos e códigos - página 480

 
Ajuda com um conselheiro não julgue estritamente estou escrevendo o primeiro

uma vez. Não quer fechar posições , o que há de errado???

 //+------------------------------------------------------------------+
//|                                                     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:
Desculpe pelo código, eu não o recebi de imediato.

Não viu onde você está tentando fechar os 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;
  }
 
ou isso é errado?
 
se nenhum lucro superior a 0 for adicionado, as negociações são fechadas corretamente de acordo com a condiçãoup>0&dn==0, mas quando o lucro é adicionado, tudo deixa de funcionar
 
Aleksandr0:
ou é errado?

Todas as bicicletas foram inventadas antes de você - conecte as funções de forma inteligente e pronto. Seria também uma boa idéia ler também um livro sobre o fechamento de pedidos.

IMHO.

Торговые функции - Создание обычной программы - Учебник по MQL4
Торговые функции - Создание обычной программы - Учебник по MQL4
  • book.mql4.com
Как правило, обычный эксперт содержит несколько торговых функций. Их можно разделить на две категории - управляющие и исполнительные. В большинстве случаев в эксперте используется всего одна управляющая функция и несколько исполнительных. Торговая стратегия в обычном эксперте реализуется на основе двух функций - функции определения торговых...
 
@Roman Shiredchenko Desculpe, eu escrevi o melhor que pude usando livros e a internet, não entendo mais, por favor me ajude e me aconselhe onde cometi um erro.
 
STARIJ:

Você já tentou meu programa? Eu não entendo bem os 300... Se você colocar 300 em vez de 60, é verdade? Se você me disser como lucrar com isso, eu vou olhar com mais cuidado!

Sim, seu programa escreve para os arquivos a cada 60 segundos. Mas os horários de abertura das posições são diferentes e devem ser contados a partir dos horários de abertura de cada posição separadamente, ou seja, o horário das entradas será diferente, mas acontece que os dados são escritos quase simultaneamente em todas as posições. Durante 300 segundos, a diferença pode ser vista com mais clareza. Lucro?) Talvez seja importante saber em que momento da abertura da posição o número "P" é maior que "L", é para BOO.

 

Você pode me dizer como ler a última linha de um arquivo?

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

ComFileReadDouble?

Eu só preciso dos valoresBlueLine eRedLine daúltima linha. ????

Eu estava escrevendo desta maneira:

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

Você pode me dizer como ler a última linha de um arquivo?

ComFileReadDouble?

Eu só preciso dos valoresBlueLine eRedLine daúltima linha. ????

Eu estava escrevendo desta maneira:

Ao abrir o arquivo para escrita, você especificou TXT ou CSV. Este é um arquivo de texto. Leia-o como um fio, selecione StringSubstr e converta-o para o que você precisa

Razão: