Quaisquer perguntas de recém-chegados sobre MQL4 e MQL5, ajuda e discussão sobre algoritmos e códigos - página 1293

 
Aleksei Stepanenko:

A partir de dois pontos em uma linha, você pode encontrar o preço de um terceiro ponto arbitrário nessa linha, também no futuro (e vice-versa).

Obrigado! Vou tentar.

P.S. A única coisa. Não entendo de relance. Será que funcionará no Expert Advisor, no MT4?

 
Olá, colegas especialistas. Preciso de sua ajuda para corrigir o indicador. A essência do indicador é a seguinte. Calcule o valor do aumento do preço em relação à barra anterior. Para zero leva uma barra estelar. Ou seja, o preço de abertura é igual ao preço de fechamento. Ao compilar sem erros, mas ao testar um erro na linha 80 20 caracteres. A linha de sinal também é desenhada incorretamente. Mas acho que esta é a razão para o cálculo incorreto do tampão principal. Por favor, ajude-me a consertá-lo.
//+------------------------------------------------------------------+
//|                                                         MSBB.mq4 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

#include <MovingAverages.mqh>

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  clrGreen
#property indicator_color2  clrRed
#property  indicator_width1  1
input int            InpMSBBPeriod=3;        // Period
input ENUM_MA_METHOD InpMSBBMethod=MODE_SMA;  // Method
//--- indicator buffers
double         ExtMSBBBuffer[];
double         ExtTempBuffer[];
double         ExtPriceBuffer[];
double         ExtSignalBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- indicator buffers mapping
   IndicatorDigits(Digits-2);
//--- drawing settings
   IndicatorBuffers(4);
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(0,ExtMSBBBuffer);
   SetIndexBuffer(1,ExtSignalBuffer);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(2,ExtTempBuffer);
   SetIndexBuffer(2,ExtPriceBuffer);
   SetIndexDrawBegin(1,InpMSBBPeriod);
//--- name for DataWindow and indicator subwindow label
   IndicatorShortName("MSBB("+IntegerToString(InpMSBBPeriod)+")");
   SetIndexLabel(0,"MSBB");
   SetIndexLabel(1,"Signal");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   int    i;//limit;
//------
   if(rates_total<=InpMSBBPeriod || InpMSBBPeriod<=2)
      return(0);
   /*//--- counting from 0 to rates_total
      ArraySetAsSeries(ExtMSBBBuffer,false);
      ArraySetAsSeries(ExtSignalBuffer,false);
      ArraySetAsSeries(open,false);
      ArraySetAsSeries(high,false);
      ArraySetAsSeries(low,false);
      ArraySetAsSeries(close,false);*/
//---
  // limit=rates_total-prev_calculated;
   //if(prev_calculated>0)
     // limit++;
//--- typical price and its moving average
   for(i=0; i<rates_total; i++)
     {
      ExtTempBuffer[i] = NormalizeDouble((close[i]-open[i])/Point(),2);
      ExtPriceBuffer[i] = NormalizeDouble((close[i+1]-open[i+1])/Point(),2);
      //ExtMSBBBuffer[i]=price_open+ExtTempBuffer[i];
      //Print("ExtPriceBuffer[i] = ", ExtPriceBuffer[i]);
      if(ExtTempBuffer[i]==0)
         ExtMSBBBuffer[i]=0.0;
      if(ExtPriceBuffer[i]>0 && ExtTempBuffer[i]>0)
        {
         double price_open = NormalizeDouble((open[i]-open[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-close[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i] = 0.0;
         if((price_open<0 && price_close<0)||(price_open>0 && price_close>0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]>0 && ExtTempBuffer[i]<0)
        {
         double price_open = NormalizeDouble((open[i]-close[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-open[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i] = 0.0;
         if((price_open>0 && price_close>0)||(price_open<0 && price_close<0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]<0 && ExtTempBuffer[i]<0)
        {
         double price_open = NormalizeDouble((open[i]-open[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-close[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i]=0.0;
         if((price_open<0 && price_close<0)||(price_open>0 && price_close>0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]<0 && ExtTempBuffer[i]>0)
        {
         double price_open = NormalizeDouble((open[i]-close[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-open[i+1])/Point(),2);
         if((price_open>0 && price_close<0)||(price_open<0 && price_close>0))
            ExtMSBBBuffer[i]=0.0;
         if((price_open>0 && price_close>0)||(price_open<0 && price_close<0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      //--- signal line counted in the 2-nd buffer
      //ExtSignalBuffer[i]=iMAOnArray(ExtMSBBBuffer,0,InpMSBBPeriod,0,InpMSBBMethod,0);
      SimpleMAOnBuffer(rates_total,prev_calculated,1,InpMSBBPeriod+2,ExtMSBBBuffer,ExtSignalBuffer);
      Print ("ExtSignalBuffer = ", ExtSignalBuffer[i]);
      //--- done
     }
   /* if(ExtPriceBuffer[i]>0||ExtPriceBuffer[i]<0)
     {
      ExtMSBBBuffer[i] = ExtPriceBuffer[i]+ExtTempBuffer[i];
      Print("ExtMSBBBuffer[i] = ", ExtMSBBBuffer[i]);
     }
   if(ExtPriceBuffer[i]==0)
     {
      ExtMSBBBuffer[i] = 0.0;
      Print("ExtMSBBBuffer[i] = ", ExtMSBBBuffer[i]);
     }
   }*/
//---
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
 
Como descobrir o número do agente local no qual o teste único está sendo realizado?
 

Boa tarde!

Você poderia, por favor, ajudar com um EA?

Ele faz negócios em sinais RSI de 30 e 70 níveis na direção apropriada, cria uma grade.

Eu tenho uma espécie de % de parada de perda, mas de tempos em tempos as encomendas estão suspensas e não fecharão até que eu as feche manualmente ou até que eu venda o depósito.

Isto é, tais ordens são abertas quando o preço já foi movido em 5000 pips e mais, mas ainda estão penduradas no vermelho.

Você precisa encontrar o erro. Se isso não for possível, devemos inserir um Stop Loss in pips separado em nossa EA.

Eu tentei combinar 2 EAs em um, mas não funcionou com minhas habilidades.

Arquivos anexados:
 

Olá. Você pode me dar uma dica? Preciso obter o número de pontos passados no último tick. Mas eu não consigo.

#property indicator_chart_window
#property indicator_buffers 1
double ExtMapBuffer[];
double dOldPriceEURUSD, dNewPriceEURUSD;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorDigits(5);
   SetIndexBuffer(0, ExtMapBuffer);
   SetIndexEmptyValue(0,0.0);        
   dOldPriceEURUSD=iClose("EURUSD",0,0);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   dNewPriceEURUSD=iClose("EURUSD",0,0);
   double delta=NormalizeDouble(dOldPriceEURUSD-dNewPriceEURUSD,5);
   ExtMapBuffer[0] = delta;
   Alert(delta);     
   dOldPriceEURUSD=dNewPriceEURUSD;
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
Forallf:

Olá. Você pode me dar uma dica? Preciso obter o número de pontos passados no último tick. Mas não está funcionando.

Tente isto.

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
double ExtMapBuffer[];
double dOldPriceEURUSD, dNewPriceEURUSD;
double delta;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorDigits(5);
   SetIndexBuffer(0, ExtMapBuffer);
   SetIndexEmptyValue(0, 0.0);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   dNewPriceEURUSD = NormalizeDouble(Close[0],Digits);
   delta = dOldPriceEURUSD - dNewPriceEURUSD;
   Comment(" delta = ", DoubleToStr(delta ,5));
   dOldPriceEURUSD = dNewPriceEURUSD;
   ExtMapBuffer[0] = delta;
 Alert(" delta = ", DoubleToStr(delta ,5));
   return(rates_total);
  }
//+------------------------------------------------------------------+
Domain Registration Services
  • www.registryrocket.com
Get a unique domain name plus our FREE value-added services to help you get the most from it. Call it a "dot-com name," a URL, or a domain. Whatever you call it, it's the cornerstone of your online presence, and we make getting one easy. Simply enter the name you want in the search field above, and we'll tell you instantly whether the name is...
 
Александр:

Tente desta forma.

Obrigado!
 

Olá novamente.
Por favor, preste atenção à pergunta de um novato.
Preciso apontar erros no código, porque no testador, o Assessor Especialista não abre ordens...
O compilador não mostra erros ou avisos, o mesmo diário não mostra erros...

extern double Lot=0.1;            
extern int Slippage = 3;
extern int TakeProfit = 30;
extern int StopLoss   = 30;
extern int MA_Smoth_S = 60;
extern int MA_Smoth_B = 12;
extern int MA_Simpl_S = 3;
extern int MA_Simpl_B = 1;
int start()
         {
          //___________________

          double SL, TP;
          int MA_Simpl_S_Cl,      //
              MA_Simpl_S_Op,      //
              MA_Simpl_B_Cl,      //
              MA_Simpl_B_Op;      //
         
          //________________

          //------------

          SL=NormalizeDouble(Bid-StopLoss*Point,Digits);      // 
          TP=NormalizeDouble(Bid+TakeProfit*Point,Digits);    //
          SL = StopLoss;                        
          TP = TakeProfit;
          if(_Digits==5 || _Digits==3)
            {
             SL = SL*10;
             TP = TP*10;
             return(0);
            }
            
          //_______________

          MA_Smoth_S = iMA(NULL,0,60,0,MODE_SMMA,PRICE_CLOSE,1);
          MA_Smoth_B = iMA(NULL,0,12,0,MODE_SMMA,PRICE_CLOSE,1);
          MA_Simpl_S = iMA(NULL,0,3,0,MODE_SMA,PRICE_CLOSE,1);
          MA_Simpl_B = iMA(NULL,0,1,0,MODE_SMA,PRICE_CLOSE,1);
          MA_Simpl_S_Cl = iMA(NULL,0,3,0,MODE_SMA,PRICE_CLOSE,1);
          MA_Simpl_S_Op = iMA(NULL,0,3,0,MODE_SMA,PRICE_CLOSE,2);
          MA_Simpl_B_Cl = iMA(NULL,0,1,0,MODE_SMA,PRICE_CLOSE,1);
          MA_Simpl_B_Op = iMA(NULL,0,1,0,MODE_SMA,PRICE_CLOSE,2);
          
          //______________________

          while(MA_Smoth_B > MA_Smoth_S)
               {
                if(MA_Simpl_B_Op < MA_Simpl_S_Op && MA_Simpl_B_Cl > MA_Simpl_S_Cl)
                  {
                   bool check = OrderSend(Symbol(),OP_BUY,Lot,NormalizeDouble(Ask, Digits),Slippage,SL,TP,"Buy",0,0,clrGreen);
                   return(0);
                  }
               }
               
          //_____________________

          while(MA_Smoth_S > MA_Smoth_B)
               {
                if(MA_Simpl_B_Op > MA_Simpl_S_Op && MA_Simpl_B_Cl < MA_Simpl_S_Cl)
                  {
                   check = OrderSend(Symbol(),OP_SELL,Lot,NormalizeDouble(Ask, Digits),Slippage,SL,TP,"Sell",0,0,clrRed);
                   return(0);
                  }   
               }     
          return(0);
         } 
 

Bom dia a todos!

Estou tentando de mql4 a mql5.

Pergunta: Por que o mql5 calcula e exibe alguma expressão desconhecida para mim como 2,99999999 - (menos) 05 ao invés da diferença entre o preço atual e o valor da variável Hay, que deveria ser <1 (como em mql4)?

Como devo fazer o mql5 calcular corretamente a diferença entre esses valores? Eu normalizo todos os valores usando NormalizeDouble(), mas os valores acima

valores são exibidos inalterados. Isto é estranho para mim, pois ambos os valores são do tipo doble

Obrigado a todos por sua ajuda.

#include <Trade\Trade.mqh>                                        
int tm, s1 ;                                    
double P=SymbolInfoDouble(Symbol(),SYMBOL_BID),S=P+0.0030,T=P-0.0010,Lou,Hay,DL=0.0030; 
CTrade            m_Trade;                 //структура для выполнения торговых операций
//=============================================================================================================
void OnTick()
  {
Print("===============",SymbolInfoDouble(Symbol(),SYMBOL_BID) - Hay,"===Hay====",Hay,"===SymbolInfoDouble()====",SymbolInfoDouble(Symbol(),SYMBOL_BID)); 

m_Trade.Sell(0.1,Symbol(),P,S,T);
Hay=SymbolInfoDouble(Symbol(),SYMBOL_BID);

   }


 
MrBrooklin:

Olá Ivan, aqui ninguém repreende os novatos, pelo contrário, eles tentam ajudar. Eu mesmo sou um principiante. Agora, em relação à sua pergunta. Várias posições são abertas porque o cheque para abrir uma posição foi realizado, mas o cheque foi esquecido de parar. O operador retorna o controle ao programa de chamadas (retirado da Referência MQL5).

Devemos acrescentar o retorno ao código do Expert Advisor (destacado em amarelo):

Além disso, para evitar que o compilador gere avisos, mais uma condição deve ser adicionada nas condições de abertura da posição Comprar e Vender para verificar OrderSend(mrequest,mresult). Esta condição é definida pelo se operador e deve ter este aspecto:

Mais uma coisa deve ser levada em conta. s vezes, ao passar de um dia de negociação para outro às 23:59:59, uma posição aberta se fecha e então, às 00:00:00, uma nova posição se abre. Isto é o chamado rollover fechado e rollover aberto, que depende do negociante forex em particular e de suas condições comerciais. Procure no fórum, eu tenho algumas informações sobre ele em algum lugar.

Atenciosamente, Vladimir.


Olá.

Muito obrigado por sua resposta! Mas eu não entendo por que preciso do retorno do operador? Há duas condições neste código e a verificação deve parar quando uma delas for cumprida.

//--- есть ли открытые позиции?
   bool Buy_opened=false;  // переменные, в которых будет храниться информация 
   bool Sell_opened=false; // о наличии соответствующих открытых позиций

   if(PositionSelect(_Symbol)==true) // есть открытая позиция
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)  // если истина, выполняем условие 1
        {
         Buy_opened=true;  //это длинная позиция
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)  // иначе выполняем условие 2
        {
         Sell_opened=true; // это короткая позиция
        }
     }
Ou não é?
Razão: