[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 13

 
keekkenen >> :

The thing is that the OrderClose() function that closes the order takes the order number as the first parameter, and the order number can only be obtained by calling OrderSelect() on existing orders, so in the general case the closing looks like this...


If OrdersTotal() = 0, i.e., if there are no open orders, then the for loop is immediately finished.



Thanks for the answer, can you write the beginning of the OrderSend function? it should go right after the last brackets????

 
vadim2304 >> :

Thanks for the answer, can you write the beginning of the OrderSend function? it should go right after the last brackets????

Well, here's an example

#define              OP_BALANCE     6
int                  TRY            = 1;     
int                  TRADESLEEP     = 1000;  
int                  SLIPPAGE       = 3;

int start(){
   //  ничего не делать   
   int action = OP_BALANCE;

   if ( isTime(Period()*60)) {
      // закрываем ордера по текущему инструменту
      closeAllOrdersBySymbol( SLIPPAGE, TRY, TRADESLEEP);
   
   // получаем условие покупать, продавать, ничего не делать   
   action = getAction();
   
   if ( action== OP_BALANCE) return(0);
   
   // для примера минимальный лот   
   double lots = MarketInfo(Symbol(),MODE_MINLOT);
   
   //количество пунктов для стоплоса и текпрофита - сами определите
   int slPoint = 0, tpPoint = 0;
      
   string сomment = "";// значение для комментария по умолчанию
   int magicNumer = 0;// значение по умолчанию
   
   // открываем позицию - while используется для того чтобы открывать позицию пока она не откроется
   while(! openOrder( action, lots, slPoint, tpPoint, SLIPPAGE, сomment, magicNumer, TRY, TRADESLEEP)){}
   }
   return(0);     
}   
//+------------------------------------------------------------------+
//|  открывает  позицию по рынку                                     |
//+------------------------------------------------------------------+
int getAction(){
   int act = OP_BALANCE;
   
   /* здесь нужно написать логику, 
      если что-то, то покупать act = OP_BUY;
      если что-то, то продавать act = OP_SELL;   
   */
   return( act);
}
//+------------------------------------------------------------------+
//|  открывает  позицию по рынку                                     |
//+------------------------------------------------------------------+
bool openOrder(int type, double lots, int slPoint, int tpPoint, int slippage, string comment, 
               int magicNumer, int try, int tradeSleep){    
   bool res = false;
   int err = 0;   
   double price, tp = 0, sl = 0, ask = 0, bid = 0;  
   color col = CLR_NONE;
   Comment("Открытие ордера...");      
   
   while ( try != 0){
      while (IsTradeContextBusy() || !IsTradeAllowed()) {Comment("Торговый поток занят...");Sleep( tradeSleep);}        
      RefreshRates(); 
      ask = MarketInfo(Symbol(),MODE_ASK);
      bid = MarketInfo(Symbol(),MODE_BID);   
      if ( type==OP_BUY)  {
         price = ask; col = Red;
         if ( slPoint > 0) sl = bid - slPoint*Point; 
         if ( tpPoint > 0) tp = ask +  tpPoint*Point;
      }
      
      if ( type==OP_SELL) {
         price = bid; col = Blue;
         if ( slPoint > 0) sl = ask + slPoint*Point; 
         if ( tpPoint > 0) tp = bid - tpPoint*Point;   
      }           
            
      if ( type==OP_BUY && AccountFreeMarginCheck(Symbol(),OP_BUY, lots) <= 0 || GetLastError()==134) 
         {Comment("Недостаточно свободных средств !"); Sleep(2000);return( res);}
      if ( type==OP_SELL && AccountFreeMarginCheck(Symbol(),OP_SELL, lots) <= 0 || GetLastError()==134)
         {Comment("Недостаточно свободных средств !"); Sleep(2000);return( res);}            
      
      res = OrderSend(Symbol(), type, lots, price, slippage, sl, tp, comment, magicNumer,0, col);
      if ( res!=-1){    
         PlaySound("alert.wav");    
         try = 0;                          
         Comment("Ордер открыт !");          
      }else{
         err = GetLastError();
         if ( err > 1) try = 0;
         Comment("Ошибка - ", err);          
      }  
      Sleep(2000);       
   }  
   return( res);
}
//+------------------------------------------------------------------+
//|  закрытие одеров
//+------------------------------------------------------------------+  
bool closeAllOrdersBySymbol(int slippage,int try, int tradeSleep){
   int k = OrdersTotal(), err, nextTry;
   string msg = "";
   bool res = false;  
   
   for (int i = 0; i < k; i++) {
      if (OrderSelect( i, SELECT_BY_POS, MODE_TRADES) &&
         OrderSymbol()==Symbol()){ 
         nextTry = try;            
         while ( nextTry != 0){
            while (IsTradeContextBusy() || !IsTradeAllowed())
               {Comment("Торговый поток занят ...");Sleep( tradeSleep);}               
            res = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(), slippage,CLR_NONE);
            if ( res){                      
               nextTry = 0;
               res = true;    
               Comment("Ордер закрыт !");              
            }else{                                                          
               if ( err > 1) nextTry = 0;  
               Comment("Ошибка - ", err);        
            }                            
         }                         
      }
   }  
   return( res);
}
//+------------------------------------------------------------------+  
bool isTime(int sec){
   bool res = false;
   static datetime time = 0;
   double min = 0;
   if (TimeCurrent() >= time){
      min = MathFloor( sec / 60);
      if ( min==0) min = 1.0;         
      time = iTime(NULL,PERIOD_H1,0) + (MathFloor(Minute()/ min) + 1) * min * 60;
      res = true;
   } 
   return( res);
}
 
Simple question to programmers:

Can you tell me which function returns the value of the margin level (in percent) for open orders, which is shown in the "Trade" tab ?

In Help, none of the functions listed returns this value.

AccountMargin

AccountFreeMargin
AccountFreeMarginCheck
AccountFreeMarginMode
 
khorosh >> :

The Damiani_Volt indicator can be used.

Interesting stuff, thank you.

 
keekkenen >> :
there it is

Thank you

 
satop >> :

I don't know why you think I'm angry.

It's just my way of explaining that

by taking any sign of inequality and running

>> in the tester you can get a positive

the result with some level, and it doesn't matter which level

positive or negative. And when asked

whether to take the level with or without the minus,

there's no clear distinction, unfortunately.


I may have made a mistake..........

The issue is that the beginner is asking what he DOES NOT KNOW. This example codes serves to understand the structure (correct structure) of the EA.

And what's embedded in this piece of code is built on a CLASSICAL trading principle. Both the Expert Advisor itself and the code samples are used to study the principles, and not to poke someone or catch him at something....... What I'm asking means that it's not clear. After all, you MUST understand theoretically what and how. And then create, sculpt, invent........

 
Can you tell me if it is possible to output a jpeg on a graph?
 
keekkenen 25.02.2009 11:34 1) Please explain, OrderSend(...) function has int type, and you define it as bool type, while bool type does not have -1 value, how correct is it? 2) In KimIV function of position opening the repeat is made through for(...), while in yours through while(...). which way do you think is better?
 

1. this is an error... you have to declare res as int and add another variable of bool type to return the value of success/failure to open the order...

2. I also used one of implementations of Igor's OpenPosition() function earlier, but later changed the function to make it easier to catch and report errors...

the result is the following structure

while ( try != 0){
      // определение условий для открытыия позиции
      //..
     
      // открытие позициц
      res = OrderSend(...);
      
      if ( res > 0){ 
         PlaySound("alert.wav");    
         try = 0;                          
         Comment("Ордер открыт !"); 
         Sleep(2000);       
         ret = true;
      }else{
         /* блок определения ошибок и возврат 
          err - уровень критичности ошибки (0,1,2,3) 
          msg - описание ошибки (если showErrors = true)
          уровни определяются по номеру ошибки
          0-нет ошибки, 1-надо ждать и обновлять,
          2-сделка бракуется,3-фатальная ошибка*/
          
         ErrorBlock( showErrors, err, msg);
         if ( err > 1) try = 0;// в данном случае 2 и 3 критичны
         Comment("Ошибка - ", msg); 
         Sleep(2000);         
      }             
   }  
 
If I understand correctly in your function, if there are continuous requotes, then the number of attempts is unlimited, unlike in Igor's function? Is any limitation needed in this case?
Reason: