초보자의 질문 MQL4 MT4 MetaTrader 4 - 페이지 129

 
테스터에서 테스트할 기호를 선택하는 방법을 알려주세요.
 int OnInit (){ return ( INIT_SUCCEEDED );}
 
Nikolay Gaylis :
테스터에서 테스트할 기호를 선택하는 방법을 알려주세요.

안 돼요. 설정에서 수동으로 만 선택하십시오.

물론 테스터에서 다른 문자에 대한 데이터를 요청할 수 있지만 이를 위해서는 데이터 동기화를 보장할 만큼 충분히 열심히 작업해야 합니다(테스터는 기본적으로 한 문자로 작동하기 때문에 이 작업을 수행하지 않습니다). 선택한 심볼이 아닌 다른 심볼에 대한 거래는 일반적으로 불가능합니다.

추신: 이것은 모두 MT4용입니다. MT5에서는 상황이 다릅니다.

 
EA OnTimer() EventSetTimer (1) 에서 작동합니다 .나는 많은 틱을 놓치고 있습니다. OnTick() 이벤트 는 여러 통화 쌍을 한 번에 분석하기 때문에 저에게 적합하지 않습니다. 심지어 주기의 Sleep(200) 도 시스템을 로드합니다... 어떻게 해야 합니까?
 

디컴파일 금지!

 
Nikolay Gaylis :
EA OnTimer() EventSetTimer(1) 에서 작동합니다 .나는 많은 틱을 놓치고 있습니다. OnTick() 이벤트 는 여러 통화 쌍을 한 번에 분석하기 때문에 저에게 적합하지 않습니다. 심지어 주기의 Sleep(200) 도 시스템을 로드합니다... 어떻게 해야 합니까?

EventSetMillisecondTimer()도 있습니다. 이 방법으로 OnTimer() 실행 빈도를 줄일 수 있습니다.

 
Vladislav Boyko :

EventSetMillisecondTimer()도 있습니다. 이 방법으로 OnTimer() 실행 빈도를 줄일 수 있습니다.

감사합니다, 시도해 보겠습니다...

 

안녕하세요.

테스트 중 강조 표시된 영역에 "Array out of range" 메시지가 나타납니다. 컴파일시 에러가 나지 않는데 에러의 본질은 무엇이며 어떻게 고칠 수 있나요?

이중 TD_Close=닫기[1];

for (int i=2; i<=Period_bars; i++)

{

if (ABS_High<높음[i]) ABS_High=높음[i];

}

경우 (TD_닫기>ABS_높음)

{

if ( OrdersTotal () <= 1 && newCandle != Time[0]) int tiket=OrderSend(Symbol(),OP_BUY,volume,Ask,3,sl,tp,"",magic,0);

그렇지 않으면 newCandle = 시간[0];

}

 
Andrey.Sabitov :

안녕하세요.

테스트 중 강조 표시된 영역에 "Array out of range" 메시지가 나타납니다. 컴파일시 에러가 나지 않는데 에러의 본질은 무엇이며 어떻게 고칠 수 있나요?

이중 TD_Close=닫기[1];

for (int i=2; i<=Period_bars; i++)

{

if (ABS_High<높음[i]) ABS_High=높음[i];

}

경우 (TD_닫기>ABS_높음)

{

if (OrdersTotal () <= 1 && newCandle != 시간[0]) int tiket=OrderSend(Symbol(),OP_BUY,volume,Ask,3,sl,tp,"",magic,0);

그렇지 않으면 newCandle = 시간[0];

}

Period_bars 는 <= Bars - 1이어야 합니다.

 

좋은 오후입니다! 다음 문제를 해결하도록 도와주세요. 간단한 Expert Advisor를 작성하려고 하는데 다음과 같은 상황이 발생했습니다. SL 값이 0이 아닌 다른 값으로 설정되면 거래가 전혀 열리지 않고 TP, Tstop 및 TrailingStep 함수가 전혀 작동하지 않습니다.

코드에서 수정해야 할 사항은 무엇입니까?

 //+------------------------------------------------------------------+
//|                                                           MA.mq4 |
//|                                                           Sergey |
//|                                              http://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright    "Sergey Karev"
#property link          "http://www.mql4.com"
#property description "Moving Average sample expert advisor"
//#property strict

#define MAGICMA   23101987
//--- Inputs
input double Lots              = 0.01 ; // Объем лота
input int     SL                = 0 ;     // Stop Loss
input int     TP                = 0 ;     // Take profit
input int     TStop             = 0 ;     // Пункты
input int     TrailingStep      = 0 ;     // Шаг TS в пунктах
input int     MA_per1           = 5 ;     // MA быстрая
input int     MA_per2           = 55 ;   // MA медленная
input int     Timeframe         = 60 ;   // Таймфрейм 
input double MaximumRisk       = 0.02 ;
input double DecreaseFactor    = 3 ;
input int     MovingShift       = 0 ;     // Cдвиг средней
input int     Shift             = 0 ;     // Сдвиг баров
input int     Magic_number      = 1987 ; // Если Magic = 0, то работает + ручные ордеры


bool          TSProfitOnly      = true ;
int           NumberOfTry       = 5 ;
bool          UseSound          = True ;
string        NameFileSound     = "expert.wav" ;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders( string symbol)
  {
   int buys= 0 ,sells= 0 ;
//---
   for ( int i= 0 ;i< OrdersTotal ();i++)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES )== false ) break ;
       if ( OrderSymbol ()== Symbol () && OrderMagicNumber ()==MAGICMA)
        {
         if ( OrderType ()== OP_BUY )  buys++;
         if ( OrderType ()== OP_SELL ) sells++;
        }
     }
//--- return orders volume
   if (buys> 0 ) return (buys);
   else        return (-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int     orders= HistoryTotal ();     // history orders total
   int     losses= 0 ;                   // number of losses orders without a break
//--- select lot size
   lot= NormalizeDouble ( AccountFreeMargin ()*MaximumRisk/ 1000.0 , 1 );
//--- calcuulate number of losses orders without a break
   if (DecreaseFactor> 0 )
     {
       for ( int i=orders- 1 ;i>= 0 ;i--)
        {
         if ( OrderSelect (i, SELECT_BY_POS , MODE_HISTORY )== false )
           {
             Print ( "Error in history!" );
             break ;
           }
         if ( OrderSymbol ()!= Symbol () || OrderType ()> OP_SELL )
             continue ;
         //---
         if ( OrderProfit ()> 0 ) break ;
         if ( OrderProfit ()< 0 ) losses++;
        }
       if (losses> 1 )
         lot= NormalizeDouble (lot-lot*losses/DecreaseFactor, 1 );
     }
//--- return lot size
   if (lot< 0.1 ) lot= 0.1 ;
   return (lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double ma1;
   double ma2;
   int     res;
   
//+------------------------------------------------------------------+
//| Приводим SL и TP к единым целым                                  |
//+------------------------------------------------------------------+   
   
   double sl= 0 , tp= 0 ;
   sl= NormalizeDouble (SL* Point (), _Digits );
   tp= NormalizeDouble (TP* Point (), _Digits );
   
//--- go trading only for first tiks of new bar
   if ( Volume [ 0 ]> 1 ) return ;
   
//--- get Moving Average 
   ma1= iMA ( NULL ,         Timeframe,   MA_per1, MovingShift,     MODE_SMMA ,         PRICE_CLOSE ,Shift);
   ma2= iMA ( NULL ,         Timeframe,   MA_per2, MovingShift,     MODE_SMMA ,         PRICE_CLOSE ,Shift);
//         имя символа,  таймфрейм,   период,  сдвиг средней,  метод усреднения, тип цены,   сдвиг

//--- sell conditions
   if (ma1 < ma2) //[1] - номер свечи
     {
      res= OrderSend ( Symbol (), OP_SELL ,Lots, Bid , 3 ,sl,tp, "" ,MAGICMA, 0 ,Red);
       return ;
     }
//--- buy conditions
   if (ma1 > ma2)
     {
      res= OrderSend ( Symbol (), OP_BUY ,Lots, Ask , 3 ,sl,tp, "" ,MAGICMA, 0 ,Blue);
       return ;
     }
//---
  }
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double ma1;
   double ma2;
   
//--- go trading only for first tiks of new bar
   if ( Volume [ 0 ]> 1 ) return ;
//--- get Moving Average 
   ma1= iMA ( NULL ,Timeframe,MA_per1,MovingShift, MODE_SMMA , PRICE_CLOSE ,Shift);
   ma2= iMA ( NULL ,Timeframe,MA_per2,MovingShift, MODE_SMMA , PRICE_CLOSE ,Shift);
//---
   for ( int i= 0 ;i< OrdersTotal ();i++)
     {
       if ( OrderSelect (i, SELECT_BY_POS , MODE_TRADES )== false ) break ;
       if ( OrderMagicNumber ()!=MAGICMA || OrderSymbol ()!= Symbol ()) continue ;
       //--- check order type 
       if ( OrderType ()== OP_BUY )
        {
         if (ma1 < ma2)
           {
             if (! OrderClose ( OrderTicket (), OrderLots (), Bid , 3 ,White))
               Print ( "OrderClose error " , GetLastError ());
           }
         break ;
        }
       if ( OrderType ()== OP_SELL )
        {
         if (ma1 > ma2)
           {
             if (! OrderClose ( OrderTicket (), OrderLots (), Ask , 3 ,White))
               Print ( "OrderClose error " , GetLastError ());
           }
         break ;
        }
     }
//---
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick ()
  {
//--- check for history and trading
   if ( Bars < 100 || IsTradeAllowed ()== false )
       return ;
//--- calculate open orders by current symbol
   if (CalculateCurrentOrders( Symbol ())== 0 ) CheckForOpen();
   else                                     CheckForClose();
//+------------------------------------------------------------------+
//| Trailing Stop / Step                                             |
//+------------------------------------------------------------------+

   double tr= 0 , ts= 0 , op= 0 , sl= 0 ,
   ask= NormalizeDouble ( Ask , _Digits ),
   bid= NormalizeDouble ( Bid , _Digits );
   
   tr= NormalizeDouble (TStop* Point (), _Digits );
   ts= NormalizeDouble (TrailingStep* Point (), _Digits ); // Приводим к единым величинам (включая центовые счета)
   
double ma2 = iMA ( NULL ,Timeframe,MA_per2,MovingShift, MODE_SMMA , PRICE_CLOSE ,Shift);
   
   for ( int i= OrdersTotal ()- 1 ; i>= 0 ; i--)
   {
       if ( OrderSelect (i, SELECT_BY_POS )== true )
      {
         if ( OrderSymbol ()== Symbol ())
         {
             if ( OrderMagicNumber ()==Magic_number) // Если Magic = 0, то работает + ручные ордеры
            {
               op= NormalizeDouble ( OrderOpenPrice (), _Digits );
               sl= NormalizeDouble ( OrderStopLoss (), _Digits );
               
               if ( OrderType ()== OP_BUY )
               {
                   if ((bid-op)>tr)
                   if ((bid-sl)>tr)
                   if ((bid-tr)>ma2)
                   if ( OrderModify ( OrderTicket (), OrderOpenPrice (), NormalizeDouble (ma2, _Digits ), OrderTakeProfit (), 0 , clrGreen )== false )
                   Print ( "Error BUY OrderModify" );
               }
               if ( OrderType ()== OP_SELL )
               {
                   if ((op-ask)>tr)
                   if ((sl-ask)>tr || sl== 0 )
                   if ((ask+tr)<ma2)
                   if ( OrderModify ( OrderTicket (), OrderOpenPrice (), NormalizeDouble (ma2, _Digits ), OrderTakeProfit (), 0 , clrGreen )== false )
                   Print ( "Error SELL OrderModify" );                  
               }
            }
         }
      }
   }
  }
//+----------------------------------------------------------------------+

MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
  • www.mql4.com
MQL4: automated forex trading, strategy tester and custom indicators with MetaTrader
 
Sergey_M_K :

좋은 오후입니다! 다음 문제를 해결하도록 도와주세요. 간단한 Expert Advisor를 작성하려고 하는데 다음과 같은 상황이 발생했습니다. SL 값이 0이 아닌 다른 값으로 설정되면 거래가 전혀 열리지 않고 TP, Tstop 및 TrailingStep 함수가 전혀 작동하지 않습니다.

코드에서 수정해야 할 사항은 무엇입니까?

오류를 찾기 위해 디버거를 사용합니까?