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

 

Is this correct?

for(int i=1; i<=OrdersTotal(); i++) // Order loop

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // if the following

{

int OT=OrdersTotal; //the number of open orders in the terminal

double Price=OrderOpenPrice(); // Price of the selected order

double Mas [Price][OT]; //array for putting in order all the orders

or

for(int i=1; i<=OrdersTotal(); i++) //order loop

{

if (OrderSelect(i-1,SELECT_BY_POS)==true) // if there is a

{

double Price=OrderOpenPrice(); // Price of the selected order

double Mas [Price]; //array to arrange all orders by price?

 
vikzip:

Is this correct?

for(int i=1; i<=OrdersTotal(); i++) // Order loop

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // if the following

{

int OT=OrdersTotal; //the number of open orders in the terminal

double Price=OrderOpenPrice(); // Price of the selected order

double Mas [Price][OT]; //array for putting in order all the orders

or

for(int i=1; i<=OrdersTotal(); i++) //order loop

{

if (OrderSelect(i-1,SELECT_BY_POS)==true) // if there is a

{

double Price=OrderOpenPrice(); // Price of the selected order

double Mas [Price]; //array to arrange all orders by price?

1. OrdersTotal returns the total number of orders, but they are numbered starting from zero. That's why the loop must be i < OrdersTotal()

2. The array must be declared double Mas[];. If the order is successfully selected, the array size should be increased, because we don't know how many orders there are in total.

3. The array string index must be in square brackets. Mas[i] = Price;

As a result, both of them are wrong.

 
Alexey Viktorov:

1. OrdersTotal returns the total number of orders but they are numbered starting from zero. That's why the loop should be i < OrdersTotal()

2. The array must be declared double Mas[];. If an order is chosen successfully, the array size should be increased, because we don't know how many of them there are...

3. The array string index must be in square brackets. Mas[i] = Price;

As a result, both of them are wrong.


Thank you very much!

 
Alexey Viktorov:

1. OrdersTotal returns the total number of orders, but they are numbered starting from zero. Therefore, the loop must be i < OrdersTotal()

2. The array must be declared double Mas[];. If an order is chosen successfully, the array size should be increased, because we don't know how many of them there are...

3. The array string index must be in square brackets. Mas[i] = Price;

As a result, both of them are wrong.


Will we get a one-dimensional array of order prices in this case?

double Price=OrderOpenPrice(); // Price of the selected order

double Mas[i] = Price; //array for putting in order all the orders

for(int i=1; i<OrdersTotal();) // Order loop

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // if there is a next

i++;

}

 
vikzip:

And in this case, it will be a one-dimensional array of order prices?

double Price=OrderOpenPrice(); // Price of the selected order

double Mas[i] = Price; //array for putting in order all the orders

for(int i=1; i<OrdersTotal();) // Order loop

{

if(OrderSelect(i-1,SELECT_BY_POS)==true) // if there is a next

i++;

}

No. It's more or less like this.
  double Price;               // Цена выбранного ордера
  double Mas[];                      //массив для упорядочивания всех ордеров
  for(int i=0; i<OrdersTotal(); i++;)          // Цикл перебора ордер
   {
    if(OrderSelect(i,SELECT_BY_POS)==true) // Если есть следующий
     {
      ArrayResize(Mas, ArraySyze()+1);
      Mas[i] = OrderOpenPrice();
// или 
//    Price=OrderOpenPrice();
//    Mas[i] = Price;
     }
   }

Selected ==true may not be written.

 
Alexey Viktorov:
No. It's more or less like this.

The highlighted ==true may not be written.


Thank you very much!

 
Afternoon, there is a line to select the profit in currency. I want 1) to choose in the EA settings either a fixed profit ( as it already is) or a part of the deposit as a percentage. Please advise how to do this.
The original string is this:

Extern double profit =10;

2) make the autocount of the profit be enabled, disabled by the selected digit of the account balance.

Bottom line:
Profit: fix/autocount.
Fix - amount.
Autorate - percentage of balance.
Turn on autorun - profit %.
Deactivate autorun - profit/loss in %.
Select the value from which the profit/loss of autoaccount will be counted
 

Hi. Can you tell me how to get rid of the closing and opening of a pending order on each bar? I need it to open and wait for the corresponding order to open.

//+------------------------------------------------------------------+
//|                                                e-News-Lucky$.mq4 |
//|                                                   Lucky$ & KimIV |
//|                                              http://www.kimiv.ru |
//|                                                                  |
//|   24.10.2005                                                     |
//| Выставление ордеров в определённое время на пробой диапазона.    |
//| Если ни один ордер не сработал, то модификация на каждом баре.   |
//+------------------------------------------------------------------+
#property copyright "Lucky$ & KimIV"
#property link      "http://www.kimiv.ru"
#define    MAGIC     123

//------- Внешние параметры советника --------------------------------
extern string _Parameters_Trade = "----- Параметры торговли";
extern double Lots           = 0.01;     // Размер торгуемого лота
extern int    StopLoss       = 0;      // Размер фиксированного стопа
extern int    TakeProfit     = 0;       // Размер фиксированного тэйка
extern string TimeSetOrders  = "10:30"; // Время установки ордеров
extern string TimeDelOrders  = "22:30"; // Время удаления ордеров
extern string TimeClosePos   = "22:30"; // Время закрытия позиций
extern int    DistanceSet    = 200;      // Расстояние от рынка
extern bool   UseTrailing    = True;    // Использовать трал
extern bool   ProfitTrailing = True;    // Тралить только профит
extern int    TrailingStop   = 25;      // Фиксированный размер трала
extern int    TrailingStep   = 5;       // Шаг трала
extern int    Slippage       = 3;       // Проскальзывание цены

extern string _Parameters_Expert = "----- Параметры советника";
extern string Name_Expert   = "e-News-Lucky$";
extern bool   UseSound      = True;         // Использовать звуковой сигнал
extern string NameFileSound = "expert.wav"; // Наименование звукового файла
extern color  clOpenBuy     = LightBlue;    // Цвет открытия покупки
extern color  clOpenSell    = LightCoral;   // Цвет открытия продажи
extern color  clModifyBuy   = Aqua;         // Цвет модификации покупки
extern color  clModifySell  = Tomato;       // Цвет модификации продажи
extern color  clCloseBuy    = Blue;         // Цвет закрытия покупки
extern color  clCloseSell   = Red;          // Цвет закрытия продажи

//---- Глобальные переменные советника -------------------------------
int prevBar;

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
void deinit() {
  Comment("");
}

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
void start() {
  if (TimeToStr(CurTime(), TIME_MINUTES)==TimeSetOrders) SetOrders();
  if (prevBar!=Bars && ExistOrder(1) && ExistOrder(2)) ModifyOrders();
  DeleteOppositeOrders();
  TrailingPositions();
  if (TimeToStr(CurTime(), TIME_DATE)==TimeDelOrders) DeleteAllOrders();
  if (TimeToStr(CurTime(), TIME_MINUTES)==TimeClosePos) CloseAllPositions();
  prevBar=Bars;
}

//+------------------------------------------------------------------+
//| Установка ордеров                                                |
//+------------------------------------------------------------------+
void SetOrders() {
  double ldStop=0, ldTake=0;
  int    spr=MarketInfo(Symbol(), MODE_SPREAD);
  double pAsk=Ask+(DistanceSet+spr)*Point;
  double pBid=Bid-DistanceSet*Point;

  if (!ExistOrder(1)) {
    if (StopLoss!=0) ldStop=pAsk-StopLoss*Point;
    if (TakeProfit!=0) ldTake=pAsk+TakeProfit*Point;
    SetOrder(OP_BUYSTOP, pAsk, ldStop, ldTake, 1);
  }
  if (!ExistOrder(2)) {
    if (StopLoss!=0) ldStop=pBid+StopLoss*Point;
    if (TakeProfit!=0) ldTake=pBid-TakeProfit*Point;
    SetOrder(OP_SELLSTOP, pBid, ldStop, ldTake, 2);
  }
}

//+------------------------------------------------------------------+
//| Модификация ордеров                                              |
//+------------------------------------------------------------------+
void ModifyOrders() {
bool ret;
  double ldStop=0, ldTake=0;
  int    spr=MarketInfo(Symbol(), MODE_SPREAD);
  double pAsk=Ask+(DistanceSet+spr)*Point;
  double pBid=Bid-DistanceSet*Point;

  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+1) {
        if (StopLoss!=0) ldStop=pAsk-StopLoss*Point;
        if (TakeProfit!=0) ldTake=pAsk+TakeProfit*Point;
        ret=OrderModify(OrderTicket(), pAsk, ldStop, ldTake, 0, clModifyBuy);
      }
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+2) {
        if (StopLoss!=0) ldStop=pBid+StopLoss*Point;
        if (TakeProfit!=0) ldTake=pBid-TakeProfit*Point;
        ret=OrderModify(OrderTicket(), pBid, ldStop, ldTake, 0, clModifySell);
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Возвращает флаг существования ордера или позиции по номеру       |
//+------------------------------------------------------------------+
bool ExistOrder(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn) {
        Exist=True; break;
      }
    }
  }
  return(Exist);
}

