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

 
MakarFX:

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

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

Hi.

I have another question about your EA

when testing it on a demo account, the following happened:

When the EA reaches the specified parameters, it has shifted to the "stop" mode, i.e., the "start" button is lit, but trading has not stopped and trades are very short, literally one or two cents. Is this the way it should be?

I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)

looked at the logs, no errors anywhere...

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

Hello.

I have another question about your Expert Advisor

when testing it on a demo, the following happened:

When the EA reaches the preset parameters, it switches to the "stop" mode, i.e. the "start" button is on, but the trading is not stopped, but very short trades are opened, just one or two cents. Is this the way it should be?

I have also found out that the EA has closed some deals not at take or stop price and not at the money limit, but "for nothing" and the price has passed various amount of points before it was closed. At the same time, the Expert Advisor completely covers the previous losses, by a couple of cents, (for example, three deals in a row have (-15.59 $) a profitable deal = +15.62 $ and closed it immediately!)

looked at the logs, no errors anywhere...

Please send us the code with your fixes. We will see.

 
MakarFX :

Post your code with your fixes. We will see.

so I'm still testing the uncorrected one, your native one.

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

so I'm still testing the uncorrected one, your native one.

I don't see any errors...

Write what period, on what pair and what parameters were there when the errors occurred.

 
MakarFX:

I don't see any errors...

write what period, on what pair and what parameters were present when the errors occurred.

these settings:

timeframe_RSI=0 period_RSI=14 level_buy=30 level_sell=70 Lot=0.01 K_Martin=1.6 Stoploss=200 Takeprofit=1000 CountLoss=100.0 CountProfit=25.0 Magic=777 DigitsLot=2 slippage=3

report is attached below.

there yellow lines with "unclear" closing, neither by stop, take profit, nor by money.

and blue - trades that were opened and closed almost immediately

Files:
v4a73y05.jpg  312 kb
f9o3ssd3.png  92 kb
 

Hello!

Please advise which function and where to add to this simple EA,

In addition to existing ways to reset a lot to the initial one,

If you want to close the current position when a drawdown of the current position is reached, specified in the deposit currency, and then, when you open the next one, to reset the lot to the starting one?

//+-----------------------------------------------------------------------------------------------+
//|                                                                     Simple Moving Average.mq4 |
//|                                                                 Copyright 2016, Andrey Minaev |
//|                                                     https://www.mql5.com/ru/users/id.scorpion |
//+-----------------------------------------------------------------------------------------------+
#property copyright "Copyright 2016, Andrey Minaev"
#property link      "https://www.mql5.com/ru/users/id.scorpion"
#property version   "1.00"
#property strict

// Параметры советника
extern string sParametersEA = "";     // Параметры советника
extern double dLots         = 0.01;   // Количество лотов
extern int    iStopLoss     = 30;     // Уровень убытка (в пунктах)
extern int    iTakeProfit   = 30;     // Уровень прибыли (в пунктах)
extern int    iSlippage     = 3;      // Проскальзование (в пунктах)
extern int    iMagic        = 1;      // Индентификатор советника
extern double K_Martin     = 2.0;
extern int    OrdersClose  = 5;
extern int    DigitsLot    = 2;
// Параметры индикатора
extern string sParametersMA = "";     // Параметры индикатора
extern int    iPeriodMA     = 14;     // Период усреднения
// Глобальные переменные
double dMA;
//+-----------------------------------------------------------------------------------------------+
int OnInit()
  {
// Если брокер использует 3 или 5 знаков после запятой, то умножаем на 10
   if(Digits == 3 || Digits == 5)
     {
      iStopLoss   *= 10;
      iTakeProfit *= 10;
      iSlippage   *= 10;
     }

   return(INIT_SUCCEEDED);
  }
//+-----------------------------------------------------------------------------------------------+
void OnDeinit(const int reason)
  {

  }
//+-----------------------------------------------------------------------------------------------+
void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0, iPeriodMA, 0, MODE_SMA, PRICE_CLOSE, 0);

// Если нет открытых ордеров, то входим в условие
   if(bCheckOrders() == true)
     {
      // Если появился сигнал на покупку, то откроем ордер на покупку
      if(bSignalBuy() == true)
         vOrderOpenBuy();

      // Если появился сигнал на продажу, то откроем ордер на продажу
      if(bSignalSell() == true)
         vOrderOpenSell();
     }
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция проверки открытых оредров |
//+-----------------------------------------------------------------------------------------------+
bool bCheckOrders()
  {
// Переберем в цикле ордера, для проверки открытых ордеров данным советником
   for(int i = 0; i <= OrdersTotal(); i++)
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == iMagic)
            return(false);

   return(true);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на покупку |
//+-----------------------------------------------------------------------------------------------+
bool bSignalBuy()
  {
   if(dMA > Open[1] && dMA < Close[1])
      return(true);

   return(false);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                             Функция поиска сигнала на продажу |
//+-----------------------------------------------------------------------------------------------+
bool bSignalSell()
  {
   if(dMA < Open[1] && dMA > Close[1])
      return(true);

   return(false);
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на покупку |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenBuy()
  {
   int iOTi = 0;   // Тикет ордера

   iOTi = OrderSend(Symbol(), OP_BUY, LOT(), Ask, iSlippage, 0, 0, "", iMagic, 0, clrNONE);

// Проверим открылся ли ордер
   if(iOTi > 0)
      // Есди да, то выставим уровни убытка и прибыли
      vOrderModify(iOTi);
   else
      // Если нет, то получим ошибку
      vError(GetLastError());
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на продажу |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenSell()
  {
   int iOTi = 0;   // Тикет ордера

   iOTi = OrderSend(Symbol(), OP_SELL, LOT(), Bid, iSlippage, 0, 0, "", iMagic, 0, clrNONE);

// Проверим открылся ли ордер
   if(iOTi > 0)
      // Есди да, то выставим уровни убытка и прибыли
      vOrderModify(iOTi);
   else
      // Если нет, то получим ошибку
      vError(GetLastError());
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                                    Функция модификации ордера |
//+-----------------------------------------------------------------------------------------------+
void vOrderModify(int iOTi)
  {
   int    iOTy = -1;   // Тип ордера
   double dOOP = 0;    // Цена открытия ордера
   double dOSL = 0;    // Стоп Лосс
   int    iMag = 0;    // Идентификатор советника

   double dSL = 0;     // Уровень убытка
   double dTP = 0;     // Уровень прибыли

// Выберем по тикету открытый ордер, получим некоторые значения
   if(OrderSelect(iOTi, SELECT_BY_TICKET, MODE_TRADES))
     {
      iOTy = OrderType();
      dOOP = OrderOpenPrice();
      dOSL = OrderStopLoss();
      iMag = OrderMagicNumber();
     }

// Если ордер открыл данный советник, то входим в условие
   if(OrderSymbol() == Symbol() && OrderMagicNumber() == iMag)
     {
      // Если Стоп Лосс текущего ордера равен нулю, то модифицируем ордер
      if(dOSL == 0)
        {
         if(iOTy == OP_BUY)
           {
            dSL = NormalizeDouble(dOOP - iStopLoss * Point, Digits);
            dTP = NormalizeDouble(dOOP + iTakeProfit * Point, Digits);

            bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
           }

         if(iOTy == OP_SELL)
           {
            dSL = NormalizeDouble(dOOP + iStopLoss * Point, Digits);
            dTP = NormalizeDouble(dOOP - iTakeProfit * Point, Digits);

            bool bOM = OrderModify(iOTi, dOOP, dSL, dTP, 0, clrNONE);
           }
        }
     }
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                                      Функция обработки ошибок |
//+-----------------------------------------------------------------------------------------------+
void vError(int iErr)
  {
   switch(iErr)
     {
      case 129:   // Неправильная цена
      case 135:   // Цена изменилась
      case 136:   // Нет цен
      case 138:   // Новые цены
         Sleep(1000);
         RefreshRates();
         break;

      case 137:   // Брокер занят
      case 146:   // Подсистема торговли занята
         Sleep(3000);
         RefreshRates();
         break;
     }
  }
//+-----------------------------------------------------------------------------------------------+

double LOT()
{
   int n=0;
   double OL=dLots;
   for (int j = OrdersHistoryTotal()-1; j >= 0; j--)
   {
      if (OrderSelect(j, SELECT_BY_POS,MODE_HISTORY))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == iMagic)
         {
            if (OrderProfit()<0) 
            {
               if (n==0) OL=NormalizeDouble(OrderLots()*K_Martin,DigitsLot);
               n++;
               if (n>=OrdersClose) {Comment("1");return(dLots);}
            }
            else
            {
               if (n==0) {Comment("2");return(dLots);}
               else {Comment("3");return(OL);}
            }
         }
      }
   }
   return(OL);
}
//------------------------------------------------------------------


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

here are the settings:

timeframe_RSI=0 period_RSI=14 level_buy=30 level_sell=70 Lot=0.01 K_Martin=1.6 Stoploss=200 Takeprofit=1000 CountLoss=100.0 CountProfit=25.0 Magic=777 DigitsLot=2 slippage=3

report is attached below.

there yellow lines with "unclear" closing, neither by stop ,take, nor by money.

And blue lines represent deals that were opened and closed almost immediately.

On what timeframe?

 
Thanks for the tip people , I did it this way, it says when it goes to stop loss or take profit
//--- get transaction type as enumeration value
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      long     deal_entry        =0;
      double   deal_profit       =0.0;
      double   deal_volume       =0.0;
      string   deal_symbol       ="";
      long     deal_magic        =0;
      long     deal_reason       =-1;
      if(HistoryDealSelect(trans.deal))
        {
         deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);
         deal_profit=HistoryDealGetDouble(trans.deal,DEAL_PROFIT);
         deal_volume=HistoryDealGetDouble(trans.deal,DEAL_VOLUME);
         deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);
         deal_magic=HistoryDealGetInteger(trans.deal,DEAL_MAGIC);
         deal_reason=HistoryDealGetInteger(trans.deal,DEAL_REASON);
        }
      else
         return;

      if(deal_symbol==m_symbol.Name() && deal_magic==m_magic)
         if(deal_entry==DEAL_ENTRY_OUT)
           {
            if(deal_reason==DEAL_REASON_SL)
               SendNotification (" Закрыл  позицию > StopLoss");

            if(deal_reason==DEAL_REASON_TP)
               SendNotification ("Закрыл  позицию > TakeProfit");
           }
     }
  }


and so on a new buy or sell

void OPENORDER(string ord)

  {

  
  double priceL=m_symbol.Ask();
   if(ord=="Sell")      
     SendNotification (" открыл позицию > short");
        //--- check for free money
            if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_BUY,my_lot,priceL)<0.0)
               printf("We have no money. Free Margin = %f",m_account.FreeMargin());
            else
      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
         Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of Retcode: ",m_trade.ResultRetcodeDescription(),
               ", ticket of order: ",m_trade.ResultOrder());                     // Если sell, то не открываемся
     double priceS=m_symbol.Bid();
   if(ord=="Buy")
     SendNotification (" открыл позицию > long");
         //--- check for free money
            if(m_account.FreeMarginCheck(Symbol(),ORDER_TYPE_SELL,my_lot,priceS)<0.0)
               printf("We have no money. Free Margin = %f",m_account.FreeMargin());
            else
      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
 
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription(),
               ", ticket of deal: ",m_trade.ResultDeal());
 

Greetings. Please advise on mt5.

I need to make an EA based on an indicator, so that the EA can work without the presence of an indicator.
Is it possible to make the data of an indicator inscribed in it appear on the chart, so that these lines do not become objects?


 
Andrey Sokolov:

Greetings. Please advise me on mt5.

I need to make an EA based on an indicator, so the EA can work without the indicator.
Is it possible to display the data of the indicator written in it on the chart, so as not to make these lines as objects?


ChartIndicatorAdd()

Документация по MQL5: Операции с графиками / ChartIndicatorAdd
Документация по MQL5: Операции с графиками / ChartIndicatorAdd
  • www.mql5.com
ChartIndicatorAdd - Операции с графиками - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
Reason: