Questions from Beginners MQL4 MT4 MetaTrader 4 - page 37

 
ed3sss:

OK, it's the same cycle here, why does it close orders?)

Because it can. But the writing is still illiterate.
 
Vitalie Postolache:
Because it can. But it's still illiterate.
Suggest it properly! If you don't spare your knowledge.
 
ed3sss:
Suggest intelligently! If you don't spare your knowledge.

Here's a slightly more correct version, which still has room for improvement:

        int error=0;
        for(i=OrdersTotal()-1;i>=0;i--)
        {//+----------------------------------------------------------------------------------------+for
         if(!OrderSelect(i,SELECT_BY_POS)) continue;
         if(OrderSymbol()!=Symbol())continue;
         if(OrderType()>1)continue;
         RefreshRates();
         if(!OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3))
          {
           error=_LastError;
           Print("Error #",error);
          }
         if(error==6){Alert("Нет связи");return(0);}
         if(error==132){Alert("Рынок закрыт");return(0);}
        }
 
//+----------------------------------------------------------------------------+
//|                                                   i-TotalStopCurrency.mq4  |
//|  21.12.2011  Indicator of the Total Stop in the Deposit Currency.          |
//|              Индикатор суммарного стопа в валюте депозита.                 |
//|  04.05.2012  Добавил способ расчета прибыли для Futures.                   |
//+----------------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 0

//------- Внешние параметры индикатора ----------------------------------------+
extern string symbol   = "";
extern color  ecText   = Black;    // Цвет текста
extern int    eiCorner = 3;       // Номер угла привязки:
                                  //   0 - левый верхний
                                  //   1 - правый верхний
                                  //   2 - левый нижний
                                  //   3 - правый нижний

//------- Глобальные переменные индикатора ------------------------------------+


//+----------------------------------------------------------------------------+
//|                                                                            |
//|  ПРЕДОПРЕДЕЛЁННЫЕ ФУНКЦИИ                                                  |
//|                                                                            |
//+----------------------------------------------------------------------------+
//|  Custom indicator initialization function                                  |
//+----------------------------------------------------------------------------+
void init() {
  Comment("");
}

//+----------------------------------------------------------------------------+
//|  Custom indicator deinitialization function                                |
//+----------------------------------------------------------------------------+
void deinit() {
  Comment("");
  for (int i=0; i<3; i++) ObjectDelete("iTotalStopCurrency"+i);
}

//+----------------------------------------------------------------------------+
//|  Custom indicator iteration function                                       |
//+----------------------------------------------------------------------------+
void start() {
  double s=ProfitIFStopInCurrency(symbol);
  int pn=ProfitIFStopInCurrency2(symbol);
  
  SetLabel("iTotalStopCurrency0", "Уровень стопа", ecText, 5, 30, eiCorner);
  SetLabel("iTotalStopCurrency1", DoubleToStr(s, 2)+" "+AccountCurrency(), ecText, 5, 5, eiCorner);
  SetLabel("iTotalStopCurrency2", "Спр="+DoubleToStr(MarketInfo(Symbol(),MODE_SPREAD),0)+" Орд="+OrdersTotal()
  +" Приб="  +DoubleToStr(AccountProfit(),2)+" Сред="+DoubleToStr(AccountEquity(),2)+" Бал="+DoubleToStr(AccountBalance(),2)+"  "+pn
  +"пипс "+DoubleToStr(s/AccountBalance()*100, 2)+"%", ecText, 130, 5, eiCorner);
}
//+----------------------------------------------------------------------------+
//|  Версия   : 03.05.2012                                                     |
//|  Описание : Возвращает предполагаемую прибыль/убыток в валюте депозита     |
//|             в случае срабатывания стопа открытых позиций.                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
double ProfitIFStopInCurrency(string sy="", int op=-1, int mn=-1) {
  /*if (sy=="0") */ sy=Symbol();  // Текущий символ
  int    i, k=OrdersTotal(); // Подсчёт открытых позиций
  int    m;                  // Способ расчета прибыли: 0 - Forex, 1 - CFD, 2 - Futures
  double l;                  // Размер контракта в базовой валюте инструмента
  double p;                  // Размер пункта в валюте котировки
  double t;                  // Минимальный шаг изменения цены инструмента в валюте котировки
  double v;                  // Размер минимального изменения цены инструмента в валюте депозита
  double s=0;                // Подсчёт стопа в валюте депозита
  double pn=0;               // Подсчёт стопа в пунктах

  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
        if ((OrderType()==OP_BUY || OrderType()==OP_SELL) && (op<0 || OrderType()==op)) {
          l=MarketInfo(OrderSymbol(), MODE_LOTSIZE);
          m=MarketInfo(OrderSymbol(), MODE_PROFITCALCMODE);
          p=MarketInfo(OrderSymbol(), MODE_POINT);
          t=MarketInfo(OrderSymbol(), MODE_TICKSIZE);
          v=MarketInfo(OrderSymbol(), MODE_TICKVALUE);
          if (OrderType()==OP_BUY) {
            if (m==0) s-=(OrderOpenPrice()-OrderStopLoss())/p*v*OrderLots(); pn-=(OrderOpenPrice()-OrderStopLoss())*MathPow(10,MarketInfo(OrderSymbol(),MODE_DIGITS));
            if (m==1) s-=(OrderOpenPrice()-OrderStopLoss())/p*v/t/l*OrderLots();
            if (m==2) s-=(OrderOpenPrice()-OrderStopLoss())/p*v*OrderLots();
            s+=OrderCommission()+OrderSwap();
          }
          if (OrderType()==OP_SELL) {
            if (OrderStopLoss()>0) {
              if (m==0) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots(); pn-=(OrderStopLoss()-OrderOpenPrice())*MathPow(10,MarketInfo(OrderSymbol(),MODE_DIGITS));
              if (m==1) s-=(OrderStopLoss()-OrderOpenPrice())/p*v/t/l*OrderLots();
              if (m==2) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots();
              s+=OrderCommission()+OrderSwap();
            } else s=-AccountBalance();
          }
        }
      }
    }
  }
  if (AccountBalance()+s<0) s=-AccountBalance(); // Ограничение убытка балансом счёта
  return(s);
}
//+----------------------------------------------------------------------------+
double ProfitIFStopInCurrency2(string sy="", int op=-1, int mn=-1) {
  /*if (sy=="0") */ sy=Symbol();  // Текущий символ
  int    i, k=OrdersTotal(); // Подсчёт открытых позиций
  int    m;                  // Способ расчета прибыли: 0 - Forex, 1 - CFD, 2 - Futures
  double l;                  // Размер контракта в базовой валюте инструмента
  double p;                  // Размер пункта в валюте котировки
  double t;                  // Минимальный шаг изменения цены инструмента в валюте котировки
  double v;                  // Размер минимального изменения цены инструмента в валюте депозита
  double s=0;                // Подсчёт стопа в валюте депозита
  double pn=0;               // Подсчёт стопа в пунктах

  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
        if ((OrderType()==OP_BUY || OrderType()==OP_SELL) && (op<0 || OrderType()==op)) {
          l=MarketInfo(OrderSymbol(), MODE_LOTSIZE);
          m=MarketInfo(OrderSymbol(), MODE_PROFITCALCMODE);
          p=MarketInfo(OrderSymbol(), MODE_POINT);
          t=MarketInfo(OrderSymbol(), MODE_TICKSIZE);
          v=MarketInfo(OrderSymbol(), MODE_TICKVALUE);
          if (OrderType()==OP_BUY) {
            if (m==0) s-=(OrderOpenPrice()-OrderStopLoss())/p*v*OrderLots(); pn-=(OrderOpenPrice()-OrderStopLoss())*MathPow(10,MarketInfo(OrderSymbol(),MODE_DIGITS));
            if (m==1) s-=(OrderOpenPrice()-OrderStopLoss())/p*v/t/l*OrderLots();
            if (m==2) s-=(OrderOpenPrice()-OrderStopLoss())/p*v*OrderLots();
            s+=OrderCommission()+OrderSwap();
          }
          if (OrderType()==OP_SELL) {
            if (OrderStopLoss()>0) {
              if (m==0) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots(); pn-=(OrderStopLoss()-OrderOpenPrice())*MathPow(10,MarketInfo(OrderSymbol(),MODE_DIGITS));
              if (m==1) s-=(OrderStopLoss()-OrderOpenPrice())/p*v/t/l*OrderLots();
              if (m==2) s-=(OrderStopLoss()-OrderOpenPrice())/p*v*OrderLots();
              s+=OrderCommission()+OrderSwap();
            } else s=-AccountBalance();
          }
        }
      }
    }
  }
  if (AccountBalance()+s<0) s=-AccountBalance(); // Ограничение убытка балансом счёта
  return(pn);
}
//+----------------------------------------------------------------------------+
//|  Версия   : 12.10.2007                                                     |
//|  Описание : Установка текстовой метки, объект OBJ_LABEL.                   |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    nm - наименование объекта                                               |
//|    tx - текст                                                              |
//|    cl - цвет метки                                                         |
//|    xd - координата X в пикселах                                            |
//|    yd - координата Y в пикселах                                            |
//|    cr - номер угла привязки        (0 - левый верхний )                    |
//|                                     1 - правый верхний                     |
//|                                     2 - левый нижний                       |
//|                                     3 - правый нижний )                    |
//|    fs - размер шрифта              (9 - по умолчанию  )                    |
//+----------------------------------------------------------------------------+
void SetLabel(string nm, string tx, color cl, int xd, int yd, int cr=0, int fs=14) {
  if (ObjectFind(nm)<0) ObjectCreate(nm, OBJ_LABEL, 0, 0,0);
  ObjectSetText(nm, tx, fs);
  ObjectSet(nm, OBJPROP_COLOR    , cl);
  ObjectSet(nm, OBJPROP_XDISTANCE, xd);
  ObjectSet(nm, OBJPROP_YDISTANCE, yd);
  ObjectSet(nm, OBJPROP_CORNER   , cr);
  ObjectSet(nm, OBJPROP_FONTSIZE , fs);
}
//+----------------------------------------------------------------------------+

Hello !

The given indicator works fine when I put it on a chart

But after restarting the terminal, there is no data, just something instead of data

i can fix it by changing the TF

i tried everything i know - it does not work

I think the setting of the text label is something wrong - help please thanks in advance!

 
Игорь:
void SetLabel(string nm, string tx, color cl, int xd, int yd, int cr=0, int fs=14) {
  if (ObjectFind(nm)<0) ObjectCreate(nm, OBJ_LABEL, 0, 0,0);
  ObjectSetText(nm, tx, fs);
  ObjectSet(nm, OBJPROP_COLOR    , cl);
  ObjectSet(nm, OBJPROP_XDISTANCE, xd);
  ObjectSet(nm, OBJPROP_YDISTANCE, yd);
  ObjectSet(nm, OBJPROP_CORNER   , cr);
  ObjectSet(nm, OBJPROP_FONTSIZE , fs);
}
//+----------------------------------------------------------------------------+

Hello !

The given indicator works fine when I put it on a chart

But after restarting the terminal, there is no data, just something instead of data

i can fix it by changing the TF

i tried everything i know - it does not work

I think the setting of the text label is something wrong - please help me, thank you in advance!

Maybe so?

void SetLabel(string nm, string tx, color cl, int xd, int yd, int cr=0, int fs=14) {
  if (ObjectFind(nm)<0) {
   ObjectCreate(nm, OBJ_LABEL, 0, 0,0);
   ObjectSet(nm, OBJPROP_COLOR    , cl);
   ObjectSet(nm, OBJPROP_XDISTANCE, xd);
   ObjectSet(nm, OBJPROP_YDISTANCE, yd);
   ObjectSet(nm, OBJPROP_CORNER   , cr);
   ObjectSet(nm, OBJPROP_FONTSIZE , fs);
  }
   ObjectSetText(nm, tx, fs);
}
 
Vitaly Muzichenko:

How about this?

void SetLabel(string nm, string tx, color cl, int xd, int yd, int cr=0, int fs=14) {
  if (ObjectFind(nm)<0) {
   ObjectCreate(nm, OBJ_LABEL, 0, 0,0);
   ObjectSet(nm, OBJPROP_COLOR    , cl);
   ObjectSet(nm, OBJPROP_XDISTANCE, xd);
   ObjectSet(nm, OBJPROP_YDISTANCE, yd);
   ObjectSet(nm, OBJPROP_CORNER   , cr);
   ObjectSet(nm, OBJPROP_FONTSIZE , fs);
  }
   ObjectSetText(nm, tx, fs);
}


Thanks for the heads up but the result is the same !

Maybe this will help ! There is no 3rd and 2nd is not right !

After changing the TF it is normal !

Files:
1.jpg  439 kb
 
So help the same with the problem - it still hasn't been solved !
 
Good afternoon. Installed MT4 on my computer. Put it on D drive for a purpose. But it stubbornly creates a data folder on the C drive. The space there is not enough, as usual, so I have to clean the tester's logs several times a day during the testing. Well, it can't be fatal, can it? Can you please advise a dummie how to make MT4 create a "data directory" folder on another drive? I can't find it in Settings.
 
VHS:
Afternoon. Installed MT4 on my computer. Purposely put it on the D drive. But it stubbornly creates a data folder on drive C. The space there is not enough, as usual, so I have to clean the tester's logs when testing several times a day. Well, it can't be fatal, can it? Can you please advise a dummie how to make MT4 create a "data directory" folder on another drive? I can't find it in Settings.

I'm not a pro but I don't think there's anything sim can do !

Just free up the c drive or reinstall the whole thing with the windup and do more !

 
VHS:
Good afternoon. Installed MT4 on my computer. Put it on D drive for a purpose. But it stubbornly creates a data folder on the C drive. The space there is not enough, as usual, so I have to clean the tester's logs several times a day during the testing. Well, it can't be fatal, can it? Can you please advise a dummie how to make MT4 create a "data directory" folder on another drive? I can't find it in Settings.
I also don't know how to use search engine. It has been written about /portable mode innumerable times on this and other forums. The problem is already three years old.
Reason: