Closing of positions. On indicator signal. - page 5

 
komposter:
rid:

The result is still the same! With the last variant only the last open position is closed!

Now remove return after OrderClose, and observe the result ;)

//----------------------------------------------------------------------
 // for (int v=0; v<OrdersTotal(); v++)               { 
  for ( int v = OrdersTotal() - 1; v >= 0; v -- )                  {       
      if (OrderSelect(v, SELECT_BY_POS, MODE_TRADES))               {           
        if (OrderSymbol()==Symbol()&& OrderMagicNumber()==Magic)     { 
//-----------------------------------------------------                  
if (OrderType() == OP_BUY) { 
      if( RVI_1>=Up_lim &&  RVI_0<Up_lim)     {
         OrderClose(OrderTicket(),OrderLots(),Bid,3,Green); // закрываем позицию
                // return(0); // выходим         
              }   }  
 //--------------------------------------------------------
if (OrderType() == OP_SELL) { 
      if((RVI_1_<=Low_lim) && (RVI_0_>Low_lim))    {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Green); // закрываем позицию
                // return(0); // выходим
              }   }  
 //-------------------------------------------------------                       
    }  // Symbol()  
  } // select
 } //total
} //Close_ 
 //****************************************************************************
I did it as instructed. And a miracle happened. All open positions are closed by the signal of the indicator! But why?
 
rid:
komposter:
rid:

The result is still the same! With the last variant only the last open position is closed!

Now remove return after OrderClose, and observe the result ;)

//----------------------------------------------------------------------
 // for (int v=0; v<OrdersTotal(); v++)               { 
  for ( int v = OrdersTotal() - 1; v >= 0; v -- )                  {       
      if (OrderSelect(v, SELECT_BY_POS, MODE_TRADES))               {           
        if (OrderSymbol()==Symbol()&& OrderMagicNumber()==Magic)     { 
//-----------------------------------------------------                  
if (OrderType() == OP_BUY) { 
      if( RVI_1>=Up_lim &&  RVI_0<Up_lim)     {
         OrderClose(OrderTicket(),OrderLots(),Bid,3,Green); // закрываем позицию
                // return(0); // выходим         
              }   }  
 //--------------------------------------------------------
if (OrderType() == OP_SELL) { 
      if((RVI_1_<=Low_lim) && (RVI_0_>Low_lim))    {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Green); // закрываем позицию
                // return(0); // выходим
              }   }  
 //-------------------------------------------------------                       
    }  // Symbol()  
  } // select
 } //total
} //Close_ 
 //****************************************************************************
I did it as instructed. And a miracle happened. All open positions were closed according to the indicator signal! But why?
Your return interrupted the processing cycle.
 
Got it. Thank you to everyone who responded!
 
KimIV:

I usually implement this kind of functionality:

//+----------------------------------------------------------------------------+
//|  Управление позициями                                                      |
//+----------------------------------------------------------------------------+
void ManagePositions() {
  double sl=0, tp=0;
  int    ms[2];
 
  ArrayInitialize(ms, 0);
  GetTradeSignal(ms);
  if (ExistPositions("", -1, Magic)) {
    if (ms[1]>0) ClosePositions("", OP_BUY , Magic);
    if (ms[1]<0) ClosePositions("", OP_SELL, Magic);
  } else {
    if (ms[0]>0) {
      if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0;
      if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0;
      OpenPosition(OP_BUY, sl, tp, Magic);
    }
    if (ms[0]<0) {
      if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0;
      if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0;
      OpenPosition(OP_SELL, sl, tp, Magic);
    }
  }
}
As you can see, functions are written that perform quite specific actions. And then these functions are combined in such a way as to implement the desired tactics of working with positions.
Please, Igor, describe your functionality in a bit more detail. I want to understand it, but due to my modest knowledge I lose my train of thought at the very beginning.
 
rid писал (а):
Please, Igor, describe your function in more details. I want to understand it, but because of my modest knowledge I may lose my train of thought at the very beginning.

This was an example pulled from a working EA. Function assignment:

  1. Function GetTradeSignal() fills array ms[] with trade signals. Each expert has its own stuffing of GetTradeSignal() function, of course.
  2. Function ExistPositions() returns the flag of position presence.
  3. Function ClosePositions() closes one or more positions in presence of a corresponding signal in ms[] array. Before closing, the presence of a position is checked by the condition if (ExistPositions("", -1, Magic)).
  4. Function OpenPosition() opens one position at the current price in the presence of a corresponding signal in the ms[] array. The position can be opened only if there is no signal.

Tactics:

  1. If there are positions and there is a signal to close, then close the positions.
  2. If there are no positions and there is a signal to open a position, then open a position.

You see how easy it is? :-)

 
Yes, thank you. I'll see what I can figure out.
 

Hello everyone! Merry Christmas!

Another problem has come up. I have looked through the theory, but have not found a way out yet. For some reason, I need to close opened positions in my Expert Advisor using the function instead of using stops (Stop Loss and Take Profit). I have done it. It worked! However...

When trying to insert into an Expert Advisor the library for calculating lots (B-lots), I found out that it started working in an unknown manner! If I had not used MM, the balance curve (after optimization) went steadily upwards with a hardly noticeable drawdown, after adding MM I suddenly had a sharp plummet! Moreover! Even if we remove the B-lots library and simply increase the lot size from 0.1 to 0.2, we again see a sharp pull-down. Even when the initial deposit is increased in several times ..... I.e., it's neither the library nor the deposit size - the drawdown was miserable to begin with... . I enter the market like this:

//---------------ПОКУПАЕМ ------------------------------------------
... ... ...
if (Long)    {  //выключатель вкл   
if (!ExpertOrder( MagicLong ))     {//если  нет открытых длинных позиций 
 
    //Lots=GetSizeLot(); 
    ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,"",MagicLong,0,Blue); 
    if(ticket<0){Print("Ошибка открытия ордера BUY #",GetLastError());return(0);}
              }
              }
Everything is clear and understandable here. Then I close positions using OrderClose(. ...) function. Like this:
for (int v=0; v<OrdersTotal(); v++)               { 
 // for ( int v = OrdersTotal() - 1; v >= 0; v -- ){      
      if (OrderSelect(v, SELECT_BY_POS, MODE_TRADES))  {           
        if (OrderSymbol()==Symbol() )                   { 
//-----------------------------------------------------             
if (ExpertOrder( MagicLong ))  {
  if(OrderProfit() > tp)   { OrderClose(OrderTicket(),OrderLots(),Bid,3,Green); return(0);}
  if(OrderProfit() <= -sl) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Green); return(0);}
                               }
}}}
When I initially set the lot=0.1, the design works fine! When I try to change the lot size (increase) or when I try to enable the MM library, the operation is broken! I cannot understand why? I used "Lots" instead of OrderLots(), but nothing has changed. Please, tell me.
 
rid:
With the initial lot=0.1 the design works fine! When I try to change the lot size (increase) or when I try to enable the MM library - the operation is broken! I cannot understand why? I used "Lots" instead of OrderLots(), but nothing has changed. Please, advise?
We have to look at how the EA acts differently.
Are the orders opened/closed at the same time as before?
 

No. By increasing the lot from 0.1 to 0.2 trades start to occur more often, more than twice as often ! With the same external parameters ... It's strange. But I'm not too lazy! I did it like this:

I removed closing of positions using the OrderClose function, and provided for normal closing by Stop Loss and Take Profit in the ticket=OrderSend(... ... ...) function. In this case the MM block worked as it should! It seems it's all about the function

if(OrderProfit() > tp)    { OrderClose(OrderTicket(),OrderLots(),Ask,3,Green);  }
Maybe the value of "tp" should be changed accordingly when increasing the lot?
 
Shall we point our fingers in the sky? ;)

The error is in the code. Where - I do not know, because there is not even a code. Call the clairvoyants from the next branch ;)