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

 
Motzaart:

Afternoon.

In a multicurrency Expert Advisor, I need to close a pending order placed against a profit when an open position triggers.

Right now, when I close a pending order at profit, all the pending orders for all currencies are closed.

How to change the code so that only the pending order linked to a currency pair closes and the rest remain open?

What should I change in this code?

Mn in this code is a magic number of a pending order BUY_STOP or SELL_STOP.

The logic is that when an open position is closed at Take Profit, this magic number is left and the command to delete it is supposed to be executed.

This works when testing each pair. However, when working with other currencies, all orders placed on all pairs are deleted.

Please help, if you can.

I understand that no one should bother with this problem, but maybe someone has a ready-made template?

I would be very grateful.

I had to copy the code into the editor and do normal styling (Ctrl+<) to understand what you've messed up there.

So: commented in the code what was messed up there:

//+------------------------------------------------------------------+
if(OrderMagicNumber()==Mn)  // а ордер где-то был выбран ранее?
  {
   operation=0; // неиспользуемая переменная
     { // лишняя скобка
      for(int i=OrdersTotal()-1; i>=0; i--)
        {
         OrderSelect(i, SELECT_BY_POS); // нет проверки на результат выделения ордера в списке, и если ордер не выбран, то всё последующее вызовет ошибки
         int  type   = OrderType();
         bool result = false;
         switch(type)
           { // К СВЕДЕНИЮ - ВСЕ ОПЕРАТОРЫ break ЗАКОММЕНТИРОВАНЫ, А ЗНАЧИТ - ВСЕ СТРОКИ КОДА ОПЕРАТОРА switch ВЫПОЛНЯЮТСЯ ВСЕГДА
            case OP_BUYSTOP   : // Если выбран отложенный BuyStop, то пытаемся его закрыть как позицию, что вызовет ошибку
               result = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red);  //break;
            case OP_SELLSTOP  : // Если выбран отложенный SellStop, то пытаемся его закрыть как позицию, что вызовет ошибку
               result = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red);   //break;
               // Независимо от типа выбранного ордера (отложенный или позиция) удаляем его как отложенный, что для позиции вызовет ошибку
               result = OrderDelete(OrderTicket());  //break;
           }
        }
     } // лишняя скобка
  }
//+------------------------------------------------------------------+

As a result, your code does this, i.e., is equivalent to this code:

//+------------------------------------------------------------------+
if(OrderMagicNumber()==Mn)  // а ордер где-то был выбран ранее?
  {
   bool result=false;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i, SELECT_BY_POS)) {}
      result = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, clrRed);
      result = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, clrRed);
      result = OrderDelete(OrderTicket());
     }
  }
//+------------------------------------------------------------------+

Now ask - what did you want to get out of it?

 
Artyom Trishkin:

To understand what you messed up there, I had to copy the code into the editor and do a proper styling (Ctrl+<).

So: commented in the code what you messed up there:

As a result, your code does this, i.e., equals this code:

Now ask - what did you want to get out of it?

OK.

if(OrderMagicNumber()==Mn)  // а ордер где-то был выбран ранее?

here:

extern int mn;//магический номер открытой позиции
int Mn=10*mn; //магический номер отложенного ордера
int TimFr1=72,TimFr2=24,TimFr3=24;

int start()
 {if(Symbol()=="EURUSD")mn=1;if(Symbol()=="GBPUSD")mn=2;if(Symbol()=="USDCHF")mn=3;if(Symbol()=="USDJPY")mn=4;
  if(Symbol()=="USDCAD")mn=5;if(Symbol()=="EURGBP")mn=6;if(Symbol()=="AUDUSD")mn=7;if(Symbol()=="NZDUSD")mn=8;
  if(Symbol()=="EURJPY")mn=9;if(Symbol()=="EURCHF")mn=10;

When a position is opened (OP_BUY or OP_SELL ), we simultaneously place pending orders (OP_SELLSTOP and OP_BUYSTOP), respectively.

When closing an open position at take profit, the pending order corresponding to it must be cancelled. This algorithm is applied to all currency pairs.

Other pending orders placed on other currencies should remain.

 

Good day to you all!

There is an indicator MTF_RSI is switching

input ENUM_TIMEFRAMES      TimeFrame   =  0;

Can you tell me if it is possible to set automatic change of TimeFrame when switching chart?

Something like

if(TimeFrame=Period())
   TimeFrame="Следующий период";        
 
MakarFX:

Good day to you all!

There is an indicator MTF_RSI is switching

Can you tell me if it is possible to set automatic change of TimeFrame when switching chart?

Something like this

Create a structure or a multidimensional array and let it run on the desired dimension, if the criterion is fulfilled, work with one column (each column is responsible for its own timeframe), if not with another column, and that's all. The program itself has access to all timeframes at once, so what you write is possible, but the implementation is very extensive and you can't see this amount of work on the forum, because it's very extensive.

 
Seric29:

Create a structure or multidimensional array

Thank you.

 

Why doesn't this code work?

typedef double(*CenBr)(string,int,int);CenBr cn_br[4];//глобально
//В Ините пытюсь сохранить указатель на функцию iOpen и ничего не выходит
cn_br[0]=iOpen;

It works with simple functions, but there's something weird about it.

 
MakarFX:

Thank you.

создаём массив double BarOCLH[1000][2][4]
далее сохраняем цену открытия 0 вого бара дневного таймфрейма
BarOCLH[0,0,0]=iOpen ();
далее сохраняем цену открытия 0 вого бара часового таймфрейма
BarOCLH[0,1,0]=iOpen ();и т.д ну а дальше критерируйте с каким столбцом работать
 
Seric29:
Are you talking to me?
 
MakarFX:
Are you talking to me?

Yes to you. You will have to work through the game with timeframes on every detail in every loop and in every function. This is why I recommend using multidimensional arrays.

 
Seric29:

Yes to you. You will have to work through the game with timeframes on every detail in every loop and in every function. This is why I recommend using multidimensional arrays.

This issue is solved more easily:

   switch(period)
     {
      case PERIOD_M1  : TimeFrame = PERIOD_M5;  break;
      case PERIOD_M5  : TimeFrame = PERIOD_M15; break;
      case PERIOD_M15 : TimeFrame = PERIOD_M30; break;
      case PERIOD_M30 : TimeFrame = PERIOD_H1;  break;
      case PERIOD_H1  : TimeFrame = PERIOD_H4;  break;
      case PERIOD_H4  : TimeFrame = PERIOD_D1;  break;
      case PERIOD_D1  : TimeFrame = PERIOD_W1;  break;
      case PERIOD_W1  : TimeFrame = PERIOD_MN1; break;
      case PERIOD_MN1 : TimeFrame = PERIOD_MN1; break;
      default :        return(INIT_FAILED);
     }
Reason: