Perguntas de Iniciantes MQL4 MT4 MetaTrader 4 - página 129

 
Você pode me dizer como selecionar o símbolo a ser testado no testador?
int OnInit(){return(INIT_SUCCEEDED);}
 
Nikolay Gaylis:
Por favor, informe como selecionar um símbolo no testador para testes em

Você não pode. Somente selecionar manualmente nas configurações.

No testador, é claro, você pode solicitar dados sobre outros símbolos, mas para isso você terá que trabalhar o suficiente para garantir a sincronização dos dados (o próprio testador não o fará por você, porque por padrão ele trabalha com um símbolo). O comércio sobre o símbolo, diferente do selecionado, em geral, não pode.

P. S. Tudo isso é para o MT4. Na MT5 a situação é diferente.

 
A EA trabalha comOnTimer()EventSetTimer(1).I miss many ticks. O eventoOnTick() não é adequado para mim, pois analiso vários pares de moedas de uma só vez ... Até mesmo Sleep(200) in loop irá carregar o sistema...O que fazer?
 

NÃO É PERMITIDA A DESCOMPILAÇÃO!

 
Nikolay Gaylis:
O Expert Advisor trabalha emOnTimer() EventSetTimer(1). Eu sinto falta de muitos carrapatos. O eventoOnTick() não me serve porque analiso vários pares de moedas ao mesmo tempo ... Até mesmo Sleep(200) in loop irá carregar o sistema...O que fazer?

Há também o EventSetMillisecondTimer() - pode reduzir a periodicidade de execução do OnTimer().

 
Vladislav Boyko:

Há também o EventSetMillisecondTimer() - para que você possa reduzir a periodicidade do OnTimer().

Obrigado, vou tentar...

 

Boa tarde.

A mensagem "Array out of range" aparece no espaço alocado durante o teste. Não indica um erro durante a compilação. Qual é a essência do erro e como podemos corrigi-lo?

duplo TD_Close=Close[1];

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

{

if (ABS_High<High[i]) ABS_High=High[i];

}

se (TD_Fechar>ABS_High)

{

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

senão newCandle = Tempo[0];

}

 
Andrey.Sabitov:

Boa tarde.

A mensagem "Array out of range" aparece no local destacado durante o teste. Não indica um erro durante a compilação. Qual é a essência do erro e como podemos corrigi-lo?

duplo TD_Close=Close[1];

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

{

if (ABS_High<High[i]) ABS_High=High[i];

}

se (TD_Fechar>ABS_High)

{

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

senão newCandle = Tempo[0];

}

Período_barras deve ser <= Barras - 1

 

Olá, amigos, ajudem-me a resolver o seguinte problema: estou tentando escrever um simples Expert Advisor e me deparei com o seguinte: se o SL é definido para um valor diferente de 0, então as negociações não são abertas, assim como as funções TP, TStop e TrailingStep não funcionam de forma alguma.

O que devo consertar no código?

//+------------------------------------------------------------------+
//|                                                           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:

Olá, amigos, ajudem-me a resolver o seguinte problema: estou tentando escrever um simples Expert Advisor e me deparei com o seguinte: se o SL é definido com um valor diferente de 0, então as negociações não são abertas, assim como o TP, TStop e TrailingStep não funcionam de forma alguma.

O que devo consertar no código?

Você usa um depurador para procurar por erros?
Razão: