Useful features from KimIV - page 111

 
Lisi4ka330:
Please tell me why there are pluses in return(StrToTime(ye+"."+mo+".01").
The pluses in this context replace theStringConcatenate() function.
 
Thank you.... big)))))
 

ProfitIFStopInCurrency() function

I needed a function for my info panel the other day that would return the estimated profit/loss in the currency of the deposit when a group of positions triggered their stops. Well, it's not the first time I've written such a function. I have tested it long and hard in different brokerage companies and on different instruments with different ways of profit calculation. If you do not know, there are three of them: Forex, CFD and Futures. But I cannot find the difference between Forex and Futures, but I still have included the possibility of different calculation into the code. The maximum loss that can be returned by the function is artificially limited by the current account balance. Traditionally, you can pass parameters to the function and thus filter out positions you need for the analysis:

  • sy - Name of instrument. If you set this parameter, the function will check positions of the specified instrument only. NULL means the current instrument, and "" (by default) means any instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier (MagicNumber). Default value -1 means any MagicNumber.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 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;                // Подсчёт стопа в валюте депозита

  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();
            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();
              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);
}

HH. Attachment here is the script for testing the ProfitIFStopInCurrency() function.

 

ProfitIFTakeInCurrency() function

This function is similar to the previous one, only it returns the estimated profit/loss in the currency of the deposit when a group of positions triggered their take. The profit calculation method is also taken into account: Forex, CFD and Futures .The maximum profit that the function can return is artificially limited by the number 999,999,999. Parameters:

  • sy - Name of instrument. If you specify this parameter, the function will only check positions of the specified instrument. NULL means the current instrument, and "" (default) means any instrument.
  • op - Trade operation, position type. Valid values: OP_BUY, OP_SELL or -1. The default value -1 means any position.
  • mn - Position identifier (MagicNumber). Default value -1 means any MagicNumber.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 03.05.2012                                                     |
//|  Описание : Возвращает предполагаемую прибыль/убыток в валюте депозита     |
//|             в случае срабатывания тейка открытых позиций.                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
double ProfitIFTakeInCurrency(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;                // Подсчёт стопа в валюте депозита

  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 (OrderTakeProfit()>0) {
              if (m==0) s+=(OrderTakeProfit()-OrderOpenPrice())/p*v*OrderLots();
              if (m==1) s+=(OrderTakeProfit()-OrderOpenPrice())/p*v/t/l*OrderLots();
              if (m==2) s+=(OrderTakeProfit()-OrderOpenPrice())/p*v*OrderLots();
              s+=OrderCommission()+OrderSwap();
            } else s=999999999;
          }
          if (OrderType()==OP_SELL) {
            if (m==0) s+=(OrderOpenPrice()-OrderTakeProfit())/p*v*OrderLots();
            if (m==1) s+=(OrderOpenPrice()-OrderTakeProfit())/p*v/t/l*OrderLots();
            if (m==2) s+=(OrderOpenPrice()-OrderTakeProfit())/p*v*OrderLots();
            s+=OrderCommission()+OrderSwap();
          }
        }
      }
    }
  }
  return(s);
}

HH. I have attached a script to test the ProfitIFTakeInCurrency() function.

 
A list of all my features with brief descriptions and links to the publication posts.
Files:
 
Hi! Don't you have some kind of template (for beginners) to make it easier to write an EA for the tester and for real trading. Something's not moving((((
 
Chuma:
Hi! Don't you have some kind of template (for beginners) to make it easier to write an EA for the tester and for real trading. Something's not moving((((
Template? :)) Well, take any of my EAs as a starting point...
 
KimIV:
Template? :)) So take any of my EAs as a starting point...

Thanks.... interesting and useful things in general.... but for now i'm planning to create a trading advisor that would open and close positions based on the simplest signals (crossing averages for example) for starters, but all these checks, determining the lot etc. .... what, when and how... a bit complicated....

 
so the thought of a template also crossed my mind.... I support "fellow inexperienced" ))))))
 

Igor, I apologise for my frequent questions, and I really hope this is not too difficult for you..... Could you please tell me what is meant by

gbDisabled

in the OpenPosition() function for online

here is a part of the code:

// Блокировка работы советника
      if (err==2 || err==64 || err==65 || err==133) {
        gbDisabled=True; break;
      }
      // Длительная пауза

When compiling it gives an error that the variable is not defined.