Useful features from KimIV - page 114

 

Good afternoon.

I'm still new to programming, if anyone can give me a hint.

Question. We have one or more open orders. We know that they will close at a profit of $20.

We need to know at what price the orders will close at $20 profit.

We calculate the total volume of open lots, and then!

Please, advise how to do it.

Perhaps there is a ready function?

Thanks in advance.

 
KimIV:

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 you want a specific implementation of any of these options, write your requests here. I will fulfill all requests within the framework of what I have listed above.

ZZY-ZY. Attached is a template for experimenting with DistMarketAndPos() function.


HelloKimIV, the function is very good, it works, I flip it, it works too, but I can't connect the two halves.

     int start()

{

      if (DistMarketAndPos()>150)

{                                     

      OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,Ask+150*Point);

   }     

      return(0);

   }

int DistMarketAndPos(string sy="", int op=OP_BUY, 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, "")<0) p=0.00001; 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);

}  


 

Please flip it for me, everyone says it's wrong but it works.
 
Newcomers, ask your questions in the dedicated thread.
 

New version of the Message() function.


The Message() function has undergone two changes since publication here. The first change added the possibility to disable the output to the Expert log by Print() and the possibility to output only the first message in a series of similar ones. The second change added output directions, i.e. in addition to existing Comment() and Print() functions Alert(), SendMail() and SendNotification() were used. It is the latter change that I am publishing.

The Message() function is designed to output the text message in different directions. It can be used both for debugging purposes and in ready-made applications for explaining the current trading situation, for logging the program operation, for timely informing a trader about important changes, etc. The function accepts three parameters, the last two of which are optional:
  • ms - String, text message to be output, transmitted.
  • nv - A string of flags which specify the direction of the message output. Five flags are five significant places. Each flag face with zero turns on and one turns off a particular output direction. From left to right in order are Alert, Comment, Print, SendMail and SendNotification. The default value is "01100", i.e. Comment and Print are enabled, the others are disabled.
  • am - Logical, True - output all messages, False - from a series of identical messages output only the first one. Default value is False.

About Alert and Print output directions (spaces 1 and 3) it should be noted, that they are able to output the message line by line. In other words, if there is a line break in the message text - control character "\n" then each line will be printed independently. Try the test script in the attachment, I think you will like it :-)

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 08.03.2013                                                     |
//|  Описание : Вывод текстового сообщения.                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    ms - текст сообщения                                                    |
//|    nv - флаги направлений вывода сообщения:   (0-выкл, 1-вкл)              |
//|           Alert, Comment, Print, SendMail, SendNotification                |
//|    am - флаг всех повторяющихся сообщений                                  |
//+----------------------------------------------------------------------------+
void Message(string ms, string nv="01100", bool am=False) {
  static string prevMessage="";
  string as[];
  int    i, k;

  if (StrToInteger(StringSubstr(nv, 1, 1))==1) Comment(ms);
  if ((StringLen(ms)>0) && (am || prevMessage!=ms)) {
    if (StrToInteger(StringSubstr(nv, 0, 1))==1) {
      k=StrSplit(ms, as, "\n");
      for (i=0; i<k; i++) Alert(as[i]);
    }
    if (StrToInteger(StringSubstr(nv, 2, 1))==1) {
      k=StrSplit(ms, as, "\n");
      for (i=0; i<k; i++) Print(as[i]);
    }
    if (StrToInteger(StringSubstr(nv, 3, 1))==1) SendMail(WindowExpertName(), ms);
    if (StrToInteger(StringSubstr(nv, 4, 1))==1) SendNotification(ms);
    prevMessage=ms;
  }
}

SZY. Attached is a script to test Message() function.

Files:
 
KimIV:

New version of the Message() function.


The Message() function has undergone two changes since publication here. The first change added the possibility to disable the output to the Expert log by Print() and the possibility to output only the first message in a series of similar ones. The second change added output directions, i.e. in addition to existing Comment() and Print() functions Alert(), SendMail() and SendNotification() were used. It is the latter change that I am publishing.

The Message() function is designed to output the text message in different directions. It can be used both for debugging purposes and in ready-made applications for explaining the current trading situation, for logging the program operation, for timely informing a trader about important changes, etc. The function accepts three parameters, the last two of which are optional:
  • ms - String, text message to be output, transmitted.
  • nv - A string of flags which specify the direction of the message output. Five flags are five significant places. Each flag face with zero turns on and one turns off a particular output direction. From left to right in order are Alert, Comment, Print, SendMail and SendNotification. The default value is "01100", i.e. Comment and Print are enabled, the others are disabled.
  • am - Logical, True - output all messages, False - from a series of identical messages output only the first one. Default value is False.

About Alert and Print output directions (spaces 1 and 3) it should be noted, that they are able to output the message line by line. That is, if there is a line break in the message text - control character "\n", then each line will be printed independently. Try the test script in the attachment, I think you will like it :-)


SZY. Attached is a script to test Message() function.

Have you added a stopplay check to your OpenPosition function?
 
sv.:
Have you added a check for stop levelling to your OpenPosition function?


No... what kind of check are you referring to? Well, let's say the stop and take failed the check, what to do? There are options:

  1. Do not open,
  2. Adjust the stop and takeaway.

 
KimIV:


no... what kind of check are you referring to? Well, let's say the stop and take didn't pass the check, what do you do? There are options:

  1. Do not open,
  2. Adjust stop and take.

You could introduce a custom switch between items 1 and 2. Following the pattern:
 int           modeSetOrders = 1;      // Способ установки ордеров:
                                       //  0 - по заданной цене
                                       //  1 - скорректировать цены
                                       //  2 - вход по текущим ценам
 

New version of theOpenPosition() functionin the test script.

What's new?

1. When the error 130 Invalid Stops and the value of the NumberOfTry>1 variable is set, the function will try to adjust the StopLoss and TakeProfit price levels to the values of MODE_STOPLEVEL+MODE_SPREAD relative to Bid for OP_SELL and Ask for OP_BUY.

Note:

TheNumberOfTry global variable mustbe greater than 1 to trigger the correction of price levels. This is due to thefact that the first attempt to open a position reveals error 130 and corrects price levels, while the second and subsequent attempts to open a position with corrected levels.

Files:
 
KimIV, good to see you back here with new features.
 

Good afternoon.

Is it possible to complement the library of useful functions from KimIV with some simple functions like :

1.open price, selected by some criteria position (symbol, type, lot size, magic number). This price can be stored in global variables and used as a certain price level, from which the algorithm of the Expert Advisor can be built.

Returns a ticket selected according to some criteria of a position or an order (symbol, type, lot size, magic number). The ticket is an important identifier, it can be used everywhere and even as an existence flag.

The more such simple functions there are, the easier it will be to pick the best ones for you, without having to worry about making mistakes when modifying existing ones.

Thank you for your functions.