Logique d'apprentissage - page 11

 
OK, quelle est l'option correcte que vous proposez - avec toutes les erreurs traitées ?
 
gip:

Moi, d'un autre côté, je l'ai sorti d'un tas de code :

Une question : pourquoi des glissements ? Et 10 (nombre de répétitions) devrait être déplacé vers les variables globales.

lea:

Et celui-là ?

Score.
 

Il y a différents glissements. Ceux qui sont dans la boucle sont... Quand vous avez une fille assise là, vous devez le répéter dix fois et attendre qu'elle mette son rouge à lèvres. Quand une fille est assise, elle doit le répéter dix fois et attendre qu'elle se maquille. Et parfois le serveur ralentit. Tout ça pour le "vrai DC".

Se glisse après PlaySound, afin que les autres sons ne l'emportent pas, PlaySound interrompt le son du précédent.

Lesvariables globales sont astucieusement pondérées par le terminal. Et ce n'est pas nécessaire, l'algorithme externe devrait fonctionner normalement avec les ordres qui ne sont pas fermés.

 
gip:

Les variables globales sont astucieusement pondérées par le terminal.

Pas de terminal. Programmes. C'est-à-dire, dans la portée globale.

Oh, j'oubliais -- Rafraîchir les taux au début de la boucle après la capture du contexte, alors vous n'aurez pas besoin de manipuler Ask et Bid. Et d'autres valeurs aussi.

 

RefreshRates n'est pas là pour autre chose. Voici comment j'ai essayé de traiter les situations où OrderClose renvoie false, mais où l'ordre est effectivement clôturé. Après la pause et les RefreshRates vient OrderSelect(). Je ne sais pas comment elle est là, mais elle semble fonctionner.

Ask et Bid sont une vraie merveille, ils ont parfois besoin d'être normalisés :)

---

Une dizaine de répétitions et quoi pour les variables globales, je ne comprends pas. Ils sont au nombre de dix, avec une marge suffisante. Est-il externe ?

 

Et si l'ordre est clôturé dans une minute ? Vous ne pouvez pas battre ça avec un code. Il s'agit d'un échec de communication du terminal.

gip:

Je ne comprends pas les dix répétitions et le rôle des variables globales.

Il faut éviter les chiffres magiques et il est facile à configurer.
 

Elle réduit simplement le nombre d'échecs par un facteur de deux. Bien sûr, toutes les situations ne sont pas traitées exactement dans ce bloc. Si un ordre est fermé pendant une minute, le programme doit attendre tout ce temps. Ces attentes, même si elles sont coupées, retardent la boucle et tout se passe comme prévu à la fin.

---

> Pour éviter les chiffres magiques et les réglages faciles.

Ajuster ce dix ? Oui c'est avec une telle marge, qu'il est plus facile de changer le DC :) Et pour le bien de mégalot, si cela a dû, et peut être dans le code à corriger.

 

Il y a un conseiller. Nous devons le faire paraître décent.

//+------------------------------------------------------------------+
// открытие доп ордеров
// OrderTip - тип ордер который нужно открыть, imagic - маджик 
// с которым надо октрыть, exp - экспонент (на что умножать объем), 
//+------------------------------------------------------------------+
bool OpenDopOrder(int OrderTip, int imagic, double exp){
double iLots = NormalizeDouble((FindLastLot(imagic) * exp), Digits);

int ticket = 0;
int i = 0;
int KolvoPopitok = 10;
int err = 0;
if (OrderTip==OP_BUY) {
   color CL_Close=OrderColorBuy;
   string cmd = "BUY";
   //double Price = NormalizeDouble(Ask, Digits); 
   double Price = Ask; 
   } else {
   CL_Close=OrderColorSell;
   cmd = "SELL";
   //Price=NormalizeDouble(Bid, Digits);
   Price=Bid;
   }
   
         for (i = 0; i < KolvoPopitok; i++) {
         ticket = OrderSend(Symbol(), OrderTip, iLots, Price, M1_Slippage, 0, 0, M1_EaComment, imagic, 0, CL_Close);
         err = GetLastError();
         if(err>0){
         Comment("Ошибка открытия дополнительного ордера " + ErrorDescription(err));
         timeprev = Time[1];
         return(false);
         }
         if (err == 0){
         Comment("Дополнительный ордер " + cmd+" # " + ticket+ " создан"); 
         return(true);
         break;}
         if (!(err == 4 || err == 137 || err == 146 || err == 136)) break;
         Sleep(3000);
         }
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
// функция определения тренда
//+------------------------------------------------------------------+
int SignalRegr(){

   int x=0;
   
   string indicator_name = "i-Regr";
   
   double ma = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name, Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 0, 0);
   double ma1 = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name, Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 0, 1);   
   
   if (kanal==1){
   double m_up = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name, Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 1, 0);
   double m_d = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name, Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 2, 0);      
   if (ma>ma1 && Bid>m_d) x=1;
   if (ma<ma1  && Ask<m_up) x=-1;
   }
   
   if (kanal==0){
   if (ma>ma1) x=1;
   if (ma<ma1) x=-1;
   }   
   
   if (kanal==2){
   m_up = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name, Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 1, 0);
   m_d = iCustom(NULL, Mas_TF_Regr[TF_Regr], indicator_name,    Regr.degree1, Regr.kstd1, SPer, Regr.shift1, 2, 0);      
   if (ma>ma1 && Bid>m_d && Ask<m_up && forSignalRegr()==1) x=1;
   if (ma<ma1  && Ask<m_up && Bid>m_d && forSignalRegr()==-1) x=-1;
   }   
return(x);
}
//+------------------------------------------------------------------+
int forSignalRegr(){
int x=0;
   string indicator_name = "i-Regr";
   double ma = iCustom(NULL, Mas_TF_Regr[TFSmall], indicator_name, Regr.degree1mall, Regr.kstd1mall, SPermall, Regr.shift1mall, 0, 0);
   double ma1 = iCustom(NULL, Mas_TF_Regr[TFSmall], indicator_name, Regr.degree1mall, Regr.kstd1mall, SPermall, Regr.shift1mall, 0, 1); 
   double m_up = iCustom(NULL, Mas_TF_Regr[TFSmall], indicator_name, Regr.degree1mall, Regr.kstd1mall, SPermall, Regr.shift1mall, 1, 0);
   double m_d = iCustom(NULL, Mas_TF_Regr[TFSmall], indicator_name, Regr.degree1mall, Regr.kstd1mall, SPermall, Regr.shift1mall, 2, 0);      
   if (ma>ma1 && Bid>m_d && Ask<m_up ) x=1;
   if (ma<ma1  && Ask<m_up && Bid>m_d ) x=-1;
return(x);
}

//+------------------------------------------------------------------+
//динамичный лот
//+------------------------------------------------------------------+
double GetLot(double iLots, double iRisk){
   double Lots_New;
   string Symb   =Symbol();                    
   double One_Lot=NormalizeDouble(MarketInfo(Symb,MODE_MARGINREQUIRED), Digits);
   double Min_Lot=NormalizeDouble(MarketInfo(Symb,MODE_MINLOT), Digits);
   double Step   =NormalizeDouble(MarketInfo(Symb,MODE_LOTSTEP), Digits);
   double Free   =AccountFreeMargin();        

   if (iLots>0){                                       
   double Money=iLots*One_Lot;              
   if(Money<=AccountFreeMargin())         
   Lots_New=iLots;                      
   else                                   
   Lots_New=MathFloor(Free/One_Lot/Step)*Step;
   }

   else{                                       
   if (iRisk > 100)                     
   iRisk=100;                       
   if (iRisk==0)                       
   Lots_New=Min_Lot;                   
   else                                   
   Lots_New=MathFloor(Free*iRisk/100/One_Lot/Step)*Step;
   }

   if (Lots_New < Min_Lot)                    
   Lots_New=Min_Lot;                       
   if (Lots_New*One_Lot > AccountFreeMargin()){                                         
}

return(Lots_New);                             
}

//+----------------------------------------------------------------------------+
//|функция модификация ордера                                                  |
//|PriceOpen - цена открытия позиции, установки ордера                         |
//|SL - ценовой уровень стопа                                                  |
//|TP - ценовой уровень тейка                                                  |
//+----------------------------------------------------------------------------+
bool ModifyOrder(double PriceOpen=-1, double SL=0, double TP=0) {
  string Symb=Symbol();
  bool   Rez_Modify;
  int NumberOfTry=3;
  int PauseAfterError=10;

  int err, kolvo;

  if (PriceOpen<=0) PriceOpen=OrderOpenPrice();
  if (SL<0) SL=OrderStopLoss();
  if (TP<0) TP=OrderTakeProfit();
  
  PriceOpen=RoundToTickSize(PriceOpen);
  SL=RoundToTickSize(SL);
  TP=RoundToTickSize(TP);

  if (PriceOpen!=OrderOpenPrice() || SL!=OrderStopLoss() || TP!=OrderTakeProfit()) {
    for (kolvo=1; kolvo<=NumberOfTry; kolvo++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      if (NormalizeDouble(TP,Digits)!=OrderTakeProfit()) 
      Rez_Modify=OrderModify(OrderTicket(), NormalizeDouble(PriceOpen,Digits), NormalizeDouble(SL,Digits), NormalizeDouble(TP,Digits), 0, OrderColorModify);
      if (Rez_Modify) {
      Comment("Ордер # " + OrderTicket()+ " успешно модифицирован : TP "+DoubleToStr(TP, Digits));
      break;
      } else {
        err=GetLastError();
        Comment("Ошибка модификации ордера # " + OrderTicket()+ " : " +ErrorDescription(err)+" ("+err+"), попытка: "+kolvo);
        timeprev = Time[1];
        Sleep(1000*PauseAfterError);
      }
    }
  }
  return(Rez_Modify);
}
//+----------------------------------------------------------------------------+
//|для функция модификация ордера                                              |
//+----------------------------------------------------------------------------+
double RoundToTickSize(double price){
return(NormalizeDouble(MathRound(price/MarketInfo(Symbol(), 
MODE_TICKSIZE))*MarketInfo(Symbol(), 
MODE_TICKSIZE), MarketInfo(Symbol(), MODE_DIGITS)));
}
//+----------------------------------------------------------------------------+
Ce sont les fonctions qui en découlent. Il y a un moyen de le rendre décent
Dossiers :
prosto_m.mq4  21 kb
 

J'ai ajouté deux fonctions pour simplifier le travail

Le premier vérifie le type d'ordre et le second recherche le dernier ordre ouvert.

//+------------------------------------------------------------------+
//|                                     Функция контроля типа ордера |
//|                                Copyright © 2010, Victor Nicolaev |
//|                                            e-mail: vinin@mail.ru |
//| isOrderType(type);                                               |
//+------------------------------------------------------------------+
//| Параметер - проверяемый тип                                      |
//+------------------------------------------------------------------+
bool isOrderType(int type){
   int gOrderType[]={OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP};
   bool Res=false;
   for (int i=0;i<ArraySize(gOrderType);i++) {
      if (gOrderType[i]==type){
         Res=true;
         break;
      }
   }
   return(Res);
}

//+------------------------------------------------------------------+
//|                       Функция поиска последнего открытого ордера |
//|                               (поиск только по открытым ордерам) |
//|                                          Возвращает номер тикета |
//|                                Copyright © 2010, Victor Nicolaev |
//|                                            e-mail: vinin@mail.ru |
//| FindLastOpenTime(tip, imagic);                                   |
//+------------------------------------------------------------------+
//| Параметер - тип позиции и магик                                  |
//+------------------------------------------------------------------+

int FindLastOpenTime(int tip, int imagic) {
   int Res=-1;
   int lOrderOpenTime=-1;
   
   for (int i=OrdersTotal()-1; i>=0; i--) {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))   continue;
      if (OrderSymbol() != Symbol())                     continue;
      if (OrderMagicNumber() != imagic)                  continue;
      if (!(tip==-1 || isOrderType(tip)))                continue;

      if (lOrderOpenTime==-1) { 
         lOrderOpenTime=OrderOpenTime(); 
         Res=OrderTicket();
      } else if (lOrderOpenTime<OrderOpenTime()) {
         lOrderOpenTime=OrderOpenTime(); 
         Res=OrderTicket();
      }
   }
   return (Res);
}
//+------------------------------------------------------------------+
 

Une partie des fonctions retravaillées de l'auteur


//+------------------------------------------------------------------+
//функция подсчета открытых ордеров по типу и маджику
//tip - тип ордера БАЙ или СЕЛЛ, imagic - маджик номер
//возвращает кол-во открытых оредров
//+------------------------------------------------------------------+
int CountTrades(int tip, int imagic) {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      if (!OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))  continue;
      if (OrderSymbol() != Symbol())                        continue;
      if (OrderMagicNumber() != imagic)                     continue;
      if (!(tip==-1 || isOrderType(tip)))                   continue;
      
      count ++;

   }
   return (count);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//поиск последней цены
//tip - тип ордера БАЙ или СЕЛЛ, imagic - маджик номер
//возвращает цену открытия последнего открытого ордера
//+------------------------------------------------------------------+
double FindLastPrice(int tip, int imagic) {

   int ticket=FindLastOpenTime(tip, imagic);
   if (ticket==-1) return(-1);
   OrderSelect(ticket, SELECT_BY_TICKET);
   double order_price = OrderOpenPrice();

   return (order_price);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//поиск последнего лота
//imagic - маджик номер
//возвращает объем последнего открытого ордера
//+------------------------------------------------------------------+
double FindLastLot(int imagic) {

   int ticket=FindLastOpenTime(-1, imagic);
   if (ticket==-1) return(-1);
   OrderSelect(ticket, SELECT_BY_TICKET);
   double order_lot=OrderLots();

   return (order_lot);
}
//+------------------------------------------------------------------+
Raison: