Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1226

 
Alexey Belyakov:


That didn't work either.

What a hobgoblin likes kilometres of code...

Your problem can be solved in SIX lines of code, taking into account declaration of variables.

/************************Expert tick function************************/
void OnTick()
 {
  bool signal = true;
  datetime timeBar = iTime(_Symbol, PERIOD_CURRENT, 0);// период можно поставить по своему усмотрению
  datetime static timeOpen = 0;
  if(timeBar > timeOpen)
   {
    if(signal)
     {
      // открыть позицию
      timeOpen = timeBar;
     }
   }
 }/******************************************************************/

I hope you can figure out the signal variable.

 

О! It's working! Thank you, comrades, for the ideas!

But I had to tweak it a bit. It even got easier, without (true). Although I can't explain this complicated MQL logic).

That's how I implemented it:

datetime timeBar = iTime(_Symbol,PERIOD_CURRENT, 0);// период можно поставить по своему усмотрению
datetime static timeOpen = 0;

if((PositionsTotal()==0)&&(c0>h1)&&(rGENUP>0.30)&&(timeBar > timeOpen))    // Условие для открытия позиции.
     {
      MqlTradeRequest request;
      MqlTradeResult  result;
      request.action   =TRADE_ACTION_DEAL;                         // тип торговой операции
      request.symbol   =Symbol();                                 // символ
      request.volume   =1;                                       // объем в 1 лот
      request.type     =ORDER_TYPE_BUY;                         // тип ордера
      request.price    =SymbolInfoDouble(Symbol(),SYMBOL_ASK); // цена для открытия
      request.deviation=3;
      request.sl    = NormalizeDouble(Ask-50*_Point,_Digits);
      request.tp    = NormalizeDouble(Ask+50*_Point,_Digits);    

      if(!OrderSend(request,result))
         PrintFormat("OrderSend error %d",GetLastError());     // если отправить запрос не удалось, вывести код ошибки
      //--- информация об операции
      PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
      // допустимое отклонение от цены
timeOpen = timeBar;
}
I wonder why there is such a big code in MQL5 for position opening. Unlike MQL4. In 4 it's just one line. Can we cut it down? For example, can we remove the error handler?


Совершение сделок - Торговые операции - Справка по MetaTrader 5
Совершение сделок - Торговые операции - Справка по MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
 
Alexey Belyakov:

О! It's working! Thank you, comrades, for the ideas!

But I had to tweak it a bit. It even got easier, without (true). Although I can't explain this complicated MQL logic).

That's how I implemented it:

I wonder why there is so much code in MQL5 to open a position. Unlike MQL4. In 4, it's just one line. But here... Can you make it shorter? For example, can we remove the error handler?


Use trade classes. And the code will be very short.

Example:

//+------------------------------------------------------------------+
//|                                            Only_one_purchase.mq5 |
//+------------------------------------------------------------------+
#property version   "1.003"
#property script_show_inputs
#include <Trade\Trade.mqh>
CTrade         m_trade;          // trading object
//--- input parameters
input ENUM_POSITION_TYPE   InpPositionType   = POSITION_TYPE_BUY; // Position Type
input double               InpVolume         = 0.0;               // Volume
input ulong                m_magic           = 15489;             // magic number
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   m_trade.SetExpertMagicNumber(m_magic);
//--- open a position
   if(InpPositionType==POSITION_TYPE_BUY)
      m_trade.Buy(InpVolume);
   else
      m_trade.Sell(InpVolume);
  }
//+------------------------------------------------------------------+
 
Alexey Belyakov:

О! It's working! Thank you, comrades, for the ideas!

But I had to tweak it a bit. It even got easier, without (true). Although I can't explain this complicated MQL logic).

That is how I implemented it:

I wonder why there is such a big code in MQL5 for position opening. Unlike MQL4. In 4, it's just one line. But here... Can it be shortened? For example, can we remove the error handler?


So, if you have in the condition

if((PositionsTotal()==0)&&

why do you need more checks for a new bar? Or is there an option that position will be closed at the same bar and the second opening should be prohibited?

 
Alexey Belyakov:

О! It's working! Thank you, comrades, for the ideas!

But I had to tweak it a bit. It even got easier, without (true). Although I can't explain this complicated MQL logic).

That's how I implemented it:

I wonder why there is such a big code in MQL5 for opening a position. Unlike MQL4. In 4, it's just one line. But here... Can it be shortened? For example, can we remove the error handler?


You know, long ago, when there was MQL4, people were indignantly saying that they hadn't been given lower-level access - so that they could do something in their own way.

Well, they did - now they gave access to OrderSend() in MQL4 - so to speak, they deployed its logic in MQL - so do what you want. But no - now I've got complaints that it's too complicated.

Complicated? No problem - give you trade classes in SB - they are almost the same as in MQL4 standard trade functions.
In MQL4 such classes are the trade functions. And in MQL5 - all with open access.

Take advantage of it.

 
Artyom Trishkin:

You know, long time ago, when there was MQL4, people were indignantly saying that they didn't give them lower-level access - so that they could do something in their own way.

Well, they did - now they gave access to OrderSend() in MQL4 - so to speak, they deployed its logic in MQL - so do what you want. But no - now I've got complaints that it's too complicated.

Complicated? No problem - give you trade classes in SB - they are almost the same as in MQL4 standard trade functions.
In MQL4 such classes are the trade functions. And in MQL5 - all with open access.

Take advantage of it.

Docent, and Docent. Why are you so angry (today) ©

 
Alexey Viktorov:

Docent, ah Docent. Why are you so angry (today) ©

Get in the ice hole...

 
Alexey Viktorov:

So if you have a condition

why do we need to check for a new bar? Or is there an option that the position will close on the same bar and we should disallow a second opening?

Exactly right - there is an option to close the position on the same bar.

 

(Cut into the new wall. ) The "wall" is called breakeven.

This is how it was implemented in MQL4:

(I copied it somewhere I do not remember).

int BULevel=30;

   for(int i=0; i<OrdersTotal(); i++) 
      {
       if(OrderSelect(i, SELECT_BY_POS))
        {      
         if(OrderType()==OP_BUY) 
          {
           if(OrderOpenPrice()<=(Bid-BULevel*Point)&&OrderOpenPrice()>OrderStopLoss())
            {      
             int p=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-50*Point,OrderTakeProfit(),0,Green);
            }
           }       
 
         if(OrderType() == OP_SELL) 
           {
            if(OrderOpenPrice()>=(Ask+BULevel*Point)&&OrderOpenPrice()<OrderStopLoss()) 
             {
              p=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+50*Point,OrderTakeProfit(),0,Red);
             }
           } 
         }
       }

//------------------------------------------------------------------+

But here is how it is implemented in 5-PC. How do I do it?

I looked through the Trading Classes, I don't see it in there. But the thing is needed. What do the pros say?

 

How can I prevent trades from other charts from appearing on the chart?

Only the trades of the robot that is on the given chart.

Reason: