Useful features from KimIV - page 14

 
KimIV:

But it allows to stop the Expert Advisor by pressing the "Expert Advisors" button on the toolbar.

I think it will do, thank you. There are not too many parameters to leave the EA, it won't be hard

 

An example of using the ClosePosBySizeProfitInCurrency() function

Especially to demonstrate the ClosePosBySizeProfitInCurrency() function, I have written an Expert Advisor
e-CloseByProfitPosInCurrency, which closes only those positions where the profit in the deposit currency exceeds a certain specified value. The Expert Advisor can be installed on only one chart or on several ones. You can specify a list of positions to be closed using external parameters of the Expert Advisor:

  • symbol="0" - Trade instrument. The following values are allowed: "0" - any trading instrument, "" - only the current instrument and any value from the market overview (EURUSD, GBPUSD, etc.).
  • Operation=-1- Trade operation. Valid values: -1 - any trade, 0 - OP_BUY, 1 - OP_SELL.
  • Profit=50- Profit in the currency of the deposit.
  • MagicNumber=0- Identifier of the position.
 

Good afternoon to all.

Do you, Igor, have a function that closes lossy positions in a similar way to ClosePosBySizeProfitInCurrency() when a specified loss is reached. (Or, perhaps, a combined one, where one can specify closing on profit and on loss).

As I understand it, we can simply set in parameters pr for OrderProfit() - with minus sign and we will get what we are looking for.

Is it possible to set the threshold in points (not in deposit currency) ? If yes, then how ? (TakeProfit and StopLoss are not suggested)

 
rid писал (а):
Do you, Igor, have a function that closes lossy positions in a similar way to ClosePosBySizeProfitInCurrency() when a specified loss is reached. (Or perhaps a combined one, where you can specify closing on profit and on loss.)

No, I don't have such a function yet. However, you can re-do ClosePosBySizeProfitInCurrency():


//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 25.04.2008                                                     |
//|  Описание : Закрытие тех позиций, у которых убыток в валюте депозита       |
//|             превысил некоторое значение                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pr - профит/убыток                                                      |
//+----------------------------------------------------------------------------+
void ClosePosBySizeLossInCurrency(string sy="", int op=-1, int mn=-1, double pr=0) {
  int i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (OrderProfit()+OrderSwap()<-MathAbs(pr)) ClosePosBySelect();
          }
        }
      }
    }
  }
}

I made it so that loss can be passed as a positive (loss) and negative (profit with a minus sign) number.

rid wrote:
As I understand it, we can just set in parameters pr for OrderProfit() - with minus sign and we will get what we are looking for.

Is it possible to set the threshold in points (and not in the deposit currency) ? If yes, how ? (Take Profit and Stop Loss are not an option)

Look at the code of e-CloseByProfit.

 
Thank you.
 

The ClosePositions() function.

This function closes positions whose parameters meet the specified values:

  • sy - Name of instrument. If you set this parameter, the function will only check positions of the specified instrument. 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 - any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие позиций по рыночной цене                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePositions(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) ClosePosBySelect();
        }
      }
    }
  }
}
 
Please help!!! I have been puzzling over a seemingly simple task for 4 days now. I have to prescribe, if CCI has become higher than 100, then open Buy position until the value is lower than -100, and when it is lower than -100, then open Sell position until it is higher than 100.
 

The ClosePosFirstProfit() function.

This function closes positions in a certain order, i.e. profitable positions first, followed by all other positions. A more accurate selection of positions to be closed is defined by external parameters:

  • sy - Name of instrument. If this parameter is set, the function will only check positions of the specified instrument. NULL means the current instrument, while "" (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 - any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие позиций по рыночной цене сначала прибыльных           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePosFirstProfit(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal();
  if (sy=="0") sy=Symbol();

  // Сначала закрываем прибыльные позиции
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (OrderProfit()+OrderSwap()>0) ClosePosBySelect();
          }
        }
      }
    }
  }
  // Потом все остальные
  k=OrdersTotal();
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) ClosePosBySelect();
        }
      }
    }
  }
}
 

The ClosePosWithMaxProfitInCurrency() function.

This function closes one position with the maximum positive profit in the deposit currency. That is, out of five positions, each of which has a profit of -34, 15, 73, -90, 41, the position with a profit of 73 units in the deposit currency will be closed. A more accurate selection of positions to be closed is specified using external parameters:

  • sy - Instrument name. If we set this parameter, the function will only check positions of the specified instrument. NULL means the current instrument, while "" (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 - any MagicNumber.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие одной позиции с максимальным положительным профитом   |
//|             в валюте депозита                                              |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePosWithMaxProfitInCurrency(string sy="", int op=-1, int mn=-1) {
  double pr=0;
  int    i, k=OrdersTotal(), np=-1;

  if (sy=="0") sy=Symbol();
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (mn<0 || OrderMagicNumber()==mn) {
          if (pr<OrderProfit()+OrderSwap()) {
            pr=OrderProfit()+OrderSwap();
            np=i;
          }
        }
      }
    }
  }
  if (np>=0) {
    if (OrderSelect(np, SELECT_BY_POS, MODE_TRADES)) {
      ClosePosBySelect();
    }
  }
}
 
B_Dima:
If the CCI value is above 100, then open a buy position until the value is below -100 and when it is below -100, then open a sell position until it is above 100.

For you, Dima, I can suggest this function:

int CCI_period=14;
int Applied_Price=PRICE_CLOSE;

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.24.2008                                                     |
//|  Описание : Возвращает торговый сигнал:                                    |
//|              1 - покупай                                                   |
//|              0 - сиди, кури бамбук                                         |
//|             -1 - продавай                                                  |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//|    tf - таймфрейм                  (    0       - текущий таймфрейм)       |
//|    nb - номер бара                 (    0       - текущий номер бара)      |
//+----------------------------------------------------------------------------+
int GetTradeSignal(string sy="", int tf=0, int nb=0) {
  if (sy=="" || sy=="0") sy=Symbol();
  double cci0=iCCI(sy, tf, CCI_period, Applied_Price, nb);
  double cci1=iCCI(sy, tf, CCI_period, Applied_Price, nb+1);
  int bs=0;

  if (cci1<=+100 && cci0>+100) bs=+1;
  if (cci1>=-100 && cci0<-100) bs=-1;

  return(bs);
}

This function returns 1 when to buy and -1 when to sell. The buy/sell conditions are as you want them to be. All you need to do now is for each tick to do the following:

1. Get the value of GetTradeSignal().

2. If the received value =0, then do nothing.

If the received value >0, then close all sales and buy.

4. If the obtained value is <0, then close all purchases and sell.