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

 
Nerd Trader #:

Removed unnecessary code.

I'm already totally desperate, even added a print variable when it's sent to OnTick... and if it helped :) it's always false in OnTick


bool BESet(double sl = 0, color arrow_color = 0, string order_type = ""){
  bool order = OrderModify( OrderTicket(), OrderOpenPrice(), sl, OrderTakeProfit(), 0, arrow_color );
          if(!order) {
            ResetLastError();
            Print("!Ошибка ",order_type,". Причина: ", GetLastError());
            return false;
          }
          else {
            return true;
          }
}

bool BEActivate(){
  double unrealized_profit = 0;
  color arrow_color = 0;
  string order_type = "";
  double sl = 0;
  bool is_be = false; // если объявить true, то в OnTick всегда будет возвращаться true

  if(OrdersTotal() >= 1){
    for(int i = OrdersTotal() -1; i >= 0; i--){
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
      if(OrderType() == OP_BUY){
        if(OrderStopLoss() > OrderOpenPrice()) continue;
        unrealized_profit = NormalizeDouble(MathAbs(OrderOpenPrice() - Ask)/Point, 0);
        if(unrealized_profit >= save_zone && Ask > OrderOpenPrice()){
          is_be = BESet(NormalizeDouble(OrderOpenPrice()+breakeven*Point,Digits), clrGreenYellow, "Бай");
          Print("BE ",is_be);
        }
      }
      if(OrderType() == OP_SELL){
        ...
        ...
      }
    }
  }
    if(!is_be){
    Print("is_be return ",is_be);
    return false;
  }
  else{
    Print("is_be return ",is_be);
    return true;
  }
}

void OnTick()
{
  
  bool is_be = BEActivate();

  if(last_time > bar.time_open){
    bar.Initialize();
    Print("is_be ",is_be); //Всегда FALSE
    ...
  }
last_time = iTime(NULL, 0, 0);
}
 
MakarFX #:

What does it mean?

I'm just looking for someone to share the experience of integrating an indicator into an Expert Advisor

To be able to calculate this data on different TFs.

const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],

I wonder if anyone has an implementation through a class.

I'm trying to understand the logic of classes, it would be a great help for learning.

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

Good afternoon. Can you help me solve a problem. on an M15 candlestick, several trades open in a row.

I want no more than one trade to open. The logic behind the EA is that until the previous order is closed, the next one will not open, but sometimes a series of deals opens on such a long candlestick. Please advise what to add in the code to prevent this situation?

code snippet :

In bCheckOrders(), not only open orders but also pending orders (MODE_TRADES) are enumerated.
 
Nerd Trader #:

Um... in iOTi in vOrderModify() always = 1, it's not a ticket but a positive result of OrderSend() operation i.e. value "1".


Thanks. The original code is not mine, so I don't change anything unnecessarily. It works and it works.

Will this help solve my problem?

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

Good afternoon. Can you help me solve a problem. on an M15 candle, several trades open in a row.

I want no more than one trade to open. The logic behind the EA is that until the previous order is closed, the next one will not open, but sometimes a series of deals opens on such a long candlestick. Please advise what to add in the code to prevent this situation?

code snippet :

Show OnTick()
 
Mikhail Toptunov #:
I'm just looking for someone who is able to share experience in implementing indicator integration in Expert Advisor

To be able to calculate this data on different TFs.

I wonder if anyone has an implementation through a class.

I'm trying to understand the logic of classes, it would be a great help for learning.

rates_total = Bars
time[]      = Time[]
open[]      = Open[]
high[]      = High[]
low[]       = Low[]
close[]     = Close[]
 
MakarFX #:
Show OnTick()
void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

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

// Если появился сигнал на продажу, то откроем ордер на продажу
      if(bSignalSell() == true)
         vOrderOpenSell();
     }
// Проверяем, вышел ли текущий баланс по открытому ордеру за вилку из внешних переменных CountLoss и CountProfit

  if(GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*-1)
     {
// Если да, то закроем ордер по текущей цене, не дожидаясь стопа или тейка
      CloseOrder();
     }
DrawLABEL("lab_Take",1,5,0,Color(GetProfitFromStart()>0,Lime,Red),StringConcatenate("Profit: ",DoubleToStr(GetProfitFromStart(),2),AC));
  }
 
законопослушный гражданин #:

Thank you. The original code is not mine, so I don't change anything unnecessarily. It works and it works.

Does this solve my problem in any way?

Nah, I was wrong, OrderSend() returns a ticket or -1, so there's nothing wrong with that.
 
законопослушный гражданин #:

Try this, remove bCheckOrders() from OnTick() and put it as highlighted.

void OnTick()
  {
// Получим значение индикатора
   dMA = iMA(Symbol(), 0,PeriodMA, MovingShift, MODE_SMA, PRICE_CLOSE, 0); // MODE_SMA - простое усреднение , значение 0. PRICE_CLOSE- цена закрытия, значение 0.

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

// Если появился сигнал на продажу, то откроем ордер на продажу
      if(bSignalSell() == true)
         vOrderOpenSell();
// Проверяем, вышел ли текущий баланс по открытому ордеру за вилку из внешних переменных CountLoss и CountProfit

  if(GetProfitFromStart()>CountProfit || GetProfitFromStart()<CountLoss*-1)
     {
// Если да, то закроем ордер по текущей цене, не дожидаясь стопа или тейка
      CloseOrder();
     }
DrawLABEL("lab_Take",1,5,0,Color(GetProfitFromStart()>0,Lime,Red),StringConcatenate("Profit: ",DoubleToStr(GetProfitFromStart(),2),AC));
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на покупку |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenBuy()
  {
// Если нет открытых ордеров, то входим в условие
   if(bCheckOrders() == true)
     {
   // Тикет ордера
      int iOTi = 0;   
   
      iOTi = OrderSend(Symbol(), OP_BUY, LOT(), Ask, Slippage, 0, 0, "", Magic, 0, clrNONE);
   
   // Проверим открылся ли ордер
      if(iOTi > 0)
   // Есди да, то выставим уровни убытка и прибыли
         vOrderModify(iOTi);
      else
   // Если нет, то получим ошибку
      vError(GetLastError());
     }
  }
//+-----------------------------------------------------------------------------------------------+
//|                                                            Функция открытия ордера на продажу |
//+-----------------------------------------------------------------------------------------------+
void vOrderOpenSell()
  {
// Если нет открытых ордеров, то входим в условие
   if(bCheckOrders() == true)
     {
   // Тикет ордера  
      int iOTi = 0;   
   
      iOTi = OrderSend(Symbol(), OP_SELL, LOT(), Bid, Slippage, 0, 0, "", Magic, 0, clrNONE);
   
   // Проверим открылся ли ордер
      if(iOTi > 0)
   // Есди да, то выставим уровни убытка и прибыли
         vOrderModify(iOTi);
      else
   // Если нет, то получим ошибку
      vError(GetLastError());
     }
  }
 
Nerd Trader #:
Nah, I was wrong, OrderSend() returns a ticket or -1, so there's nothing wrong with that.

Okay.

I'll keep that in mind for the future.

Reason: