학습 논리 - 페이지 11

 
글쎄, 당신은 모든 오류를 처리하는 올바른 옵션을 무엇을 제공합니까?
 
gip :

다음은 코드 더미에서 얻은 것입니다.

한 가지 질문 - 왜 미끄러지는가? 글쎄, 10ku (반복 횟수) 전역 변수 에서 스레드를 꺼냅니다.

레아 :

이 옵션은 어떻습니까?

더 읽기
 

다양한 슬립이 있습니다. 사이클에 있는 것들은... 음, 일반적으로 상황은 이렇습니다. 거래 데스크가 있거나 시장이 고요한 경우 첫 번째 시도에서 주문이 마감됩니다. 소녀는 앉아 있을 때 10번을 반복해야 하고 심지어 입술을 칠할 때까지 기다려야 합니다. 그리고 때때로 서버가 느려집니다. 이것은 모두 "실제 DC"를 위한 것입니다.

PlaySound 이후에 미끄러져 다른 소리가 가려지지 않도록 PlaySound는 이전 소리를 중단합니다.

전역 변수 는 터미널을 능숙하게 평가합니다. 예, 필요하지 않습니다. 외부 알고리즘은 일반적으로 마감되지 않은 주문을 처리해야 합니다.

 
gip :

전역 변수는 터미널을 능숙하게 평가합니다.

터미널이 아닙니다. 프로그램들. 즉, 전역 범위 에서 .

아, 나는 또한 잊었다 - 컨텍스트 캡처 후 사이클의 시작 부분에 RefreshRates, 그러면 요청 및 입찰을 엉망으로 만들 필요가 없습니다. 예, 다른 값도 마찬가지입니다.

 

RefreshRates는 다른 사람을 위해 존재하지 않습니다. 그래서 OrderClose가 false를 반환하는 상황을 처리하려고 했지만 실제로는 주문이 마감되었습니다. 일시 중지 및 RefreshRates 후에 OrderSelect()가 제공됩니다. 내부는 어떨지 모르겠지만 작동하는 것 같습니다.

Ask 및 Bid는 일반적으로 깃털의 기적이며 때때로 정규화해야 합니다. :)

---

약 10번의 반복과 전역 변수 에서 내가 이것을 이해하지 못한 이유. 여백이 있는 10개가 있습니다. 외부에서 또는 무엇?

 

그리고 주문이 잠시 닫히면? 코드로 이 상황을 이길 수 없습니다. 터미널 통신 오류입니다.

gip :

약 10번의 반복과 전역 변수에서 내가 이것을 이해하지 못한 이유.

마법의 숫자를 피하고 설정하기 쉬운 덕입니다.
 

단순히 실패 횟수를 몇 배 줄여줍니다. 물론 이 블록의 모든 상황이 해결되는 것은 아닙니다. 주문이 1분 동안 닫히면 프로그램은 그 시간 동안 기다려야 합니다. 이러한 기대는 심지어 깨진 기대조차도 주기를 지연시키고 결국 모든 것이 원래대로 나타납니다.

---

> 마법의 숫자를 피하고 쉽게 설정할 수 있습니다.

이 10개를 사용자 정의하시겠습니까? 예, DC를 변경하기가 더 쉽도록 마진이 있습니다. :) 그리고 메가로트를 위해 실제로 발생한 경우 코드에서 수정할 수 있습니다.

 

한 명의 고문이 있습니다. 좋은 모양으로 다시 가져와야 합니다.

 //+------------------------------------------------------------------+
// открытие доп ордеров
// 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)));
}
//+----------------------------------------------------------------------------+
이것들은 그것의 기능입니다. 이 모든 것을 소화 가능한 형태로 가져오는 것이 가능합니다.
파일:
prosto_m.mq4  21 kb
 

작업을 단순화하는 두 가지 기능 추가

하나는 주문 유형 을 확인하고 두 번째는 마지막으로 열린 주문을 찾습니다.

 //+------------------------------------------------------------------+
//|                                     Функция контроля типа ордера |
//|                                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);
}
//+------------------------------------------------------------------+
 

변환된 저작 기능의 일부


//+------------------------------------------------------------------+
//функция подсчета открытых ордеров по типу и маджику
//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);
}
//+------------------------------------------------------------------+