[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 303

 
costy_:

There are plenty of options, for example recording open times in a file, but it is easier to scroll through the open orders and compare lifetimes.

In general, rephrase .

..

"It is necessary to close all open positions after a specified time interval

" for each individual position (that's how I understood the question). thanks! The word "easier" in your answer is the key word, it means there is no such function built in. I just wanted to close each individual position 2 hours after it was opened .
 
costy_:

The script will not find the tester's time so easily (but the indicator will), you can attach it to the start of the test advisor

quickly and reliably ...

Thank you. Made it in the script like this:
    datetime time_start=GlobalVariableGet( "Time_test");
//    Alert(iBarShift(NULL,0,time_start)); 
    EndBar =  iBarShift(NULL,0,time_start);
Everything works.
 

I'm trying to write an inikator. I don't understand why it redraws. Besides, it only draws on rendering. Please help me. I am new to programming.

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Magenta
#property indicator_color2 Red
//---- input parameters
extern int N;
datetime some_time=D'1971.01.11 00:00';
datetime some_time_1=D'1971.01.11 00:00';
//---- buffers
double RLB_Buffer[];
double RLB_Buffer_1[];
double Real_Line_Balanse=0,x=0,last_high,last_low,RLB, Real_Line_Balanse_1=0,x1=0,last_high_1,last_low_1,RLB_1;
bool dirlong,first;
int i,ii,bar_high,bar_low,first_t_bar,now_bar,first_t_bar_1,now_bar_1;
//+------------------------------------------------------------------+
//| Custom indicator initialisation function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- indicator line
SetIndexStyle(0, DRAW_ARROW);
SetIndexArrow(0, 159);
SetIndexBuffer(0,RLB_Buffer);
//----;
SetIndexStyle(1, DRAW_ARROW);
SetIndexArrow(1,159);
SetIndexBuffer(1,RLB_Buffer_1);
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();
Comment(i," ",ii);
//----
if(Bars < 3)
return(0);
//----------
first_t_bar=iBarShift(NULL,0,some_time,false); //bars trend upwards
now_bar=iBarShift(NULL,0,TimeCurrent(),false); //last bar, rightmost
i=counted_bars-first_t_bar+1;
//------------
first_t_bar_1=iBarShift(NULL,0,some_time_1,false); //trend start bar
now_bar_1=iBarShift(NULL,0,TimeCurrent(),false); //last bar, rightmost
ii=counted_bars-first_t_bar_1+1;
// if(IsVisualMode()==TRUE) i=first_t_bar-counted_bars-1; //if(counted_bars), then trend start bar
if(counted_bars == 0)
{
first = false;
i=first_t_bar+1;
ii=first_t_bar_1+1;
}
//------------ //minus bars counted
dirlong = false;
if(iMA(NULL,0,1,0,MODE_SMA,PRICE_MEDIAN,0)>iMA(NULL,0,2,0,MODE_SMA,PRICE_MEDIAN,0))dirlong = true;
if(dirlong == true) //if trend is upwards
{
while(i>=0)
{
x++; //count of bars from the trend start
Real_Line_Balanse=Close[i+5]; //count of the sum of bars from the trend
RLB=Real_Line_Balanse;
if(RLB<Low[1]) RLB_Buffer[i]=Real_Line_Balanse; //show the line only if the price is up
//-------
if(RLB>Close[i]&& x>50) //if price has crossed RLB from top to bottom
{
bar_high=iHighest(NULL,0,MODE_HIGH,first_t_bar,now_bar);//then determine HIGH between
//last bar and start of trend
some_time_1=Time[bar_high]; //new beginning of the downward trend
x=0; //zeroing of the bar counter from the trend start
Real_Line_Balanse=0;
}
i--;
}//while
//-------
}//dirlong
//---------------------
//---------------------
if(dirlong == false) //if trending downwards
{
while(ii>=0)
{
x1++; //count of bars from the trend start
Real_Line_Balanse_1=Close[ii+10]; //count the amount of bars from the trend
RLB_1=Real_Line_Balanse_1;
if(RLB_1>High[1]) RLB_Buffer_1[ii]=Real_Line_Balanse_1;
//-------
if(RLB_1<Close[ii]&& x1>50) //if price has crossed the RLB from top to bottom
{
bar_low=iLowest(NULL,0,MODE_LOW,first_t_bar_1,now_bar_1);//then determine the LOW between
//last bar and start of trend
some_time=Time[bar_low]; //new beginning of the trend upwards
x1=0; //zeroing of the bar counter from the trend start
Real_Line_Balanse_1=0;
}
ii--;
} //while
//-------
}//dirlong
//---------------------
return(0);
}
//+------------------------------------------------------------------+

 

This is nonsense. Instead of

i=counted_bars-first_t_bar+1;

I put in a design that counts the bars it counts itself. ALL started to run smoothly. IndicatorCounted(); glitches or I don't get it...

 

how to inform a variable about the status of a closed order?


avatar
2
vitaluxa 29.10.2011 21:26
Hello!

If an EA has opened an order and it has closed on Stop Loss or Take Profit, how do I inform the variable that the order has closed exactly on Stop Loss or Take Profit?
Thanks in advance!
 
001:

This is nonsense. Instead of

i=counted_bars-first_t_bar+1;

I put in a construct that counts the counted bars itself. ALL goes well. IndicatorCounted(); glitches or I don't get it...

You use while(i>=0), so when a new candle appears, i=1 (to make sure the data of the previous candle is counted by the recorded data once).

Why enter some_time=D'1971.01.11 00:00'; use Bars , IndicatorCounted does not work for me (well, the error is probably because of the first_t_bar).

Your algorithm and you should fix it.

"I'm new to programming."Since 2007).

 
sergeev:

how to inform a variable about the status of a closed order?


:)

+ ...

For Vitaluha:

https://docs.mql4.com/ru/trading/OrderStopLoss

https://docs.mql4.com/ru/trading/OrderTakeProfit

 
Good afternoon, could you please tell me why the quotes from June 10 to September 22 of this year cannot be uploaded? I have made two to three history uploads and all have the same gap in the data.
 
//жжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжж Закрвает открытые позиции через 2 суток
void DelOldPositions()                                    
{   
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--)
    {
      OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
        {
         if (OrderOpenTime()+2*24*60*60  > TimeCurrent())  
          {
           OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,4 ),3,Red);
          }
        }
   }
}
//жжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжжж
Помогите поправить 2 последние строки, т.к. в тестере почему-то  мгновенно  закрывает все открытые позы. С уважением.
 

The problem is that the EA constantly reopens orders, i.e. there is a buy signal - it opens an order, then closes it at profit, and the conditions are still preserved it opens it again.

I thought it could be handled with the traditional buy and sell counter - if a buy order has opened the counter +1 and a new buy cannot be opened until the counter is 0 and the counter is reset only when it is closed.

extern double TakeProfit = 150;
extern double Sl = 150;
extern double Lots = 0.1;
extern int n = 9;     
        
//-----------------------------------------------------------

int start()
 {
  int cnt, ticket, total, i, Buy=0, Sell=0;
  double x1=iIchimoku(NULL,0,9,26,52,MODE_TENKANSEN,0);   //красная
  double x2=iIchimoku(NULL,0,9,26,52,MODE_KIJUNSEN,0);    //синяя
  double x3=iIchimoku(NULL,0,9,26,52,MODE_SENKOUSPANA,0); //фиол пунктир
  double x4=iIchimoku(NULL,0,9,26,52,MODE_SENKOUSPANB,0);  //кр пунктир
  double x5=iIchimoku(NULL,0,9,26,52,MODE_CHINKOUSPAN,0);  //зеленая
  double x6=Ask;
  double x61=Bid;
  double Lot=0;  
  total=OrdersTotal();
  
  for (i=total-1;i>=0;i--)   //счетчик выставленных ордеров
   { 
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
       {
         if(OrderType()==OP_BUY)
          { 
           Buy++;
            }  
          if (OrderType()==OP_SELL)
           { 
            Sell++;
             }  
        }
     }
  if(total<1)//проверка количества ордеров 
   {
    
         if(AccountFreeMargin()<(100*Lots))
              {
     Print("Недостаточно средств = ", AccountFreeMargin());
     return(0);  
               }

         if (x6>x3 && x6>x4 && x1>x2 && x6>x2 && x6<(x2+60) && Buy==0) //бай
               {
                   ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-Sl*Point,Ask+TakeProfit*Point,0,0,0,Green); Sell=0; // ордер и обнуление счетчика
                      if(ticket>0)
                      {
                         if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("открыта позиция BUY : ",OrderOpenPrice());
      
                         else Print("Ошибка при открытии BUY позиции : ",GetLastError()); 
                        }
              }
   
         if (x6<x3 && x6<x4 && x1<x2 && x6<x2 && x6>(x2-60) && Sell==0) //селл 
                {
                   ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+Sl*Point,Bid-TakeProfit*Point,0,0,0,Red); Buy=0; //сам по себе ордер и обнуление счетчика 
                     if(ticket>0)
                     {
                         if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("открыта позиция SELL : ",OrderOpenPrice());
    
                         else Print("Ошибка при открытии SELL позиции : ",GetLastError());
      
                      } 
    
                  }
  
  
  } 

   if((OrderType()==0 && x61<x3 && x61<x4 && x1>x2 && x1>x3 && x1>x4) || (OrderType()==1 && x61>x3 && x61>x4 && x1<x2 && x1<x3 && x1<x4)) //закрытиеи на развороте
      {
          bool   result;
          double price;
          int    cmd,error;
//----
          if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))
              {
                  cmd=OrderType();
                  if(cmd==OP_BUY || cmd==OP_SELL)
                    {
                      while(true)
                        {
                         if(cmd==OP_BUY) price=Bid;
                         else            price=Ask;
                         result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE);
                         if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); }
                         else error=0;
                         if(error==135) RefreshRates();
                         else break;
                        }
                     }
               }
          else Print( "Error when order select ", GetLastError());
//----
          
      }
 
 }
 
 
Files: