[Qualsiasi domanda da principiante, per non ingombrare il forum. Professionisti, non passate. Non posso andare da nessuna parte senza di te. - pagina 13

 
keekkenen >> :

Il fatto è che la funzione OrderClose() che chiude l'ordine prende il numero dell'ordine come primo parametro, e il numero dell'ordine può essere ottenuto solo chiamando OrderSelect() sugli ordini esistenti, quindi nel caso generale la chiusura appare così...


Se OrdersTotal() = 0, cioè se non ci sono ordini aperti, allora il ciclo for si conclude immediatamente.



Grazie per la risposta, puoi scrivere l'inizio della funzione OrderSend? dovrebbe andare subito dopo l'ultima parentesi ????

 
vadim2304 >> :

Grazie per la risposta, puoi scrivere l'inizio della funzione OrderSend? dovrebbe andare subito dopo l'ultima parentesi ????

Bene, ecco un esempio

#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);
}
 
Semplice domanda ai programmatori:

Potete dirmi quale funzione restituisce il valore del livello di margine (in percentuale) per gli ordini aperti, che è mostrato nella scheda "Trade"?

In Aiuto, nessuna delle funzioni elencate restituisce questo valore.

AccountMargin

AccountFreeMargin
AccountFreeMarginCheck
AccountFreeMarginMode
 
khorosh >> :

Si può usare l'indicatore Damiani_Volt.

Roba interessante, grazie.

 
keekkenen >> :
eccolo lì

Grazie

 
satop >> :

Cosa ti fa pensare che io sia arrabbiato?

È solo il mio modo di spiegare che

prendendo qualsiasi segno di disuguaglianza e correndo

>> nel tester si può ottenere un positivo

il risultato con qualche livello, e non importa quale livello

positivo o negativo. E quando è stato chiesto

se prendere il livello con o senza il meno,

Non c'è una chiara distinzione, purtroppo.


Potrei aver fatto un errore..........

Il problema è che il principiante sta chiedendo ciò che NON SA. Questo codice di esempio serve a capire la struttura (struttura corretta) dell'EA.

E ciò che è incorporato in questo pezzo di codice è costruito su un principio di trading CLASSICO. Sia l'Expert Advisor stesso che gli esempi di codice servono per studiare i principi, e non per punzecchiare qualcuno o prenderlo a qualcosa....... Quello che sto chiedendo significa che non è chiaro. Dopo tutto, si DEVE capire teoricamente cosa e come. E poi creare, scolpire, inventare........

 
Potete dirmi se è possibile emettere un jpeg su un grafico?
 
keekkenen 25.02.2009 11:34 1) Per favore spiega, la funzione OrderSend(...) ha il tipo int, e tu la definisci come tipo bool, mentre il tipo bool non ha il valore -1, come è corretto? 2) In KimIV la funzione di apertura della posizione ripetuta è fatta attraverso for(...), mentre nella tua attraverso while(...). quale modo pensi sia migliore?
 

1. questo è un errore... res dovrebbe essere dichiarato come int e un'altra variabile di tipo bool dovrebbe essere aggiunta per restituire il valore di successo/fallimento dell'apertura dell'ordine...

2. Ho anche usato una delle implementazioni della funzione OpenPosition() di Igor prima, ma in seguito ho cambiato la funzione per rendere più facile catturare e segnalare gli errori...

il risultato è la seguente struttura

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);         
      }             
   }  
 
Se ho capito bene nella tua funzione, se ci sono continue requote, allora il numero di tentativi è illimitato, a differenza della funzione di Igor? È necessaria qualche limitazione in questo caso?
Motivazione: