Questions from Beginners MQL5 MT5 MetaTrader 5 - page 305

 
PokrovMT5:

Good evening all! I decided to put a trail on open trades in the tester, tried to go through OrderGet....() and realized that the deal went from the category of orders to an open position, respectively went through PositionGet....(), but again nothing works,

The question is if I should now use HistoryDealGet...() ? Or I don't understand something? Which way to go to modify SL in open trade in the tester? Thanks in advance for comments.

PositionSelect(Symbol())
 

Please direct me to !!!! how to implement in MQL5 the check of presence (or absence) of a graphical object, e.g. a trend line or a vertical line?

Ideally, I would like to use logic similar to "If Order Does Not Exist" or "If Order Exists".

 
aleks557:

Please direct me to !!!! how to implement in MQL5 the check of presence (or absence) of a graphical object, e.g. a trend line or a vertical line?

Ideally, I would like to use logic similar to "If Order Does Not Exist" or "If Order Exists".

https://www.mql5.com/ru/docs/constants/chartconstants/enum_chartevents
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы графиков / Типы событий графика
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы графиков / Типы событий графика
  • www.mql5.com
Стандартные константы, перечисления и структуры / Константы графиков / Типы событий графика - справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
pako:
Thank you! Everything works )).
 

Can you advise how to correctly implement the buying algorithm?

At the moment, the Expert Advisor has to buy many times, until it receives the information that there are open positions, and it lags behind. How to make the Expert Advisor wait for the exchange response after the first buy (when the conditions come).

The problem now is that the variable Bye_opened should become true and this should keep the EA from making unnecessary trades until the stops are triggered. But changing the variable Bye_opened takes a long time and the EA has time to make several trades.


What is missing in my code? Please point out the shortcomings.


 //--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
        }
     }

//+------------------------------------------------------------------+
//|   СОВЕРШАЕМ СДЕЛКУ                                               |
//+------------------------------------------------------------------+
                  
     if(last_tick.last < BBLow[2] && Buy_opened == false)
        {
        int znak = last_tick.last - BBLow[2];

      //--- 1. Создать запрос
         
         MqlTradeRequest Trade_reqst={0};            // Инициализация структуры торгового запроса
         Trade_reqst.action=TRADE_ACTION_DEAL;       // Тип: немедленное совершение сделки
         Trade_reqst.symbol=_Symbol;                 // Инструмент: текущий
         Trade_reqst.volume=Lot;                     // Объём: 1 лот
         Trade_reqst.price=SymbolInfoDouble(_Symbol,SYMBOL_ASK)-TakeProfit*_Point; // Цена исполнения
         Trade_reqst.type=ORDER_TYPE_BUY;            // Тип ордера: на продажу
         Trade_reqst.type_filling=ORDER_FILLING_RETURN; // Политика исполнения 
         Trade_reqst.sl=last_tick.last - StopLoss * _Point;  // Stop Loss
         Trade_reqst.tp=SymbolInfoDouble(_Symbol,SYMBOL_ASK) + TakeProfit * _Point; // Take Profit
      // Trade_reqst.tp=Trade_reqst.price + TakeProfit * 2 * _Point; // Take Profit
      //--- 2. Отправить торговый приказ
         MqlTradeResult Trade_reslt={0};             // Инициализация структуры результата торгового запроса
         OrderSend(Trade_reqst,Trade_reslt);         // Отправка торгового запроса на сервер
   //--- выведем в лог ответ сервера  
   //Print(__FUNCTION__," - : - ",Trade_reslt.comment);
   if(Trade_reslt.retcode==10016) Print("Ответ: ",Trade_reslt.bid,Trade_reslt.ask,Trade_reslt.price);
 
mavar:

The problem now is that the variable Bye_opened should become true and this should keep the EA from making unnecessary trades until the stops are triggered. But changes of variable Bye_opened take long time and EA has time to make several trad es.

Just because a variable change takes a long time... how did you determine that? Ok, let's assume that it is. Then the answer lies in the question. If you need a delay in opening of a position you must use Sleep( N ) where N is calculated experimentally.

Variant 2. The answer, again, is in the question. Make Bye_opened global and change it immediately after the position is successfully opened, right in this module. Reset in the same way, as you check the existence of position.

 
papaklass:
...

If you insert a line

after the command: OrderSend(), there will be no reopening of positions.

Maybe it's better to check whether the position has opened first, and then ...

???

 
papaklass:

Apparently he has a robot running on every tick. Between sending the order to the server and receiving the response from the server, several more ticks will come and an extra position will open on each tick. My proposal excludes the situation of repetition of openings. And it is necessary to check whether a position has been opened or not.

That's what I mean. Otherwise, they will literally understand everything and miss an important check.
 
artmedia70:
That's what I'm saying. Otherwise it would literally understand everything and miss an important check.

So this is actually how to check correctly? Sorry, I can't get it right.

Here's the code (all located in the OnTick block):


void OnTick()
  {

      MqlTick last_tick;
     
      if(SymbolInfoTick(Symbol(),last_tick))
        {
        // Print(last_tick.time,": Bid = ",last_tick.bid,
        //       " Ask = ",last_tick.ask,"  Volume = ",last_tick.volume, "  LastPrice = ",last_tick.last );
        }
      else Print("SymbolInfoTick() failed, error = ",GetLastError());
      //---
      
        //---Читаем свечку
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int copied=CopyRates(Symbol(),0,0,1,rates);
   if(copied>0)
     {
      //Print("Скопировано баров: "+copied);
      string format="open = %G, high = %G, low = %G, close = %G, volume = %d";
      string out;
      int size=fmin(copied,10);
      for(int i=0;i<size;i++)
        {
         //out=i+":"+TimeToString(rates[i].time);
         out=out+" "+StringFormat(format,
                                  rates[i].open,
                                  rates[i].high,
                                  rates[i].low,
                                  rates[i].close,
                                  rates[i].tick_volume);
        // Print(out);
       
         //Print(rates[i].open - rates[i].close );

        }
     }
   else Print("Не удалось получить исторические данные по символу ",Symbol());

//---=======-----\_____BOLLINGER____/--------========--//
//--- получить хэндл индикатора Bollinger Bands и DEMA
      BolBandsHandle=iBands(NULL,my_timeframe,bands_period,bands_shift,deviation,PRICE_LOW);
      ChartIndicatorAdd(0,0,BolBandsHandle);
   
//--- копируем новые значения индикаторов используя хэндлы
   if(CopyBuffer(BolBandsHandle,0,0,3,BBMidle)<0 || CopyBuffer(BolBandsHandle,1,0,3,BBUp)<0
      || CopyBuffer(BolBandsHandle,2,0,3,BBLow)<0)
     {
      Alert("Ошибка копирования буферов индикатора Bollinger Bands - номер ошибки:",GetLastError(),"!!");
      return;
     }
//********** это цикл надо добавить в код советника, выводит значения при наступлении нового бара
   //for(int nbar=0; nbar < 3; nbar++)
    // Print("nbar=", nbar, "  BBLow[nbar]=", DoubleToString(BBLow[nbar], _Digits), "  BBMidle[nbar]", DoubleToString(BBMidle[nbar], _Digits),
   //                 "  BBUp[nbar]=", DoubleToString(BBUp[nbar], _Digits));
      
      
  //--- Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   
       
   //--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
        }
     }

//+------------------------------------------------------------------+
//|   СОВЕРШАЕМ СДЕЛКУ                                               |
//+------------------------------------------------------------------+
                  
     if(last_tick.last < BBLow[2]-natyajka && Buy_opened == false)
        {
        int znak = last_tick.last - BBLow[2];

      //--- 1. Создать запрос
         
         MqlTradeRequest Trade_reqst={0};            // Инициализация структуры торгового запроса
         Trade_reqst.action=TRADE_ACTION_DEAL;       // Тип: немедленное совершение сделки
         Trade_reqst.symbol=_Symbol;                 // Инструмент: текущий
         Trade_reqst.volume=Lot;                     // Объём: 1 лот
         Trade_reqst.price=SymbolInfoDouble(_Symbol,SYMBOL_ASK)-TakeProfit*_Point; // Цена исполнения
         Trade_reqst.type=ORDER_TYPE_BUY;            // Тип ордера: на продажу
         Trade_reqst.type_filling=ORDER_FILLING_RETURN; // Политика исполнения 
         Trade_reqst.sl=last_tick.last - StopLoss * _Point;  // Stop Loss
         Trade_reqst.tp=SymbolInfoDouble(_Symbol,SYMBOL_ASK) + TakeProfit * _Point; // Take Profit
      // Trade_reqst.tp=Trade_reqst.price + TakeProfit * 2 * _Point; // Take Profit
      //--- 2. Отправить торговый приказ
         MqlTradeResult Trade_reslt={0};             // Инициализация структуры результата торгового запроса
         OrderSend(Trade_reqst,Trade_reslt);         // Отправка торгового запроса на сервер
   //--- выведем в лог ответ сервера  
   //Print(__FUNCTION__," - : - ",Trade_reslt.comment);
   if(Trade_reslt.retcode==10016) Print("Ответ: ",Trade_reslt.bid,Trade_reslt.ask,Trade_reslt.price);

//--- вернем код ответа торгового сервера
        Print("Покупаю. Buy_opened = ", Buy_opened);
        Print( "last_tick.last= ", last_tick.last, 
               " last_tick.ask= ", last_tick.ask, " - ",    
               " BBLow= ",DoubleToString(BBLow[2], _Digits) , 
               " SYMBOL_BID=", SymbolInfoDouble(_Symbol,SYMBOL_BID),
               " SYMBOL_ASK=", SymbolInfoDouble(_Symbol,SYMBOL_ASK), 
               " StopLoss=", StopLoss,
               " TakeProfit=", TakeProfit,
               " Trade_reslt.bid=", Trade_reslt.bid,
               " Trade_reslt.bid=", Trade_reslt.bid,
               " Trade_reslt.ask=", Trade_reslt.ask
            ); 

      
   //return Trade_reslt.retcode;

         
        }

  } 
 
papaklass:

In order to avoid opening unnecessary volumes:

Unfortunately, this condition does not work when opening a trade.

      //проверка выполнения торгового приказа
      if(Trade_reslt.retcode==10009)   //заявка выполнена
      {
         Bye_opened = true;
      }