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

 
Alexey Viktorov:

with identifiers CHART_PRICE_MIN and CHART_PRICE_MAX

Seems to be just what I need. Thank you so much!!!
 
MakarFX:

returns true/false , what time are we talking about?

The class stores the time of the previous tick, and true/false is not returned by the class, but by a member functionof the class:

void OnTick()
{
    if (NB_M1.IsNewBar())  // (1) Если появился новый бар M1
        {....}
    ......
}
 
Mikhail Tkachev:

The class stores the time of the previous tick, and true/false is not returned by the class, but by a member functionof the class:

In the code you posted the public only bar!

Given that the class reports a new bar, the time is iTime(all you need,0),

respectively the previous time iTime(all you need,1)

Z.U. Maybe you know how to get the time with fractions of a second...

 
MakarFX:

In the code you posted, the publc is only bool!

Given that the class reports a new bar, the time is iTime(all you need,0),

respectively the previous time iTime(all you need,1)

Z.U. Maybe you know how to get the time with fractions of a second...

My mistake, sorry

I don't need fractions of a second. I need to catch the first second of a new bar

 
Mikhail Tkachev:

Wrong a bit, sorry

I don't need fractions of a second. I need to catch the first second of a new bar

like this

datetime NB_M1;
int OnInit()
{
}

void OnTick()
{
   if (CIsNewBar(_Symbol,PERIOD_M1))  // (1) Если появился новый бар M1
        {NB_M1=TimeCurrent();}
    ......
}

and to save the previous value

datetime NB_01_M1, NB_02_M1;
int OnInit()
{
}

void OnTick()
{
   if (CIsNewBar(_Symbol,PERIOD_M1))  // (1) Если появился новый бар M1
        {NB_02_M1=NB_01_M1; NB_01_M1=TimeCurrent();}
    ......
}
 
MakarFX:

then it's like this

Thank you, MakarFX, I will try it)

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

ok, thanks, I'll think about it and run it in the tester.

please tell me more about the martin function in your code.

where do I need to replace something so that martin spreads to profitable orders instead of unprofitable ones?

 //+------------------------------------------------------------------+
//|                                                 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 );
  }
//+------------------------------------------------------------------+
 
законопослушный гражданин:

Please tell me more about the martin function in your code.

Where should I replace what, so that a martin will be applied to profitable orders instead of losing ones?

Highlighted...if <0, then the lot of a losing trade is increased

if >0, then the lot of a profit trade is increased

//+------------------------------------------------------------------+
//| Расчет лота                                                      |
//+------------------------------------------------------------------+
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);
  }
 
AMarkov:
That seems to be what you need. Thank you so much!!!

This is not the way to do it! This is how you get the minimum and maximum prices of the instrument, not the oscillator. An experienced programmer is ashamed to give such answers to such elementary questions...

In fact, you need to get the oscillator data using the CopyBufer

    int s, len;
    double main[];
    double min, max;
    len = (int)ChartGetInteger(0, CHART_VISIBLE_BARS); // длина копируемых видимых значений
    s = (int)ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR) - len + 1; // 1-й видимый бар минус длина -- начало копируемых баров
    if (CopyBuffer(handle, MAIN_LINE, s, len, main) != len)
      return;
    // handle - хэндэл осциллятора
    // MAIN_LINE - меняем на нужный индекс буфера осциллятора
    // получаем мин. и макс. значения
    min = main[ArrayMinimum(main, 0, WHOLE_ARRAY)];
    max = main[ArrayMaximum(main, 0, WHOLE_ARRAY)];
        

How to create an oscillator

handle = iMACD(NULL, PERIOD_CURRENT, 12, 26, 1, PRICE_CLOSE);

Or any other oscillator you need.

 
MakarFX:

Highlighted...if <0, then the lot of the losing trade is increased

if >0 then the lot of the profitable trade is increased

Thank you very much

Reason: