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

 

Another question then :-)

Before moving the price marker, the horizontal position is calculated through the current screen width

 x=width -70;

When I open the sidebar, the marker moves to the right beyond the screen boundary. If I press refresh button in log I can see indicator working, but marker doesn't come back, it appears only on second try. It turns out that OnCalculate is not called every time? How to make the function work permanently?



 
psyman:

Another question then :-)

Before moving the price marker, the horizontal position is calculated through the current screen width

When I open the sidebar, the marker moves to the right beyond the screen boundary. If I press refresh button in log I can see indicator working, but marker doesn't come back, it appears only on second try. It turns out that OnCalculate is not called every time? How to make this function work always?

do polling and redrawing inOnChartEvent - CHARTEVENT_CHART_CHANGE

 

Greetings. Can you tell me something?

If the indicator draws arrows on the chart and the arrows are not objects, is it possible to get the parameters of such drawing from the chart itself or in any other way? I cannot get data from buffers and even run the indicator for testing normally

 
Andrey Sokolov:

Greetings. Can you tell me something?

If the indicator draws arrows on the chart and the arrows are not objects, is it possible to get the parameters of such drawing from the chart itself or in any other way? I cannot get data from buffers and even run the indicator for testing normally

Do you have the code of the indicator?

 
Alexey Viktorov:

Is there a code for the indicator?

no

Attempts to get data from it, and the indicator itself, have been discussed here

https://www.mql5.com/ru/forum/160587/page165#comment_10221621

Вопросы от начинающих MQL4 MT4 MetaTrader 4
Вопросы от начинающих MQL4 MT4 MetaTrader 4
  • 2019.01.04
  • www.mql5.com
Если у Вас вопросы по MQL4, MT4, MetaTrader 4, пожалуйста пишите в этой теме. Особенно когда вопросы касаются торговых функций...
 

I'm studying the examples in the tutorial and one of them fails to compile on the line

   Print("Запущен эксперт с именем ",MQLInfoString(MQL5_PROGRAM_NAME)); 

'MQL5_PROGRAM_NAME' - cannot convert enum mouse_2.mq5 29 52


 
Ilya Prozumentov :

Check the work permit for an adviser. And where is the output in the print? This piece of code seems to return something, since there are no errors, then the problem is outside of this piece of code. In this piece, except that division by 0 can occur

Whole code? Yes now .

 //+------------------------------------------------------------------+
//|                                                 Stop_Ma_v5.1.mq4 |
//|                                            Copyright 2018, axe44 |
//|                                 http://axe44.opentraders.ru/bio/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018,@ axe44"
#property link        "gerchikco.com/registration/?ref=sfaCLYmR"
#property version    "5.10"
#property strict

//--- Inputs
extern double Lots       = 0.1 ;     // Lots лот
extern bool Z_schet      = 1 ;       // Z_schet з-тенденция
extern int Expir         = 20 ;       // Expir истечение в часах
extern double klot       = 1.5 ;     // klot - множитель тенденции
extern int StopLoss      = 200 ;     // StopLoss лось
extern int TakeProfit    = 300 ;     // TakeProfit язь
extern int BULevel       = 0 ;       // BULevel уровень БУ
extern int BUPoint       = 3 ;       // BUPoint пункты БУ
extern int Spred         = 4 ;       // Spred спред 
extern int TrailingStop  = 0 ;       // TrailingStop трал
input ENUM_TIMEFRAMES TF1 = PERIOD_M15 ; //TF1 Время АТР
extern int Stop            = 14 ;           // Stop Периуд Stop
//extern int Atr_Procent   = 20;       //Atr_Procent  Максимальный процент АТР для работы
input ENUM_TIMEFRAMES TF2  = PERIOD_M15 ; //TF2 Время Ма открытия\закрытия 
//extern int Pr            = 50;       // Pr Процент разницы движения.
extern int MA            = 14 ;           //MA Периуд MA
extern int MaM           = 3 ;         //MaM способ расчёта Ма   
extern int StartHour     = 0 ;         //StartHour час начала торговли
extern int StartMin      = 30 ;       //StartMin минута начала торговли
extern int EndHour       = 23 ;       //EndHour час окончания торговли
extern int EndMin        = 30 ;       //EndMin минута окончания торговли
extern int Slip          = 30 ;       //Slip реквот
extern int Magic         = 124 ;       //Magic магик
extern int TesterMinPercentProfitTrades= 50 ;
extern int AutoLot       = 1 ;         // автолот

double atr,ma,rm,pm,minatr,lot,hma,lma,min,max,zn,C,pribul;
double NormalP[ 302 ];
int i,count,prom,index,psd,usd;
datetime t= 1 ,day,hour;
bool ww,nn,bb,ss;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//---
   if ( Digits == 3 || Digits == 5 )
     {
      TakeProfit*= 10 ;
      StopLoss*= 10 ;
      TrailingStop*= 10 ;
      BUPoint*= 10 ;
      BULevel*= 10 ;
      Slip*= 10 ;
      Spred*= 10 ;
      
     }
//---
   return ( INIT_SUCCEEDED );
  }
  

//+------------------------------------------------------------------+
//| расчёт лота                                                      |
//+------------------------------------------------------------------+
double MoneyManagement()
  {
   double DynamicLot= 0 ;
   double Free_Equity= AccountEquity ();
   if (Free_Equity<= 0 ) return ( 0 );
   double TickValue= MarketInfo ( Symbol (), MODE_TICKVALUE );
   double LotStep= MarketInfo ( Symbol (), MODE_LOTSTEP );
   double MinLot= MarketInfo ( Symbol (), MODE_MINLOT );
   double MxLot= MarketInfo ( Symbol (), MODE_MAXLOT );
   if (TickValue*LotStep!= 0 ) DynamicLot= MathFloor ((Free_Equity* MathMin (AutoLot/ 10 , 100 )/ 1000 )/StopLoss*TickValue/LotStep)*LotStep; 
   if (DynamicLot<MinLot)DynamicLot=MinLot;
   if (DynamicLot>MxLot)DynamicLot=MxLot;
   return (DynamicLot);
  }
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
   Comment ( "" );
  }

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 30.04.2009                                                     |
//|  Описание : Возвращает флаг разрешения торговли по времени.                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    hb - часы времени начала торговли                                       |
//|    mb - минуты времени начала торговли                                     |
//|    he - часы времени окончания торговли                                    |
//|    me - минуты времени окончания торговли                                  |
//+----------------------------------------------------------------------------+
bool isTradeTimeInt( int hb= 0 , int mb= 0 , int he= 0 , int me= 0 )
  {
   datetime db, de;           // Время начала и окончания работы
   int       hc;               // Часы текущего времени торгового сервера

   db= StrToTime ( TimeToStr ( TimeCurrent (), TIME_DATE )+ " " +( string )hb+ ":" +( string )mb);
   de= StrToTime ( TimeToStr ( TimeCurrent (), TIME_DATE )+ " " +( string )he+ ":" +( string )me);
   hc= TimeHour ( TimeCurrent ());

   if (db>=de)
     {
       if (hc>=he) de+= 24 * 60 * 60 ; else db-= 24 * 60 * 60 ;
     }

   if ( TimeCurrent ()>=db && TimeCurrent ()<=de) return ( True );
   else return ( False );
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void PutOrder( int type, double price)
  {
   int r= 0 ;
   color clr=Green;
   double sl= 0 ,tp= 0 ;

   if (type== 1 || type== 3 || type== 5 )
     {
      clr=Red;
       if (StopLoss> 0 ) sl= NormalizeDouble (price+StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (price-TakeProfit* Point , Digits );
     }

   if (type== 0 || type== 2 || type== 4 )
     {
      clr=Blue;
       if (StopLoss> 0 ) sl= NormalizeDouble (price-StopLoss* Point , Digits );
       if (TakeProfit> 0 ) tp= NormalizeDouble (price+TakeProfit* Point , Digits );
     }
   if (AutoLot> 0 ){lot=MoneyManagement();}
   if (AutoLot<= 0 ){lot=Lots;}
   r= OrderSend ( NULL ,type,lot, NormalizeDouble (price, Digits ),Slip,sl,tp, "" ,Magic, TimeCurrent ()+Expir* 60 * 60 ,clr);
   return ;
  }
//+------------------------------------------------------------------+
//| история                                                          |
//+------------------------------------------------------------------+
double history()
{

   if ( OrderSelect ( OrdersHistoryTotal ()- 1 , SELECT_BY_POS , MODE_HISTORY ))
     {   
      pribul= OrderProfit (); 
     }
     

return (pribul);
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int CountOrders( int type)
  {
    count= 0 ;
   for ( i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()==type) count++;
           }
        }
     }
   return (count);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int CountTrades()
  {
    count= 0 ;
   for ( i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()< 2 ) count++;
           }
        }
     }
   return (count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
  
double Znomer()
  {
    zn= 0 ;         // z-число
    psd= 0 ;         // кол. положительных сделок
    usd= 0 ;         // количество отрицательных сделок 
    ww= 0 ;         // боол переменная 
    nn= 0 ;         // боол переменная
    C= 0 ;           // C = количество чередований между отрицательными и положительными сделками
    index= OrdersHistoryTotal (); 
     if ( OrdersHistoryTotal ()> 302 ) index= 301 ; // берём не более 301 сделки
     if (index< 30 ) return ( 0 );                 // берём не менее 30
    count= OrdersHistoryTotal ();             // считаем от скольки 
    prom=count-index;                       // выделяем только последние сделки
     if (prom< 0 ) prom= 0 ;                     // исключаем ошибки
    
   for ( i=count;i>prom;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_HISTORY )== true )
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           { // далее магия
           pribul= OrderProfit (); 
           if (ww== 0 &&pribul> 1 ){C++;ww= 1 ;nn= 0 ;} // подсчитываем смену тенденции
           if (nn== 0 &&pribul< 1 ){C++;ww= 0 ;nn= 1 ;} // подсчитываем смену тенденции 
           if (pribul> 1 ){psd++;} //прибыльные сделки
           if (pribul< 1 ){usd++;} // убыточные сделки
           
           }
        }
     }
     /*/*
Величина Z = (A * (C — 0.5) — B)/   ((B*(B — C))/(C -1))^(1/2), где:
A = количество анализируемых сделок;
B = 2*количество прибыльных сделок * количество убыточных сделок;
C = количество чередований в выборке (чередованием считается каждая пара сделок, 
когда прибыльная сделка сменяет убыточную либо наоборот).
           */
            index=psd+usd;
             if (index< 30 ) return ( 0 );
            zn=(index*(C- 0.5 )-( 2 *psd*usd))/
             (((( 2 *psd*usd)*(( 2 *psd*usd)-C))/
            (C- 1 ))*(((( 2 *psd*usd)*(( 2 *psd*usd)-C))/
            (C- 1 ))* 0.5 ));
      
     
     
   return (zn);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Trailing()
  {
   bool mod;
   for ( i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( Bid - OrderOpenPrice ()>TrailingStop* Point )
                 {
                   if (( OrderStopLoss ()<( Bid -TrailingStop* Point )) || ( OrderStopLoss ()== 0 ))
                    {
                     mod= OrderModify ( OrderTicket (), OrderOpenPrice (), Bid -TrailingStop* Point , OrderTakeProfit (), 0 ,Yellow);
                     return ;
                    }
                 }
              }

             if ( OrderType ()== OP_SELL )
              {
               if (( OrderOpenPrice ()- Ask )>TrailingStop* Point )
                 {
                   if (( OrderStopLoss ()>( Ask +TrailingStop* Point )) || ( OrderStopLoss ()== 0 ))
                    {
                     mod= OrderModify ( OrderTicket (), OrderOpenPrice (), Ask +TrailingStop* Point , OrderTakeProfit (), 0 ,Yellow);
                     return ;
                    }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void BU()
  {
   bool m;
   for ( i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== OP_BUY )
              {
               if ( OrderOpenPrice ()<=( Bid -(BULevel+BUPoint)* Point ) && OrderOpenPrice ()> OrderStopLoss ())
                 {
                  m= OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()+BUPoint* Point , OrderTakeProfit (), 0 ,Yellow);
                  
                 }
              }

             if ( OrderType ()== OP_SELL )
              {
               if ( OrderOpenPrice ()>=( Ask +(BULevel+BUPoint)* Point ) && ( OrderOpenPrice ()< OrderStopLoss () || OrderStopLoss ()== 0 ))
                 {
                  m= OrderModify ( OrderTicket (), OrderOpenPrice (), OrderOpenPrice ()-BUPoint* Point , OrderTakeProfit (), 0 ,Yellow);
                  
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAll( int ot=- 1 )
  {
   bool cl;
   for ( i= OrdersTotal ()- 1 ;i>= 0 ;i--)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES ))
        {
         if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==Magic)
           {
             if ( OrderType ()== 0 && (ot== 0 || ot==- 1 ))
              {
               RefreshRates ();
               cl= OrderClose ( OrderTicket (), OrderLots (), NormalizeDouble ( Bid , Digits ),Slip,White);
              }
             if ( OrderType ()== 1 && (ot== 1 || ot==- 1 ))
              {
               RefreshRates ();
               cl= OrderClose ( OrderTicket (), OrderLots (), NormalizeDouble ( Ask , Digits ),Slip,White);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {  
   if (t!= Time [ 0 ]&&( Ask - Bid )<Spred* Point )
 {
   ww= 1 ;
   nn= 1 ;
   t= Time [ 0 ]; 
   if (TrailingStop> 0 ) Trailing();
   if (BULevel> 0 ) BU();   
  
  rm = iMA ( NULL ,TF2,MA, 0 ,MaM, 0 , 1 )- iMA ( NULL ,TF2,MA, 0 ,MaM, 1 , 1 ); 
  pm = iMA ( NULL ,TF2,MA, 0 ,MaM, 0 , 2 )- iMA ( NULL ,TF2,MA, 0 ,MaM, 1 , 2 );   
  
   // Stop
  
   //---- maximums counting 

        hma = High [ iHighest ( NULL , 0 , MODE_HIGH ,Stop, 1 )]; 
        lma = Low [ iLowest ( NULL , 0 , MODE_LOW ,Stop, 1 )];
        
//----
//Print("hma ",hma);
//Print("lma ",lma);
//if ( Znomer()!=0) {zn=Znomer();Print("== Z-счёт равен = ",zn);}     

  }
  
   if (ww== 1 && pm< 0 && rm> 0 && isTradeTimeInt(StartHour,StartMin,EndHour,EndMin)) { if ( Ask <hma)PutOrder( 4 ,hma);
                                                                                   if ( Bid >lma)PutOrder( 5 ,lma);
                                                                                  ww= 0 ;} // Если цена раньше падала а теперь растёт
   if (nn== 1 && pm> 0 && rm< 0 && isTradeTimeInt(StartHour,StartMin,EndHour,EndMin)) { if ( Ask <hma)PutOrder( 4 ,hma);
                                                                                   if ( Bid >lma)PutOrder( 5 ,lma);
                                                                                  nn= 0 ;}
   
   
   
 }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Tester function                                                  |
//+------------------------------------------------------------------+
double OnTester ()
{
     double PercentProfitTrades = 0 ;
     if ( TesterStatistics ( STAT_PROFIT_TRADES ) > 0 )
        PercentProfitTrades = TesterStatistics ( STAT_PROFIT_TRADES ) / TesterStatistics ( STAT_TRADES ) * 100 ;
     if (PercentProfitTrades >= TesterMinPercentProfitTrades)
         return ( NormalizeDouble (( TesterStatistics ( STAT_PROFIT ) / TesterStatistics ( STAT_EQUITY_DD )), 2 ));
     else return ( 0 );
}
//+------------------------------------------------------------------+

Line 378 is the same print, when enabled, the EA no longer works.

I have a suspicion that there is an error in the design of the code in line 221 and 223 . No one uses history enumeration, there are few examples, so a mistake is possible. There is one example on the page https://www.mql5.com/en/code/7452 , but it's too complicated for me there.
Division by zero in the Znomer() function, line 206, I excluded.


I look forward to instructions and recommendations. Thank you.

Вычисление Z-счета
Вычисление Z-счета
  • www.mql5.com
Включаемый файл Z_include.mqh содержит функцию, которая вычисляет на массиве данных следующие параметры: Max - максимальное значение;Min - минимальное значение;матожидание - среднее значение;стандартное отклонение - среднеквадратичное отклонение (несмещенную оценку);скос;эксцесс;Z-счет на массиве данных. Описание понятия Z -счет смотрите в...
 
Andrey Sokolov:

no

Attempts to get data from it, and the indicator itself, have been discussed here

https://www.mql5.com/ru/forum/160587/page165#comment_10221621

Sorry, I don't run the .dll on my computer as a matter of principle, go ahead without me.
 
Alexey Viktorov:
Sorry, I don't run the .dll on my computer as a matter of principle, go ahead without me.

Only the indicators here. When using in the parameters I disabled the use of the second one.

Files:
BiforexV1.zip  161 kb
 
Aliaksei Karalkou:

The whole code? Yes, now .

Line 378 is the same print, which, once enabled, makes the EA not work anymore.

I suspect that there is an error in the code formatting on lines 221 and 223 . No one uses the replaying of history, there are not so many examples, so this might be an error. There is one example on https://www.mql5.com/ru/code/7452 , but it is too complicated for me.
I excludeddivision by zero in the Znomer() function, line 206.


I'm waiting for instructions and recommendations. Thank you.

zn=(index*(C-0.5)-(2*psd*usd))	/   ((((2*psd*usd)*((2*psd*usd)-C))/(C-1))*((((2*psd*usd)*((2*psd*usd)-C))/(C-1))*0.5));

The excess((2*psd*usd)*((2*psd*usd)-C))/(C-1)) in the formula.

To the degree: ^0.5 is not *0.5

zn=(index*(C-0.5)-2*psd*usd)  /  pow(((2*psd*usd*(2*psd*usd-C))/(C-1)),0.5);

If there is not a single trade on the looked through symbol and majik, or there is not a single profit or loss, or there is only one pair (C=1), we will get the division by 0.

Before the formula itself, you should check that psd and usd are > 0, and C !=1

Profitable pairs are calculated with profit > 1, loss < 1, with profit=1 are not analyzed, i.e. 1 also has to be included somewhere in this or that group.

In your function, it would be better to first select transaction numbers matching the symbol and magic number and then check if their number has changed, if so - recalculate zn, if not - return zn (zn in this case do not zeroize and check != 0 will not be needed when printing)

The owl stops working, because it relies on variables ww and nn, and when your function works, they change and mess up the owl algorithm.

Nothing would have compiled if there had been a code design error.