//+------------------------------------------------------------------+
//| Возвращает флаг существования позиции по номеру                  |
//+------------------------------------------------------------------+
bool ExistPosition(int mn) {
  bool Exist=False;
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          Exist=True; break;
        }
      }
    }
  }
  return(Exist);
}

//+------------------------------------------------------------------+
//| Установка ордера                                                 |
//| Параметры:                                                       |
//|   op     - операция                                              |
//|   pp     - цена                                                  |
//|   ldStop - уровень стоп                                          |
//|   ldTake - уровень тейк                                          |
//|   mn     - добавить к MAGIC                                      |
//+------------------------------------------------------------------+
void SetOrder(int op, double pp, double ldStop, double ldTake, int mn) {
  bool ret;
  color  clOpen;
  string lsComm=GetCommentForOrder();

  if (op==OP_BUYSTOP) clOpen=clOpenBuy;
  else clOpen=clOpenSell;
  ret=OrderSend(Symbol(),op,Lots,pp,Slippage,ldStop,ldTake,lsComm,MAGIC+mn,0,clOpen);
  if (UseSound) PlaySound(NameFileSound);
}

//+------------------------------------------------------------------+
//| Генерирует и возвращает строку коментария для ордера или позиции |
//+------------------------------------------------------------------+
string GetCommentForOrder() {
  return(Name_Expert);
}

//+------------------------------------------------------------------+
//| Удаление всех ордеров                                            |
//+------------------------------------------------------------------+
void DeleteAllOrders() {
  bool fd;
  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) {
            fd=OrderDelete(OrderTicket());
            if (fd && UseSound) PlaySound(NameFileSound);
          }
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Закрытие всех позиций по рыночной цене                           |
//+------------------------------------------------------------------+
void CloseAllPositions() {
  bool fc;
  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          fc=False;
          if (OrderType()==OP_BUY) {
            fc=OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clCloseBuy);
          }
          if (OrderType()==OP_SELL) {
            fc=OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clCloseSell);
          }
          if (fc && UseSound) PlaySound(NameFileSound);
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Удаление противоположных ордеров                                 |
//+------------------------------------------------------------------+
void DeleteOppositeOrders() {
  bool fd, fep1, fep2;

  fep1=ExistPosition(1);
  fep2=ExistPosition(2);

  for (int i=OrdersTotal()-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==Symbol()) {
        fd=False;
        if (OrderType()==OP_BUYSTOP && OrderMagicNumber()==MAGIC+1) {
          if (fep2) fd=OrderDelete(OrderTicket());
        }
        if (OrderType()==OP_SELLSTOP && OrderMagicNumber()==MAGIC+2) {
          if (fep1) fd=OrderDelete(OrderTicket());
        }
        if (fd && UseSound) PlaySound(NameFileSound);
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Сопровождение позиции простым тралом                             |
//+------------------------------------------------------------------+
void TrailingPositions() {
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2) {
        if (OrderSymbol()==Symbol()) {
          if (OrderType()==OP_BUY) {
            if (!ProfitTrailing || (Bid-OrderOpenPrice())>TrailingStop*Point) {
              if (OrderStopLoss()<Bid-(TrailingStop+TrailingStep-1)*Point) {
                ModifyStopLoss(Bid-TrailingStop*Point, clModifyBuy);
              }
            }
          }
          if (OrderType()==OP_SELL) {
            if (!ProfitTrailing || OrderOpenPrice()-Ask>TrailingStop*Point) {
              if (OrderStopLoss()>Ask+(TrailingStop+TrailingStep-1)*Point || OrderStopLoss()==0) {
                ModifyStopLoss(Ask+TrailingStop*Point, clModifySell);
              }
            }
          }
        }
      }
    }
  }
}

//+------------------------------------------------------------------+
//| Перенос уровня StopLoss                                          |
//| Параметры:                                                       |
//|   ldStopLoss - уровень StopLoss                                  |
//|   clModify   - цвет модификации                                  |
//+------------------------------------------------------------------+
void ModifyStopLoss(double ldStop, color clModify) {
  bool   fm;
  double ldOpen=OrderOpenPrice();
  double ldTake=OrderTakeProfit();

  fm=OrderModify(OrderTicket(), ldOpen, ldStop, ldTake, 0, clModify);
  if (fm && UseSound) PlaySound(NameFileSound);
}
//+------------------------------------------------------------------+

 

Hello. Does anyone here use indicators from ClasterDelta in their work? I have a question about the automatic use of data from the VolumeProfile indicator. The thing is that this indicator does not return anything but only draws a histogram of trend lines. But when putting the cursor over this line, the value of volume traded on this tick will appear. How to get this information out of the indicator!

Any thoughts?

 

As I have encountered before studying the classes, again there are nuances that are not described in the articles or somewhere so hidden that it is not possible to find through a search engine. A whole day spent in vain looking for explanations. For example what this symbol means and how it affects if not. As seen below in the example of stati, first it is there and then it is not: &

   // Для int. Проверка существования в массиве элемента с заданным значением
   int Find(int & aArray[],int aValue)
     {
      for(int i=0; i<ArraySize(aArray); i++) 
        {
         if(aArray[i]==aValue) 
           {
            return(i); // Элемент существует, возвращаем индекс элемента
           }
        }
      return(-1); // Нет такого элемента, возвращаем -1
     }

Also this symbol is not clear what it means: ~

   // Конструктор
                     CName() { Alert("Конструктор"); }
   // Деструктор
                    ~ CName() { Alert("Деструктор"); }

*

CInfo * returnInfo()
  {
   CInfo * i = new CInfo();
   i.symbol=_Symbol;

   return i;
  }