Useful features from KimIV - page 15

 
KimIV:
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 to do the following on every tick:

1. Get the value of GetTradeSignal().

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

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

4. If the calculated value is <0, then close all trades and sell.

:)))) of course thanks for the help, but my mistake, I didn't explain accurately enough, the CCI indicator with an interval of 50 shows the direction and trend change and the opening occurs when the price touches the EMA 8 and also uses stop-loss and take-profit and other indicators to determine the correction. The picture is that when the CCI breaks through +100 a buy position is opened at the touch of EMA and it does not matter where the CCI is (+10 or -20), the main thing is that when it crosses -100 a sell position is opened. In the time span between crossing 100 candles and opening 10 or more positions, the CCI>=+100 and CCI<=-100 can go through 100 candles. I hope it is clear. If you have any tips, I will be happy to help.

 
B_Dima писал (а):
my mistake, I didn't explain it accurately enough,

Well... Your mistake is yours to correct :-)

I gave you the right direction. It will lead to the goal. So go ahead...

 
KimIV:

Examples of how to use the ModifyOrder() function.

I decided to give the very first examples that I've been asked many times before. This is opening of positions in terms of market order execution Market Watch. It is when we cannot simultaneously give an order to open a position at the market price and attach a pending order to it. Such an opening at Market Watch should be performed in two stages: first, we open a position, and then we attach a pending order to it, i.e. we set StopLoss and TakeProfit price levels.

1. Buy 0.1 lot of the current symbol and set a stop of 30 points

int ti=OpenPosition(NULL, OP_BUY, 0.1);
if (OrderSelect(ti, SELECT_BY_TICKET))
  ModifyOrder(-1, Ask-30*Point, -1, clModifyBuy);

2. Sell 0.15 lot of the current instrument and set SL=45, TP=99

int ti=OpenPosition(NULL, OP_SELL, 0.15);
if (OrderSelect(ti, SELECT_BY_TICKET))
  ModifyOrder(-1, Bid+45*Point, Bid-99*Point, clModifySell);
A working script with examples is included in the trailer.


Igor, please check again - the script does not work:

1) In normal brokerage companies there is no limit on the number of open orders (opens endlessly)

2) In brokerage companies where orders are opened at market - (Error131). You can test it, for example with NorthFinance.

 

So many useful functions laid out... Maybe there is a desire to write a template for writing a trading EA that can open and close pending orders, positions, set take and stoploss, modify orders and positions, depending on user-defined conditions... Such a template will allow you to quickly write an EA where only the block of conditions changes (of course, this part will be inserted by the user depending on the strategy)...


If there are useful functions from Kim, i.e. a certain standard of versatility in use, then why not lay out the code of a template for a trading EA from Kim...

 
Set777 писал (а):
Igor, please check again - the script does not work:
1) In normal brokerage companies there is no limit on the number of open orders (opens infinitely)
2) In brokerage companies where orders are opened by market - (Error131). You can test it, for example NorthFinance.

1. There is no check on the number of open positions in the script. How many times you run the script, the number of positions it will open.

Error 131 - Incorrect volume, lot size. Probably, it is 0.15. Replace it with 0.2

 
kharko писал (а):
So many useful features laid out...

Not even a fifth of what I have in mind yet... I'll be boring everyone here until the fall. So bear with me...

kharko wrote (a):
Maybe there is a desire to write some template for writing a trading advisor, which can open and close pending orders, positions, set take and stoploss, modify orders and positions, depending on user-defined conditions...
Template... Template... Good idea! Thank you! But first the functions...
 

DistMarketAndPos() function.

Here we go! Here come more interesting functions! For example, it returns the distance in pips between the market and the nearest position. The more accurate selection of positions to be checked is set by external parameters:

  • sy - Name of the instrument. If this parameter is set, the function will only check positions of the specified instrument. The "" or NULL means the current 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      - любой магик)             |
//+----------------------------------------------------------------------------+
int DistMarketAndPos(string sy="", int op=-1, int mn=-1) {
  double d, p;
  int i, k=OrdersTotal(), r=1000000;

  if (sy=="" || sy=="0") sy=Symbol();
  p=MarketInfo(sy, MODE_POINT);
  if (p==0) if (StringFind(sy, "JPY")<0) p=0.0001; else p=0.01;
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy) && (op<0 || OrderType()==op)) {
        if (mn<0 || OrderMagicNumber()==mn) {
          if (OrderType()==OP_BUY) {
            d=MathAbs(MarketInfo(sy, MODE_ASK)-OrderOpenPrice())/p;
            if (r>d) r=NormalizeDouble(d, 0);
          }
          if (OrderType()==OP_SELL) {
            d=MathAbs(OrderOpenPrice()-MarketInfo(sy, MODE_BID))/p;
            if (r>d) r=NormalizeDouble(d, 0);
          }
        }
      }
    }
  }
  return(r);
}
 

Examples of the use of DistMarketAndPos().

Why would one need a function that determines how far the market is from the closest position? I see at least four basic options:

  1. Bought or sold. The market has moved in our direction. And as soon as it passes some distance, existing positions have gained some profit, we immediately make a deposit - enter again in the same direction.
  2. We buy or sell. The market went in our direction. Once it has travelled a certain distance, and the existing positions have earned a certain profit, we immediately realize that that is it! The reversal is near! It's time to flip. We close our current positions and open in the opposite direction.
  3. We buy or sell. The market has turned against us. But for some reason, we are sure that we are right and, at some distance from the nearest entry point, i.e. at some level of loss, we average and open in the same direction.
  4. We buy or sell. The market has gone against us. And we have realized that we entered the market incorrectly. Therefore, we fix on a certain level of loss and open in the other direction.

If I want to place an order with the proper order, it should be done within the frame of the market conditions. I will fulfill all requests within the framework of what I have listed above.

ZZY-ZY. Attached is a "template" script for experimentation with DistMarketAndPos() function.

 
Dear KimIV In the idPriceLevel() function which is part of your Expert Advisor e-TFL_v2 there is an error: in the last condition gdUpPrice==0 is repeated twice. Probably, in the second case you meant to write gdDnPrice==0. For some reason, this EA works in the Strategy Tester in visual mode, but the demo account position does not open, although the comments inform about the buy and sell levels. Maybe you can tell me what's wrong.
 
khorosh:
there is an error in bool idPriceLevel() function included in e-TFL_v2 Expert Advisor: gdUpPrice==0 is repeated twice in the last condition, you probably meant to write gdDnPrice==0 in the second case.

Thank you! I have uploaded the corrected version of e-TFL_v2 to the website.


khorosh:
For some reason this EA works in my Strategy Tester in visual mode but it does not open positions on a demo account, although it reports buy and sell levels in the comments. Maybe you can tell me what is the matter.

I do not know... I have just finished testing this Expert Advisor on a NorthFinance demo. Yesterday my friend from Moscow called me. He complained about the same Expert Advisor. He says that it opens position by the line and then more and more until you stop it and opens many positions. Therefore, there were two objectives for testing:

1. Concerning your question. Check of general functionality.

2. On my friend's question. I opened only one position from one line.

To check it, I put e-TFL_v2 Expert Advisor on 5-minute timeframes EURUSD, GBPUSD, USDCHF and USDJPY. Using trend lines I drew channels on the last 20-30 bars. As a result, the Expert Advisor worked as it should. EUR has been bought from the bottom line, while JPY has been sold from the top one. For pound and chyf everything was correct too. So you should check it on your own. The Expert Advisor works.