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

 
Alexey Viktorov:

De nada, pero parece que no he hecho nada...

Aquí
 
MakarFX:
Aquí

Gracias, y también aAlexey Viktorov.

Alexey Viktorov
Alexey Viktorov
  • 2021.06.30
  • www.mql5.com
Профиль трейдера
 
законопослушный гражданин :


Intentalo

puede editar la función "Señal para abrir una orden"

 //+------------------------------------------------------------------+
//|                                                 Citizen.v2.1.mq4 |
//|                                           Copyright 2020, DrMak. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, DrMak."
#property link        " https://www.mql5.com "
#property version    "1.00"
#property strict
//--- input parameters
input ENUM_TIMEFRAMES    timeframe_RSI  = PERIOD_H1 ;
input int                period_RSI     = 14 ;
input int                level_buy      = 30 ;
input int                level_sell     = 70 ;
input double             Lot            = 0.1 ;   // Размер стартового лота
input double             K_Martin       = 2.0 ;   // Размер увеличения лота(Мартин) 
input int                Stoploss       = 100 ;   // Размер StopLoss в пунктах
input int                Takeprofit     = 500 ;   // Размер TakeProfit в пунктах
input double             CountLoss      = 200 ;   // Размер максимального убытка
input double             CountProfit    = 300 ;   // Размер минимального профита
input int                Magic          = 777 ;   // Магик
input int                DigitsLot      = 2 ;     // Шаг лота
input int                slippage       = 3 ;     // Проскальзывание
//---
string AC;
datetime Start;
double AB,MINLOT,MAXLOT,RSI1,RSI0,SL,TP,sl,tp;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- create timer
   ObjectsDeleteAll ( 0 , "lab_" );
   EventSetMillisecondTimer ( 500 );
   Start  = TimeCurrent ();
   MINLOT = MarketInfo( Symbol (),MODE_MINLOT);
   MAXLOT = MarketInfo( Symbol (),MODE_MAXLOT);
   AC     = StringConcatenate ( " " , AccountCurrency());
   AB     = AccountInfoDouble ( ACCOUNT_BALANCE );
   int Y= 20 ;
   CreateButton( 0 , "lab_Button" , 0 , 79 ,Y, 77 , 25 , CORNER_RIGHT_UPPER , "Советник остановлен" , "START" , "Arial Black" , 10 , clrWhite , clrGreen ,
   false , false , false , false , false , 0 );Y += 25 ;
   DrawLABEL( "lab_Торговля"    , 1 , 5 ,Y, clrRed , "Торговля " );Y += 20 ;
   DrawLABEL( "lab_Start Time" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));Y += 15 ;
   DrawLABEL( "lab_Current Lot" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));Y += 15 ;
   DrawLABEL( "lab_Balance"     , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AccountBalance(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_Equity"      , 1 , 5 ,Y, clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));Y += 15 ;
   DrawLABEL( "lab_FreeMargin" , 1 , 5 ,Y, clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));Y += 30 ;
   DrawLABEL( "lab_Take"        , 1 , 5 ,Y, clrLime , "Profit: " );
//---
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//--- destroy timer
   EventKillTimer ();
   if (!IsTesting()) 
     {
       ObjectsDeleteAll ( 0 , "lab_" );
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
//---
   if (IsTesting()) 
     {
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
        }
       if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
        {
         ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
         ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
         Start = iTime ( _Symbol , PERIOD_D1 , 0 );
        }
     }
   if (GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*- 1 )
     {
       if (IsTesting()) 
        {
         CloseOrder(); ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_STATE , false );
        }
       else
        {
         CloseOrder();
        }
     }
   // Обновляем текст на лейблах
   DrawLABEL( "lab_Start Time" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Start Time: " ,TimeToStr(Start, TIME_DATE | TIME_SECONDS )));
   DrawLABEL( "lab_Current Lot" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Current Lot: " ,DoubleToStr(Lots(),DigitsLot)));
   DrawLABEL( "lab_Balance"     , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Balance: " ,DoubleToStr(AB, 2 ),AC));
   DrawLABEL( "lab_Equity"      , 1 , 5 , 0 , clrGreen , StringConcatenate ( "Equity: " ,DoubleToStr(AccountEquity(), 2 ),AC));
   DrawLABEL( "lab_FreeMargin" , 1 , 5 , 0 , clrGreen , StringConcatenate ( "FreeMargin: " ,DoubleToStr(AccountFreeMargin(), 2 ),AC));
   DrawLABEL( "lab_Take"        , 1 , 5 , 0 ,Color(GetProfitFromStart()> 0 ,Lime,Red), StringConcatenate ( "Profit: " ,DoubleToStr(GetProfitFromStart(), 2 ),AC));
   //---
   sl  = MathMax (Stoploss, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   SL  = NormalizeDouble (sl* Point (), Digits );
   tp  = MathMax (Takeprofit, MarketInfo( _Symbol , MODE_STOPLEVEL)) * Point ();
   TP  = NormalizeDouble (tp* Point (), Digits );
   //---
   if (CountOrders()== 0 && ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE ))
     {
       if (TradeSignal()>= 0 )
        {
         SendOrder(TradeSignal());
        }
     }
   //---
   if (!IsTradeAllowed()) 
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrRed , "Торговля запрещена" ); return ;} 
   else
     {DrawLABEL( "lab_Торговля" , 0 , 0 , 0 , clrLime , "Торговля разрешена" );}
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer ()
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Сигнал для открытия ордера                                       |
//+------------------------------------------------------------------+
int TradeSignal() 
  {
   int sig=- 1 ;
   // Здесь расчет сигнала
   RSI0= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 0 );
   RSI1= iRSI ( NULL ,timeframe_RSI,period_RSI, PRICE_CLOSE , 1 );
   // Здесь определение направления сигнала sig=0-BUY, sig=1-SELL
   if (RSI0>=level_buy && RSI1<=level_buy)   sig= 0 ;
   if (RSI0<=level_sell && RSI1>=level_sell) sig= 1 ;
   return (sig);
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent ( const int id,
                   const long &lparam,
                   const double &dparam,
                   const string &sparam)
  {
//---
   if (sparam== "lab_Button" ) TradeButton();
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| ButtonSTART                                                                                                        |
//+--------------------------------------------------------------------------------------------------------------------+
void TradeButton()
  {
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== true )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrRed );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник запущен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "STOP" );
     }
   if ( ObjectGetInteger ( 0 , "lab_Button" , OBJPROP_STATE )== false )
     {
       ObjectSetInteger ( 0 , "lab_Button" , OBJPROP_BGCOLOR , clrGreen );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TOOLTIP , "Советник остановлен" );
       ObjectSetString ( 0 , "lab_Button" , OBJPROP_TEXT , "START" );
      Start = TimeCurrent ();
     }
  }
//+------------------------------------------------------------------+
//| Расчет лота                                                      |
//+------------------------------------------------------------------+
double Lots()
  {
   double L= 0 ;
   if (GetInfoLastPos( 3 )>Start && GetInfoLastPos( 2 )< 0 )
     {L= NormalizeDouble (GetInfoLastPos( 1 )*K_Martin,DigitsLot);}
   else
     {L=Lot;}
   
   if (L>MAXLOT) L = MAXLOT;
   if (L<MINLOT) L = MINLOT;
   return (L);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  размер профита с учетом комиссии и свопа с начала цикла                   |
//+----------------------------------------------------------------------------+
double GetProfitFromStart()
  {
   double lp= 0 ,cp= 0 ;
   for ( int i= 0 ; i<OrdersHistoryTotal(); i++)
     {
       if ( OrderSelect (i, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (Start<OrderCloseTime()) {lp+=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   for ( int pos= OrdersTotal ()- 1 ;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL) {cp=OrderProfit()+OrderCommission()+OrderSwap();}
           }
        }
     }
   return (lp+cp);
  }
//+----------------------------------------------------------------------------+
//|  Функция возвращает по символу и магику                                    |
//|  1 - размер лота последней закрытой позиции                                |
//|  2 - размер профита с учетом комиссии и свопа последней закрытой позиции   |
//|  3 - время последней закрытой позиции                                      |
//+----------------------------------------------------------------------------+
double GetInfoLastPos( int a= 1 )
  {
   datetime t= 0 ;
   double result= 0 ,l= 0 ,p= 0 ,f= 0 ;
   int i=OrdersHistoryTotal();
   for ( int pos= 0 ; pos<i; pos++)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_HISTORY))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if (t<OrderCloseTime()) {t=OrderCloseTime(); l=OrderLots(); p=OrderProfit()+OrderCommission()+OrderSwap();}
              }
           }
        }
     }
   if (a== 1 ) {result=l;} else
   if (a== 2 ) {result=p;} else
   if (a== 3 ) {result=( double )t;}
   else      {result= 0 ;}
   return (result);
  }
//+------------------------------------------------------------------+
//| Подсчет открытых ордеров                                         |
//+------------------------------------------------------------------+
int CountOrders() 
  {
   int cnt= 0 ;
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol )
           {
             if (OrderMagicNumber()==Magic) cnt++;
           }
        }
     }
   return (cnt);
  }
//+------------------------------------------------------------------+
//| Открытие ордера                                                  |
//+------------------------------------------------------------------+
void SendOrder( int so= 0 ) 
  {
   if (so== 0 )
     {
       if ( OrderSend ( Symbol (),OP_BUY, Lots(),Ask,slippage,Ask-sl,Ask+tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Buy: " , _Symbol );} else { Print ( "Error Open Buy: " , _Symbol , " / " , GetLastError ());}
     }
   if (so== 1 )
     {
       if ( OrderSend ( Symbol (),OP_SELL, Lots(),Bid,slippage,Bid+sl,Bid-tp, NULL ,Magic, 0 , clrBlue ))
        { Print ( "Open Sell: " , _Symbol );} else { Print ( "Error Open Sell: " , _Symbol , " / " , GetLastError ());}
     }
  }
//+------------------------------------------------------------------+
//| Закрытие открытого ордера                                        |
//+------------------------------------------------------------------+
void CloseOrder() 
  {
   int i= OrdersTotal ()- 1 ;
   for ( int pos=i;pos>= 0 ;pos--)
     {
       if ( OrderSelect (pos, SELECT_BY_POS, MODE_TRADES))
        {
         if (OrderSymbol()== _Symbol && OrderMagicNumber()==Magic)
           {
             if (OrderType()==OP_BUY)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Bid,slippage, clrBlue )) TradeButton();
              }
             if (OrderType()==OP_SELL)
              {
               if (OrderClose(OrderTicket(),OrderLots(),Ask,slippage, clrRed )) TradeButton();
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Установка цвета                                                  |
//+------------------------------------------------------------------+
color Color( bool P, color a, color b)
  {
   if (P) return (a);
   else return (b);
  }
//+------------------------------------------------------------------+
//| Установка лейблов/текста                                         |
//+------------------------------------------------------------------+
void DrawLABEL( string name, int CORNER, int X, int Y, color clr, string Name)
  {
   if ( ObjectFind ( 0 ,name)!= 0 )
     {
       ObjectCreate ( 0 ,name, OBJ_LABEL , 0 , 0 , 0 );
      ObjectSet(name, OBJPROP_CORNER , CORNER);
      ObjectSet(name, OBJPROP_XDISTANCE , X);
      ObjectSet(name, OBJPROP_YDISTANCE , Y);
     }
   ObjectSetText(name,Name, 10 , "Arial" ,clr);
  }
//+--------------------------------------------------------------------------------------------------------------------+
//| Создает кнопку                                                                                                     |
//+--------------------------------------------------------------------------------------------------------------------+
bool CreateButton( const long               chart_ID= 0 ,               // ID графика
                   const string             name= "Button" ,             // имя кнопки
                   const int                sub_window= 0 ,             // номер подокна
                   const int                x= 0 ,                       // координата по оси X
                   const int                y= 0 ,                       // координата по оси Y
                   const int                width= 50 ,                 // ширина кнопки
                   const int                height= 18 ,                 // высота кнопки
                   const int                corner= 0 ,                 // угол графика для привязки
                   const string             tool= "TOOLTIP" ,           // TOOLTIP
                   const string             text= "Button" ,             // текст
                   const string             font= "Arial" ,             // шрифт
                   const int                font_size= 10 ,             // размер шрифта
                   const color              clr= clrBlack ,             // цвет текста
                   const color              back_clr= C'236,233,216' ,   // цвет фона
                   const bool               state= false ,               // нажата/отжата
                   const bool               back= false ,               // на заднем плане
                   const bool               selection= false ,           // выделить для перемещений
                   const bool               selected= false ,           // выделить для перемещений
                   const bool               hidden= true ,               // скрыт в списке объектов
                   const long               z_order= 0 )                 // приоритет на нажатие мышью
  {
//--- сбросим значение ошибки
   ResetLastError ();
//--- создадим кнопку
   if (! ObjectCreate (chart_ID,name, OBJ_BUTTON ,sub_window, 0 , 0 ))
     {
       Print ( __FUNCTION__ , ": не удалось создать кнопку! Код ошибки = " , GetLastError ()); return ( false );
     }
   ObjectSetInteger (chart_ID,name, OBJPROP_XDISTANCE ,x);
   ObjectSetInteger (chart_ID,name, OBJPROP_YDISTANCE ,y);
   ObjectSetInteger (chart_ID,name, OBJPROP_XSIZE ,width);
   ObjectSetInteger (chart_ID,name, OBJPROP_YSIZE ,height);
   ObjectSetInteger (chart_ID,name, OBJPROP_CORNER ,corner);
   ObjectSetString (chart_ID,name, OBJPROP_TOOLTIP ,tool);
   ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text);
   ObjectSetString (chart_ID,name, OBJPROP_FONT ,font);
   ObjectSetInteger (chart_ID,name, OBJPROP_FONTSIZE ,font_size);
   ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BGCOLOR ,back_clr);
   ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
   ObjectSetInteger (chart_ID,name, OBJPROP_STATE ,state);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
   ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selected);
   ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
   ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
//--- успешное выполнение
   return ( true );
  }
//+------------------------------------------------------------------+
 
MakarFX:

Inténtalo,

puede editar la función "Señal para abrir la orden".

Vaya, qué enorme código se ha convertido esto.

Muchas gracias, lo probaré hoy mismo.

 

Profesionales, un consejo... He hecho un botón en el gráfico.

) {
  if(id == CHARTEVENT_OBJECT_CLICK) {
    if(sparam == button.Name()) {
      Alert("Button \""+sparam+"\" clicked!"); // Вместо этого функция с кодом...
      button.State(0);
      ChartRedraw(0);
}}}

Intentando que cuando se pulse el botón en lugar de la alerta, se ejecute un script llamado K1, cuando se vuelva a pulsar se borre el script, pero no ha habido suerte. Gracias.

 
Константин:

Profesionales, un consejo... He hecho un botón en el gráfico.

Estoy intentando hacer que cuando se pulse el botón en lugar de la alerta, se ejecute un script llamado K1, cuando se vuelva a pulsar se borrará el script, pero falla. Gracias.

Mejor escribir el código de la secuencia de comandos donde el botón es
 
MakarFX:

Inténtalo,

la función "Señal para abrir la orden" puede editar

He probado los búhos en el probador. todo funciona perfectamente.

pero tengo un par de preguntas:

1. según entendí en las pruebas, los búhos mantienen un registro de la ganancia/pérdida actual de acuerdo a los parámetros que se le especifican, y no hace ninguna diferencia en el número de operaciones para que esto suceda,

Quiero saber si he alcanzado el beneficio/pérdida especificado en una operación o en tres operaciones consecutivas.

2. He puesto al Asesor Experto una reducción de 25$, pero ha fallado con una reducción de 40$ en un lote grande - ¿es normal para un probador? ¿Quizás es imposible ejecutar la prueba a máxima velocidad?

3. ¿es posible hacer que el seguimiento del beneficio/pérdida actual se restablezca después de cada operación, independientemente de la señal con la que se haya cerrado (tp/sl o después de alcanzar un beneficio/pérdida determinado )?

 
законопослушный гражданин:

He probado los búhos en el probador. todo funciona perfectamente.

Pero tengo un par de preguntas:

1. según he entendido en las pruebas, el búho rastrea el beneficio/pérdida actual según los parámetros que se le especifican, y no hace ninguna diferencia en el número de operaciones que se produzcan,

Quiero saber si he alcanzado el beneficio/pérdida especificado en una operación o en tres operaciones consecutivas.

2. Le pedí a mi Asesor Experto un drawdown de 25$, pero falló con un drawdown de 40$ en un lote grande - ¿es normal para un probador? ¿Quizás es imposible hacer una prueba a máxima velocidad?

3. ¿es posible hacer que el seguimiento de las ganancias/pérdidas actuales se restablezca después de cerrar cada operación, independientemente de la señal con la que se haya cerrado (tp/sl o después de alcanzar las ganancias/pérdidas especificadas )?

1) A alta velocidad o si no está en ticks en el probador, se cerrará al primer precio disponible.

2)Tienes un aumento de lote en marcha y con un lote grande 1 punto puede ser más que el nivel permitido.

3)No entiendo lo que quieres, ¿qué necesitas para hacer un seguimiento si la puesta a cero después de cada comercio?

 

¡¡¡Buenas tardes señores programadores!!!

Por favor, ayude a un novato con una función.

La función cuenta el beneficio total por historia.

El problema es que funciona para un corredor y no quiere funcionar para otro.

Funciona en Hercic pero no en RoboForex. Tengo una cuenta ECN en RoboForex.

No sé cuál es el problema. Aquí está el código:

double lastloss()

{

int typ = -1,cnt = 0;

double lastloss = 0;

for(int i = OrdersHistoryTotal()-1; i>=0; i--)

{

if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))

{

if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)

{

if(cnt == 0) typ = OrderType();

if(cnt > 0 && OrderType()!= typ) break;

lastlos += OrderProfit() + + OrderSwap() + OrderCommission();

cnt++;

}

}

}

return(lastlos);

}

Документация по MQL5: Торговые функции / OrderSelect
Документация по MQL5: Торговые функции / OrderSelect
  • www.mql5.com
OrderSelect - Торговые функции - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Hola. ¿Alguien conoce alguna biblioteca MQL gratuita para escribir estructuras de datos en un archivo y cargarlas después? Idealmente una biblioteca que trabaje con el formato json, parserjson, etc.
Razón de la queja: