Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 198

 

Here is a piece of code, the data from which is then used for analysis:

   if (CurTime() == tm2)              //tm1 и tm2 - заданное время
   {
   //ObjectCreate("line2",OBJ_VLINE,0,tm1,0);
   price1=iHigh(Symbol(),PERIOD_M30,1);
   //ObjectCreate("highLine",OBJ_HLINE,0,0,price1);
   price2=iLow(Symbol(),PERIOD_M30,1);
   //ObjectCreate("lowLine",OBJ_HLINE,0,0,price2);
   Alert("price1=",price1);
   Alert("price2=",price2);
   }

i.e. further the code will look like this:

 if (Open[0]<price2) Alert("Цена ниже заданного диапазона");
 if (Open[0]>price1) Alert("Цена выше заданного диапазона");

And here is the question: how and where should we put it? If inside the condition, no alerts will be printed, and if outside the condition, the alerts will be printed on every tick.

I apologize for my incorrectly phrased question.

 
Atlis:

Here is a piece of code, the data from which is then used for analysis:

i.e. further the code will look like this:

And here's the question: how and where should we put it? If inside the condition, no alerts will be printed, and if outside the condition, the alerts will be printed on every tick.

I apologize for my incorrectly phrased question.

If you put the time check condition inside, the price alerts will only appear if the price is outside the range limits
 
Thanks, I think I've sorted it out. But one more question: now the alerts are output from a given time interval and when the range is exceeded up to "stop". Is there any way to stop this "search" when the first value satisfies the condition?
 
Atlis:
Thank you, I have sorted it out. Here is another question: the alerts are now generated from a specified time interval and when the range is exceeded up to the "stop". Can I somehow stop this "search" when the first value satisfies the condition?

Well, you need to understand the main condition that is true all the time, over a period of time. For example - comparing times. After issuing all the alerts, you need to assign a new value to the variable with which you are comparing the current time. Look for a function that defines a new bar. The concept of its construction should help you.

Have you read it here?

 

How do I know the minimum distance from the market to place a pending order?

 
Elektronik:

How do I know the minimum distance from the market to place a pending order?

int level=MarketInfo(Symbol(), MODE_STOPLEVEL);

if the StopLevel is zero, then most likely level=MarketInfo(Symbol(), MODE_SPREAD)*2;

Alpari precisely uses double spread as StopLevel.

To determine the distance read here.

 

Thank you artmedia70:

 
artmedia70:

OK, long time no answer, I'll give you a hint: when returning true value from isCloseLastPosByStop () function, return one more value, which is the lot size of the last position found.

How to do? Pass a variable into the function by reference, in which you will write the lot size in the function itself. To do this, you will need to slightly modify function isCloseLastPosByStop ()

If you don't understand anything, look for a function that returns the lot size of the last closed position. Or you can make one yourself. And use it, but this is more costly than passing the lot value together with true

I have changed the function so that instead of True function returns a variable lot, in which the function itself I have written the size of the lot.

Everything compiles, but the orders don't open:

2013.10.23 20:57:46 2011.02.24 16:25 GMT EURUSD,M5: OrderSend error 4051

2013.10.23 20:57:46 2011.09.22 22:20 WEDNING EURUSD,M5: invalid lots amount for OrderSend function

if(isCloseLastPosByStop ()== lot )         //если последний ордер закрылся по стопу
{
P=lot*2;                                      //открыть ордер объемом = объему закрытому по стопу ордеру умноженному на 2                                  
OrderSend(Symbol(),OP_SELL,P,Bid,1,Ask+1500*Point,Ask-300*Point,"jfh",123 );
}
else                                         //если последний ордер закрылся не по стопу
{

P=0.1;  
OrderSend(Symbol(),OP_SELL,1,Bid,P,Ask+1500*Point,Ask-300*Point,"jfh",123 );   //открыть ордер обычным объемом 0.1
}
   return(0);
  }
//============================================================  
bool isCloseLastPosByStop(string sy="", int op=-1, int mn=-1) {
  datetime t;
  double   ocp,lot, osl;                                             // добавил переменную - количество лотов в оредере
  int      dg, i, j=-1, k=OrdersHistoryTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (t<OrderCloseTime()) {
                t=OrderCloseTime();
                j=i;
              }
            }
          }
        }
      }
    }
  }
  if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
    dg=MarketInfo(sy, MODE_DIGITS);
    if (dg==0) if (StringFind(OrderSymbol(), "JPY")<0) dg=4; else dg=2;
    ocp=NormalizeDouble(OrderClosePrice(), dg);
    osl=NormalizeDouble(OrderStopLoss(), dg);
    if (ocp==osl)
    lot=OrderLots( ) ;                              //добавил вычисление количества лотов в ордере который закрылся по стопу.
    return(lot);                                    // вместо возвращаемого функцией значения True вставил переменную lot со значением количества лотов
  }
  return(False);
}

Please tell me what my mistake is.

Thank you.

 
solnce600:

I have changed the function so that instead of True the function returns a variable lot, in which I have written the lot size in the function itself.

All compiles, but the orders are not opened in the journal says:

2013.10.23 20:57:46 2011.02.24 16:25 PM EURUSD,M5: OrderSend error 4051

2013.10.23 20:57:46 2011.09.22 22:20 WEDNING EURUSD,M5: invalid lots amount for OrderSend function

Please advise what is my mistake.

Thank you.


The function determining the last closed position by stop has a bool type, while you are trying to return the double type. Correspondingly, it returns either 0 or 1.

I wrote that we should add passing of one variable by reference into it:

//+----------------------------------------------------------------------------+
bool isCloseLastPosByStop(string sy, int op, int mn, double &ll) {
   double   pt;
   int      t, dg, i, j=-1, k=OrdersHistoryTotal()-1;

   for (i=k; i>=0; i--) {
     if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
         if (OrderMagicNumber()!=mn)   continue;   // если магик не тот, переходим к следующему
         if (OrderSymbol()!=sy)        continue;   // если символ не тот, переходим к следующему
         if (OrderType()!=op           continue;   // если тип не тот, переходим к следующему
         if (t<OrderCloseTime()) {
            t=OrderCloseTime();
            j=i;
            }
         }
      }
   if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY)) {
      dg=MarketInfo(OrderSymbol(), MODE_DIGITS);      // количество знаков в цене символа ордера
      pt=MarketInfo(OrderSymbol(), MODE_POINT);       // размер пункта инструмента в валюте котировки ордера
      if (MathAbs(OrderClosePrice()-OrderStopLoss()<0.5*pt)) { // Если закрыт по стопу
         ll=OrderLots();                              // записываем количество лотов в ордере, закрытом по стопу
         return(true);                                // возвращаем истину
         }
      }
   return(False);                                     // возвращаем ложь (позиции нету, либо не по стопу)
}
//+----------------------------------------------------------------------------+

Now check the last Buy, for example:

//+----------------------------------------------------------------------------+
double Lot=MarketInfo(Symbol(), MODE_MINLOT);            // задаём минимальное значение переменной
if (isCloseLastPosByStop(Symbol(), OP_BUY, Magic, Lot)) {// в переменную Lot будет записано значение лота закрытой позиции
   // Если последний закрытый Buy закрыт по стопу
   Lot= //... эта переменная содержит размер лота закрытой позиции, выполняете нужные вычисления с этой переменной
   }
//+----------------------------------------------------------------------------+

Like this...

 

Good evening.

Could you please tell me how to add closing all positions and deleting all orders at the end of the trading week?

Thank you!