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

 

Otra pregunta entonces :-)

Antes de mover el marcador de precio, se calcula la posición horizontal a través del ancho de pantalla actual

 x=width -70;

Cuando abro la barra lateral, el marcador se desplaza a la derecha más allá del límite de la pantalla. Si pulso el botón de actualizar en el registro puedo ver que el indicador funciona, pero el marcador no vuelve, sólo aparece en el segundo intento. Resulta que OnCalculate no se llama cada vez? ¿Cómo hacer que la función funcione permanentemente?



 
psyman:

Otra pregunta entonces :-)

Antes de mover el marcador de precio, se calcula la posición horizontal a través del ancho de pantalla actual

Cuando abro la barra lateral, el marcador se desplaza a la derecha más allá del límite de la pantalla. Si pulso el botón de actualizar en el registro puedo ver que el indicador funciona, pero el marcador no vuelve, sólo aparece en el segundo intento. Resulta que OnCalculate no se llama cada vez? ¿Cómo hacer que esta función funcione siempre?

hacer el sondeo y redibujar enOnChartEvent - CHARTEVENT_CHART_CHANGE

 

Saludos. ¿Puede decirme algo?

Si el indicador dibuja flechas en el gráfico y las flechas no son objetos, ¿es posible obtener los parámetros de dicho dibujo desde el propio gráfico o de alguna otra forma? No puedo obtener los datos de los buffers e incluso ejecutar el indicador para probarlo normalmente

 
Andrey Sokolov:

Saludos. ¿Puede decirme algo?

Si el indicador dibuja flechas en el gráfico y las flechas no son objetos, ¿es posible obtener los parámetros de dicho dibujo desde el propio gráfico o de alguna otra forma? No puedo obtener los datos de los buffers e incluso ejecutar el indicador para probarlo normalmente

¿Tiene el código del indicador?

 
Alexey Viktorov:

¿Existe un código para el indicador?

no

Los intentos de obtener datos de él, y el propio indicador, se han discutido aquí

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, пожалуйста пишите в этой теме. Особенно когда вопросы касаются торговых функций...
 

Estoy estudiando los ejemplos del tutorial y uno de ellos falla al compilar en la línea

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

'MQL5_PROGRAM_NAME' - no se puede convertir enum mouse_2.mq5 29 52


 
Ilya Prozumentov :

Consultar el permiso de trabajo para un asesor. ¿Y dónde está la salida en la impresión? Este fragmento de código parece devolver algo, ya que no hay errores, entonces el problema está fuera de este fragmento de código. En esta pieza, excepto que la división por 0 puede ocurrir

¿Código completo? Ahora sí .

 //+------------------------------------------------------------------+
//|                                                 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 );
}
//+------------------------------------------------------------------+

La línea 378 es la misma impresión, cuando está habilitada, el EA ya no funciona.

Tengo la sospecha de que hay un error en el diseño del código en la línea 221 y 223. Nadie usa la enumeración de historial, hay pocos ejemplos, por lo que es posible un error. Hay un ejemplo en la página https://www.mql5.com/en/code/7452, pero es demasiado complicado para mí allí.
División por cero en la función Znomer(), línea 206, excluí.


Espero instrucciones y recomendaciones. Gracias.

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

no

Los intentos de obtener datos de él, y el propio indicador, se han discutido aquí

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

Lo siento, no ejecuto el .dll en mi ordenador por una cuestión de principios, sigue sin mí.
 
Alexey Viktorov:
Lo siento, no ejecuto el .dll en mi ordenador por una cuestión de principios, sigue sin mí.

Sólo los indicadores aquí. Al utilizar en los parámetros desactivé el uso de la segunda.

Archivos adjuntos:
BiforexV1.zip  161 kb
 
Aliaksei Karalkou:

¿Todo el código? Sí, ahora.

La línea 378 es la misma impresión que, una vez habilitada, hace que el EA no funcione más.

Sospecho que hay un error en el formato del código en las líneas 221 y 223 . Nadie utiliza la repetición de la historia, no hay tantos ejemplos, por lo que podría ser un error. Hay un ejemplo en https://www.mql5.com/ru/code/7452 , pero es demasiado complicado para mí.
He excluido ladivisión por cero en la función Znomer(), línea 206.


Estoy esperando instrucciones y recomendaciones. Gracias.

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));

El exceso((2*psd*usd)*((2*psd*usd)-C))/(C-1)) en la fórmula.

Al grado: ^0,5 no es *0,5

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

Si no hay una sola operación en el símbolo buscado y majik, o no hay una sola ganancia o pérdida, o sólo hay un par (C=1), obtendremos la división por 0.

Antes de la fórmula propiamente dicha, debe comprobar que psd y usd son > 0, y que C !=1

Los pares rentables se calculan con beneficio > 1, pérdida < 1, con beneficio=1 no se analizan, es decir, el 1 también tiene que incluirse en algún lugar de este o aquel grupo.

En su función, sería mejor seleccionar primero los números de transacción que coincidan con el símbolo y el número mágico y luego comprobar si su número ha cambiado, si es así - recalcular zn, si no - devolver zn (zn en este caso no se pone a cero y comprobar != 0 no será necesario al imprimir)

El búho deja de funcionar, porque depende de las variables ww y nn, y cuando su función funciona, cambian y rompen el algoritmo del búho.

No se habría compilado nada si hubiera habido un error de diseño del código.
Razón de la queja: