Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 480

 
Help with an adviser do not judge strictly I am writing the first

once. Doesn't want to close positions , what's wrong???

 //+------------------------------------------------------------------+
//|                                                     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:
Sorry about the code, I didn't get it right away.

Didn't see where you are trying to close orders?

 
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;
  }
 
or is that wrong?
 
if no profit exceeding 0 is added, trades are closed correctly according to the conditionup>0&dn==0but when profit is added, everything stops working
 
Aleksandr0:
or is it wrong?

All the bikes have been invented before you - connect the functions intelligently and that's it. It would also be a good idea to read a textbook on order closures as well.

IMHO.

Торговые функции - Создание обычной программы - Учебник по MQL4
Торговые функции - Создание обычной программы - Учебник по MQL4
  • book.mql4.com
Как правило, обычный эксперт содержит несколько торговых функций. Их можно разделить на две категории - управляющие и исполнительные. В большинстве случаев в эксперте используется всего одна управляющая функция и несколько исполнительных. Торговая стратегия в обычном эксперте реализуется на основе двух функций - функции определения торговых...
 
@Roman Shiredchenko Sorry, I wrote as best I could using books and the internet, I do not understand more, please help and advise me where I made a mistake.
 
STARIJ:

Have you tried my programme? I do not quite understand the 300... If you put 300 instead of 60, is it true? If you tell me how to get profit from it, I'll look more carefully!

Yes, your programme writes to the files every 60 seconds. But the opening times of positions are different and should be counted from the opening times of each position separately, i.e. the time of entries will be different, but it turns out that the data is written almost simultaneously on all positions. For 300 seconds, the difference can be seen more clearly. Profit?) Perhaps, it is important to know at what time from the position opening the number "P" is greater than "L", it is for BOO.

 

Can you tell me how to read the last line of a file ?

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

WithFileReadDouble?

I only need theBlueLine andRedLine values ofthe last line. ????

I was writing it this way:

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

Can you tell me how to read the last line of a file ?

WithFileReadDouble?

I only need theBlueLine andRedLine values ofthe last line. ????

I was writing it this way:

When opening the file for writing you specified TXT or CSV. This is a text file. Read it as a string, select StringSubstr and convert it to what you need

Reason: