Useful features from KimIV - page 92

 
alexpert007 >> :

And here's another question for Igor.

Have you created a separate custom (or other) function to flip the buy-sell position and vice versa, without the usual OrderClose - OrderSend?

I'm not Igor, but there is a standard OrderCloseBy function for flipping.

 

Hello, I need help in solving a problem. Let me try to describe it:

There is a function that counts orders:

int OrdersAll(int mag)
{
int kolvo=0;
for (int i=OrdersTotal()-1; i>=0; i--)
{
if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if((OrderType()==OP_BUY || OrderType()==OP_SELL) && OrderSymbol()==Symbol() && OrderMagicNumber() == mag )
kolvo++;
}
}
return(kolvo);
}

Further, in the process, if there is no order for the current symbol, when the condition is met, 1 order, for example, to buy should be placed:

if(OrdersAll(MAGICNO)==0)
{
if(condition)
{
op=Ask;if(SL>0){sl=Ask-SL*Point*mn;}if(TP>0){tp=Ask+TP*Point*mn;}
err=OrderSend(Symbol(),OP_BUY,LotsOptimized(),NormalizeDouble(op,Digits),3,NormalizeDouble(sl,Digits),
NormalizeDouble(tp,Digits),"",MAGICNO,0,Blue);
if(err<0)
{
Print("OrderSend()- Error OP_BUY. The order is not accepted. op "+op+" sl "+sl+" tp "+tp+""+GetLastError());return(-1);
}
}
}

Instead, when opening several symbols in the terminal and running an EA in each of them, for example, the code above can open one order - this is correct, but at the same time it can open 20-30 orders until the walrus runs out if the condition holds for several ticks. I haven't seen this happen on a single instrument yet, but I'm not at all sure it won't happen on a single instrument either. How do I fix my code to make it hard to open no more than one order.

 

Igor, good evening,

I can't manage your function call:

//+----------------------------------------------------------------------------+
//| Author : Kim Igor V. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Version : 19.02.2008 |
//| Description : Returns total profit of open positions in the deposit currency |
//+----------------------------------------------------------------------------+
//| Parameters: |
//| sy - name of instrument (" - any symbol, |
//| NULL - current symbol) |
| //| op - operation (-1 - any position) |
//| mn - MagicNumber (-1 - any magik) |
//+----------------------------------------------------------------------------+
double GetProfitOpenPosInCurrency(string sy="", int op=-1, int mn=-1) {
double p=0;
int i, k=OrdersTotal();

if (sy=="0") sy=Symbol();
for (i=0; i<k; 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) {
p+=OrderProfit()+OrderCommission()+OrderSwap();
}
}
}
}
}
return(p);
}

Can you tell me, in the call TotOrdProf=GetProfitOpenBuyPosInCurrency(EURUSD, ____, 1);

1. Suppose EURUSD, should it be in quotes "EURUSD" or is it allowed without;

2. What should be the second calling parameter (where is a dash) to calculate the total buy and sell profit (I tried the default -1; not correct)

3. the third parameter is the magic number of the Expert Advisor? - I have not got to it yet, just a question if I understand the parameter correctly.

Thanks.

 

TotOrdProf=GetProfitOpenBuyPosInCurrency("EURUSD",-1, -1);

- only for EURUSD

- all open positions (-1)

- positions with any magik (-1)

 

Good afternoon.

As you know, Sleep() does not work in the terminal tester, so you have to use loops from math functions to delay the execution:

if (IsTesting()==true){for(int z0 = 1; z0 < zFILE*10000; z0++){MathSqrt(MathPow(5,5));MathSqrt(MathPow(5,5));MathSqrt(MathPow(5,5));}}

where zFILE is the Expert Advisor's execution delay.

My question is: Is there more sophisticated solution, because I need some delay from few seconds to 10-20min (processing data by external program) ?

Or at least how to measure runtime more accurately (couse processors performance is different) and pick up the slowest one ?





 
Piboli >> :

Question: is there a more elegant solution (delay function), as the delay is needed from several seconds to 10-20min (data processing by external software) ?

Did not try to use callbacks and synchronizers?

 

Kim's functions

I wonder if there's a function that allows you to pull the name of the last pattern

and record changes in its components


 

KimIV maybe you can and write an indicator

The indicator should search for a flat channel within a specified period of time and not wider than specified in the settings

This indicator should search the channel both within one day and on the next day as in your function isTradeTimeInt().
This indicator can draw 5 channels during a day or just one.
In the settings

extern double maximum channel height in points
extern int Bar_Time how we calculate the time interval in bars (1) or hours and minutes (2)
extern string minimum time interval of the channel in hours and minutes
extern int int minimum time interval of the channel in bars
extern int maximum number of drawn channels that remain drawn

I attach a similar indicator to https://www.mql5.com/ru/code but it draws the channel in a strictly set time interval and doesn't look for such a channel by itself. It should only look for a channel that does not exceed the maximum height of the channel and is not shorter than the minimum time interval of the channel.
If we choose Bar_Time for the channel time, the channel(1) is calculated from the current time minus the time given in the settings, i.e. 2 hours 15 minutes or another given time. If it is now 1 hour 15 minutes, it looks for max and min from 23 hours 00 minutes and if the max minus the min is below the max channel height, it draws two max and min lines from 23:00 to 02:15. It also draws Fibo levels above and below the channel.

If we choose Bar_Time by number of bars, the channel is calculated from the current bar minus the number of bars specified in the settings, i.e. from zero bar to the zero bar minus the number specified in the settings. If the chosen number is 50, we will look for high and low of the last 50 bars from the zero bar and if the high minus the low is not more than the maximum channel height, two lines of high and low of 50 bars will be drawn.

All levels and channel data are stored in buffers

 

Question to Igor

If you can give me a code fragment of an Expert Advisor working on two separate accounts (Buy Sell), polling the state of each account (to calculate the lot size) and having the ability to transfer the deposit from one account to another, as well as simulating the withdrawal of part of the deposit under certain conditions (say a monthly or quarterly profit - from it n%)

Let me clarify my question

1 Expert Advisor works on Buy (polls state of account 2) . 6200

2 Expert Advisor opens Sell position (requests account balance at 1) ... 8400

If there are no open positions

1100 from account 2 to account 1

account 1 - 7300

account 2 - 7300

total gross deposit SD=14600 Maximum risk - 10% Maximum lot 0.14

Further

as of 01.04.09 SD=10000

as of 01.07.09 SD=14600

Profit=4600

10% = 460

460 deducted on the third account

Thank you

 

Dear Igor, Help me out!

I connected a-SimpleTrailing.mqh.

Added what was specified, but 3 errors are popping up:

'clModifyBuy' - variable not defined
'clModifySell' - variable not defined
'ti' - variable already defined

What to do?(



Here's what fits:

.........................
   total=OrdersTotal();
   if( total<1)
     {
      if(AccountFreeMargin()<(1000* Lots))
        {
         Print("У вас нет денег. Свободные средства = ", AccountFreeMargin());
         return(0);
        }
      if(Hour()>=0)
        {
         chk=1;
         Print("Позиция возможна!");
        }
      if( chk==1)
        {
         if((Low[0]<= MaDert1sell) || (Low[0]<= MaDert2sell))
           {
int ti= OpenPosition(NULL, OP_BUY, 0.1);
if (OrderSelect( ti, SELECT_BY_TICKET))
ModifyOrder(-1, Ask-30*Point, Bid-99*Point, clModifySell);
            if( ticket>0)
              {
               if(OrderSelect( ticket, SELECT_BY_TICKET, MODE_TRADES))
                  Print("Открыт ордер SELL : ",OrderOpenPrice());
               chk=0;
              }
            else
              {
               Print("Ошибка открытия SELL ордера : ",GetLastError());
               return(0);
              }
           }
         if((High[0]>= MaDert1buy) || (High[0]>= MaDert2buy))
           {
int ti= OpenPosition(NULL, OP_BUY, 0.1);
if (OrderSelect( ti, SELECT_BY_TICKET))
ModifyOrder(-1, Ask-30*Point, Bid-99*Point, clModifyBuy);
            if( ticket>0)
              {
               if(OrderSelect( ticket, SELECT_BY_TICKET, MODE_TRADES))
                  Print("Открыт ордер BUY : ",OrderOpenPrice());
               chk=0;
              }
            else
              {
               Print("Ошибка открытия BUY ордера : ",GetLastError());
               return(0);
              }
           }
        }
      return(0);
     }
   for( cnt=0; cnt< total; cnt++)
     {
      OrderSelect( cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // это открытая позиция? OP_BUY или OP_SELL 
         OrderSymbol()==Symbol())  // инструмент совпадает?
        {
         if(OrderType()==OP_BUY)   // открыта длинная позиция
           {
            // проверим, может уже пора закрываться?
            if(Hour()==23)
              {
               chk=0;
               OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // закрываем позицию
               return(0); // выходим
              }
           }
         else // иначе это короткая позиция
           {
            // проверим, может уже пора закрываться?
            if(Hour()==23)
              {
               chk=0;
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // закрываем позицию
               return(0); // выходим
              }

           }
        }
     }
   return(0);
  }

//+----------------------------------------------------------------------------+
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Модификация одного предварительно выбранного ордера.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена установки ордера                                              |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    cl - цвет значка модификации                                            |
//+----------------------------------------------------------------------------+
void ModifyOrder(double pp=-1, double sl=0, double tp=0, color cl=CLR_NONE) {
  bool   fm;
  double op, pa, pb, os, ot;
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;
 
  if ( pp<=0) pp=OrderOpenPrice();
  if ( sl<0 ) sl=OrderStopLoss();
  if ( tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble( pp, dg);
  sl=NormalizeDouble( sl, dg);
  tp=NormalizeDouble( tp, dg);
  op=NormalizeDouble(OrderOpenPrice() , dg);
  os=NormalizeDouble(OrderStopLoss()  , dg);
  ot=NormalizeDouble(OrderTakeProfit(), dg);
 
  if ( pp!= op || sl!= os || tp!= ot) {
    for ( it=1; it<= NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, 0, cl);
      if ( fm) {
        if ( UseSound) PlaySound( NameFileSound); break;
      } else {
        er=GetLastError();
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        Print("Error(", er,") modifying order: ", ErrorDescription( er),", try ", it);
        Print("Ask=", pa,"  Bid=", pb,"  sy=",OrderSymbol(),
              "  op="+ GetNameOP(OrderType()),"  pp=", pp,"  sl=", sl,"  tp=", tp);
        Sleep(1000*10);
      }
    }
  }
}
//+----------------------------------------------------------------------------+
//|  Возвращает наименование торговой операции                                 |
//|  Параметры:                                                                |
//|    op - идентификатор торговой операции                                    |
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
	switch ( op) {
		case OP_BUY      : return("Buy");
		case OP_SELL     : return("Sell");
		case OP_BUYLIMIT : return("Buy Limit");
		case OP_SELLLIMIT: return("Sell Limit");
		case OP_BUYSTOP  : return("Buy Stop");
		case OP_SELLSTOP : return("Sell Stop");
		default          : return("Unknown Operation");
	}
}
//+----------------------------------------------------------------------------+
Reason: