Useful features from KimIV - page 118

 
borilunad:
This and that, lots of unnecessary calls to other functions with resulting errors!

Well, you've already made mistakes...

It's simple and straightforward: you can edit it to suit your needs.

 
KimIV:


Can you draw something similar to this one...

update...

Attached is a script to test the ExistOPNearPrice() function

Made it, don't know if it's correct.

//+----------------------------------------------------------------------------+
//|  Описание : Возвращает флаг существования позиции или ордера в заданном    | 
//|           : диапазоне от заданной цены                                     |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента        ("" или NULL - текущий символ)     |
//|    op - торговая операция               (    -1      - любая операция)     |
//|    mn - MagicNumber                     (    -1      - любой магик)        |
//|    price - заданная цена                (    -1 - текущая цена рынка       |  
//|    ds - расстояние в пунктах от цены    (  1000000   - по умолчанию)       |
//+----------------------------------------------------------------------------+
bool ExistOPNearMarkets(string sy="", int op=-1, int mn=-1, double price = -1, int ds=1000000) {
  int i, k=OrdersTotal(), ot;

  if (sy=="" || sy=="0") sy=Symbol();
  double p=MarketInfo(sy, MODE_POINT);
  if (p==0) if (StringFind(sy, "JPY")<0) p=0.00001; else p=0.001;
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (OrderSymbol()==sy) {
        if (mn<0 || OrderMagicNumber()==mn) {
          if (op==OP_BUY && (ot==OP_BUY || ot==OP_BUYLIMIT || ot==OP_BUYSTOP)) {
            if ((price<0 && MathAbs(MarketInfo(sy, MODE_ASK)-OrderOpenPrice())<ds*p) ||
                (price>0 && MathAbs(price-OrderOpenPrice())<ds*p)) 
               {
                return(True);
               }
          }
          if (op==OP_SELL && (ot==OP_SELL || ot==OP_SELLLIMIT || ot==OP_SELLSTOP)) {
            if ((price<0 && MathAbs(OrderOpenPrice()-MarketInfo(sy, MODE_BID))<ds*p) ||
                (price>0 && MathAbs(OrderOpenPrice()-price)<ds*p)) 
               {
                return(True);
               }
          }
        }
      }
    }
  }
  return(False);
}
 
artmedia70:

Well, you've already made mistakes...

It's simple and straightforward: adjust as you like.

Thank you. Yes, I've already made do with other tricks.
 
khorosh:

Did it, I don't know if it's right.

It seems to be right... It's universal )))
 

CorrectingPrice().


In one of my EAs I once needed to drastically reduce the number of 130 "Invalid Stops" errors. My arguments that one should not use small stops and takes, that there is a limit of their minimum value which is set by the trade server's setting called STOPLEVEL, did not convince the customer. After all, he said, we could somehow process this error before sending a trade request to the server. I parried that if there was no error, how could it be handled. But a thought got into my brain and it started working and gave birth to this function.

Function CorrectingPrice() is intended for correcting the main price levels of orders and positions to meet the STOPLEVEL requirement before sending a trade request to the server, i.e. before preparing the initial data.

All parameters of this function are mandatory, there are no default values. Besides, the last three parameters are passed by reference, i.e. they will contain the result of the function's work. The function accepts the following parameters:
  • sy - Name of a trade instrument. Empty value "" or NULL will indicate the current trade instrument (symbol).
  • op - Trade operation. The following values are allowed: OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP and OP_SELLSTOP.
  • pp - Open/setting price of the position/order.
  • sl - StopLoss price level.
  • tp - TakeProfit price level.
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 02.07.2013                                                     |
//|  Описание : Выполняет корректирование ценовых уровней под STOPLEVEL.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование торгового инструмента                                 |
//|    op - торговая операция                                                  |
//|    pp - цена открытия/установки                                            |
//|    sl - ценовой уровень StopLoss                                           |
//|    tp - ценовой уровень TakeProfit                                         |
//+----------------------------------------------------------------------------+
void CorrectingPrice(string sy, int op, double& pp, double& sl, double& tp) {
  if (sy=="" || sy=="0") sy=Symbol();
  RefreshRates();
  int    di=MarketInfo(sy, MODE_DIGITS);
  int   msl=MarketInfo(sy, MODE_STOPLEVEL);
  int    sp=MarketInfo(sy, MODE_SPREAD);
  double mp=MarketInfo(sy, MODE_POINT);
  double pa=MarketInfo(sy, MODE_ASK);
  double pb=MarketInfo(sy, MODE_BID);
  double ds=NormalizeDouble(pp-sl, di);
  double dp=NormalizeDouble(pp-tp, di);

  if (msl==0) msl=2*sp;
  switch (op) {
    case OP_BUY:
      pp=pa;
      sl=pp-ds;
      tp=NormalizeDouble(pp-dp, di);
      if (sl>pp-msl*mp) sl=pp-msl*mp;
      if (tp>0 && tp<pp+msl*mp) tp=pp+msl*mp;
      break;
    case OP_SELL:
      pp=pb;
      sl=NormalizeDouble(pp-ds, di);
      tp=pp-dp;
      if (sl>0 && sl<pp+msl*mp) sl=pp+msl*mp;
      if (tp>pp-msl*mp) tp=pp-msl*mp;
      break;
    case OP_BUYLIMIT:
      if (pp>pa-msl*mp) {
        pp=pa-msl*mp;
        sl=pp-ds;
        tp=NormalizeDouble(pp-dp, di);
      }
      if (sl>pp-msl*mp) sl=pp-msl*mp;
      if (tp>0 && tp<pp+msl*mp) tp=pp+msl*mp;
      break;
    case OP_BUYSTOP:
      if (pp<pa+msl*mp) {
        pp=pa+msl*mp;
        if (sl>0) sl=pp-ds;
        if (tp>0) tp=NormalizeDouble(pp-dp, di);
      }
      if (sl>pp-msl*mp) sl=pp-msl*mp;
      if (tp>0 && tp<pp+msl*mp) tp=pp+msl*mp;
      break;
    case OP_SELLLIMIT:
      if (pp<pb+msl*mp) {
        pp=pb+msl*mp;
        sl=NormalizeDouble(pp-ds, di);
        tp=pp-dp;
      }
      if (sl>0 && sl<pp+msl*mp) sl=pp+msl*mp;
      if (tp>pp-msl*mp) tp=pp-msl*mp;
      break;
    case OP_SELLSTOP:
      if (pp>pb-msl*mp) {
        pp=pb-msl*mp;
        sl=NormalizeDouble(pp-ds, di);
        tp=pp-dp;
      }
      if (sl>0 && sl<pp+msl*mp) sl=pp+msl*mp;
      if (tp>pp-msl*mp) tp=pp-msl*mp;
      break;
    default:
      Message("CorrectingPrice(): Неизвестная торговая операция!");
      break;
  }
}

 
KimIV:

CorrectingPrice().


In one of my EAs I once needed to drastically reduce the number of 130 "Invalid Stops" errors. My arguments that one should not use small stops and take points and that there is a limit on their minimum value set by the trade server's setting called STOPLEVEL did not convince the customer. After all, he said, we could somehow process this error before sending a trade request to the server. I parried, if there's no error, how could it be handled. But a thought got into my brain and it started working and gave birth to this function.

Function CorrectingPrice() is intended for correcting the main price levels of orders and positions to meet the STOPLEVEL requirement before sending a trade request to the server, i.e. before preparing the initial data.

All parameters of this function are mandatory, there are no default values. Besides, the last three parameters are passed by reference, i.e. they will contain the result of the function's work. The function accepts the following parameters:
  • sy - Name of a trade instrument. Empty value "" or NULL will indicate the current trade instrument (symbol).
  • op - Trade operation. The following values are allowed: OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP and OP_SELLSTOP.
  • pp - Open/setting price of the position/order.
  • sl - StopLoss price level.
  • tp - TakeProfit price level.

Igor, some brokerage companies use Spread*2 instead of StopLevel, which has zero value. Briefly reviewing the code, I did not notice the check for this situation. It would be good to correct the code to check this situation, otherwise there will be the same 130 errors
 
artmedia70:
Igor, some brokerage companies use Spread*2 instead of StopLevel that has zero value. After a cursory glance at the code, I did not see any check for this situation. It would be nice to tweak the code to check this situation, otherwise it will be the same 130 errors


Artem, I didn't meet such DC... Can you send me a couple of them in your personal message? I'll read the trade regulations...

Or is there a simpler way to go about it? Can you tell me, is it correct enough to use such correction?

int   msl=MarketInfo(sy, MODE_STOPLEVEL);
int    sp=MarketInfo(sy, MODE_SPREAD);
if (msl==0) msl=2*sp;

UPDATE: I have corrected theCorrectingPrice() function.

 

A new version of the CorrectTF() function.

Some time ago I was criticized for theCorrectTF() function claiming that its functionality does not correspond to its name. In fact, it adjusts the timeframe to the nearest minimum and not just to the nearest one. I have calculated the arithmetic mean values between the standard timeframes and rewritten the function according to its description.

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 21.05.2013                                                     |
//|  Описание : Корректирует таймфрейм под ближайший поддерживаемый МТ4.       |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    TimeFrame - таймфрейм (количество минут).                               |
//+----------------------------------------------------------------------------+
int CorrectTF(int TimeFrame) {
  if (TimeFrame>     1 && TimeFrame<    3) return(PERIOD_M1);
  if (TimeFrame>=    3 && TimeFrame<   10) return(PERIOD_M5);
  if (TimeFrame>=   10 && TimeFrame<   23) return(PERIOD_M15);
  if (TimeFrame>=   23 && TimeFrame<   45) return(PERIOD_M30);
  if (TimeFrame>=   45 && TimeFrame<  150) return(PERIOD_H1);
  if (TimeFrame>=  150 && TimeFrame<  840) return(PERIOD_H4);
  if (TimeFrame>=  840 && TimeFrame< 5760) return(PERIOD_D1);
  if (TimeFrame>= 5760 && TimeFrame<26640) return(PERIOD_W1);
  if (TimeFrame>=26640                   ) return(PERIOD_MN1);
}
 
KimIV:


Artem, I did not meet such DC... Can you send me a couple of them in your personal message? I'll read the trading regulations...

Dropped

Or you could do something simpler. Can you tell me, is it correct enough to use such correction?

int   msl=MarketInfo(sy, MODE_STOPLEVEL);
int    sp=MarketInfo(sy, MODE_SPREAD);
if (msl==0) msl=2*sp;

Of course, everything is correct.

UPDATE: I correctedCorrectingPrice() function.

Igor, I practically do the same in EAs, I always read the data first and assign the required value to the variable level, then I check the calculations with it.
 
KimIV:


Artyom, I haven't come across any DCs like that... Can you send me a couple of them in your personal message? I'll read the trading regulations...

Or you can do it in a simpler way. Tell me yourself, is it correct enough to use such an amendment?

UPDATE: I have made an amendment toCorrectingPrice() function.

Hello, colleagues, I'm still studying the code, I can't understand the subtleties well and am in a bit of a quandary.

As I understand it, we have to call this function to correct the parameters before placing an order.

There is such a line to open an order:

if(buy == true && Open[0]>UpTr && Trade) {

buy=OrderSend(Symbol(),OP_BUYSTOP,LOT(),NormalizeDouble(op,Digits),slippage,NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits), "T",Magic,0,MediumBlue);

is this where it should be addressed? And how to do it correctly. Or this command doesn't needCorrectingPrice()?

Thank you in advance.