[¡AVISO CERRADO!] Cualquier pregunta de novato, para no saturar el foro. Profesionales, no pasen. No puedo ir a ningún sitio sin ti. - página 13

 
keekkenen >> :

La cuestión es que la función OrderClose() que cierra la orden toma el número de orden como primer parámetro, y el número de orden sólo se puede obtener llamando a OrderSelect() en las órdenes existentes, por lo que en el caso general el cierre se ve así...


Si OrdersTotal() = 0, es decir, si no hay órdenes abiertas, el bucle for se termina inmediatamente.



Gracias por la respuesta, ¿puedes escribir el principio de la función OrderSend? debería ir justo después de los últimos corchetes????

 
vadim2304 >> :

Gracias por la respuesta, ¿puedes escribir el principio de la función OrderSend? debería ir justo después de los últimos corchetes????

Bueno, aquí hay un ejemplo

#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);
}
 
Una simple pregunta a los programadores:

¿Pueden decirme qué función devuelve el valor del nivel de margen (en porcentaje) para las órdenes abiertas, que se muestra en la pestaña "Comercio"?

En la Ayuda, ninguna de las funciones enumeradas devuelve este valor.

AccountMargin

AccountFreeMargin
AccountFreeMarginCheck
AccountFreeMarginMode
 
khorosh >> :

Se puede utilizar el indicador Damiani_Volt.

Un material interesante, gracias.

 
keekkenen >> :
ahí está

Gracias

 
satop >> :

¿Qué te hace pensar que estoy enfadado?

Es sólo mi manera de explicar que

tomando cualquier signo de desigualdad y corriendo

>> en el probador se puede obtener un positivo

el resultado con algún nivel, y no importa qué nivel

positivo o negativo. Y cuando se le preguntó

si se toma el nivel con o sin el menos,

no hay una distinción clara, por desgracia.


Puede que haya cometido un error..........

La cuestión es que el principiante está preguntando lo que NO SABE. Este ejemplo de códigos sirve para entender la estructura (estructura correcta) de la EA.

Y lo que hay en esta pieza de código se basa en un principio de comercio CLÁSICO. Tanto el propio Asesor Experto como los ejemplos de código sirven para estudiar los principios, y no para pinchar a alguien o pillarle en algo....... Lo que pregunto es que no está claro. Al fin y al cabo, hay que entender teóricamente el qué y el cómo. Y luego crear, esculpir, inventar........

 
¿Pueden decirme si es posible imprimir un jpeg en un gráfico?
 
keekkenen 25.02.2009 11:34 1) Por favor, explique, la función OrderSend(...) tiene tipo int, y usted la define como tipo bool, mientras que el tipo bool no tiene valor -1, ¿qué tan correcto es? 2) En la función KimIV de apertura de posición la repetición se hace a través de for(...), mientras que en la suya a través de while(...).
 

1. esto es un error... tienes que declarar res como int y añadir otra variable de tipo bool para devolver el valor de éxito/fracaso al abrir la orden...

2. También utilicé antes una de las implementaciones de la función OpenPosition() de Igor, pero después cambié la función para que fuera más fácil detectar e informar de los errores...

el resultado es la siguiente estructura

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);         
      }             
   }  
 
Si he entendido bien en tu función, si hay requotes continuos, entonces el número de intentos es ilimitado, a diferencia de la función de Igor? ¿Es necesaria alguna limitación en este caso?
Razón de la queja: