Assista a como baixar robôs de negociação gratuitos
Encontre-nos em Twitter!
Participe de nossa página de fãs
Script interessante?
Coloque um link para ele, e permita que outras pessoas também o avaliem
Você gostou do script?
Avalie seu funcionamento no terminal MetaTrader 5
Visualizações:
175
Avaliação:
(6)
Publicado:
Freelance MQL5 Precisa de um robô ou indicador baseado nesse código? Solicite-o no Freelance Ir para Freelance

Desenvolvi esse indicador para oferecer uma alternativa aos métodos de média móvel padrão no indicador Bollinger Bands do MetaTrader 5, que oferece apenas o método "simples". Com meu indicador, os usuários têm a opção de selecionar métodos adicionais, incluindo Exponential, Smoothed e LinearWeighted.

Para utilizar esse indicador, é necessário colocá-lo em um diretório (no Windows) semelhante ao seguinte caminho:

C:\Users\lucas\AppData\Roaming\MetaQuotes\Terminal\Indicators\Examples

Recursos adicionados:

um


É definido como zero por padrão:

dois


Exemplo de execução que opta pela média de LinearWeighted:


árvore quatro


CODE:

//+------------------------------------------------------------------+
//|BBPersonalizada.mq5 |
//|Lucas Vidal
//|https://www.mql5.com
//+------------------------------------------------------------------+
#property copyright   "Lucas Vidal"
#property link        "https://www.mql5.com/pt/users/lucasmoura00"
#property description "Bollinger Bands Personalizada"
#include <MovingAverages.mqh>
//---
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_color1  LightSeaGreen
#property indicator_type2   DRAW_LINE
#property indicator_color2  LightSeaGreen
#property indicator_type3   DRAW_LINE
#property indicator_color3  LightSeaGreen
#property indicator_label1  "Bands middle"
#property indicator_label2  "Bands upper"
#property indicator_label3  "Bands lower"
//--- parâmetros de entrada
enum MovingAverageMethod {
    Simple,    // 0
    Exponential,  // 1
    Smoothed,     // 2
    LinearWeighted  // 3
};
input MovingAverageMethod InpMaMethod = Simple; // Método da Média Móvel
input int     InpBandsPeriod=20;       // Período
input int     InpBandsShift=0;         // Turno
input double  InpBandsDeviations=2.0;  // Desvio
//--- variáveis globais
int           ExtBandsPeriod,ExtBandsShift;
double        ExtBandsDeviations;
int           ExtPlotBegin=0;
//--- buffer de indicador
double        ExtMLBuffer[];
double        ExtTLBuffer[];
double        ExtBLBuffer[];
double        ExtStdDevBuffer[];
//+------------------------------------------------------------------+
//| Função de inicialização do indicador personalizado
//+------------------------------------------------------------------+
void OnInit()
  {
//--- verificação dos valores de entrada
   if(InpBandsPeriod<2)
     {
      ExtBandsPeriod=20;
      PrintFormat("Incorrect value for input variable InpBandsPeriod=%d. Indicator will use value=%d for calculations.",InpBandsPeriod,ExtBandsPeriod);
     }
   else
      ExtBandsPeriod=InpBandsPeriod;
   if(InpBandsShift<0)
     {
      ExtBandsShift=0;
      PrintFormat("Incorrect value for input variable InpBandsShift=%d. Indicator will use value=%d for calculations.",InpBandsShift,ExtBandsShift);
     }
   else
      ExtBandsShift=InpBandsShift;
   if(InpBandsDeviations==0.0)
     {
      ExtBandsDeviations=2.0;
      PrintFormat("Incorrect value for input variable InpBandsDeviations=%f. Indicator will use value=%f for calculations.",InpBandsDeviations,ExtBandsDeviations);
     }
   else
      ExtBandsDeviations=InpBandsDeviations;
//--- definir buffers
   SetIndexBuffer(0,ExtMLBuffer);
   SetIndexBuffer(1,ExtTLBuffer);
   SetIndexBuffer(2,ExtBLBuffer);
   SetIndexBuffer(3,ExtStdDevBuffer,INDICATOR_CALCULATIONS);
//--- definir rótulos de índice
   PlotIndexSetString(0,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Middle");
   PlotIndexSetString(1,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Upper");
   PlotIndexSetString(2,PLOT_LABEL,"Bands("+string(ExtBandsPeriod)+") Lower");
//--- nome do indicador
   IndicatorSetString(INDICATOR_SHORTNAME,"Bollinger Bands");
//--- índices desenham configurações de início
   ExtPlotBegin=ExtBandsPeriod-1;
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,ExtBandsPeriod);
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,ExtBandsPeriod);
   PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,ExtBandsPeriod);
//--- indexa as configurações de deslocamento
   PlotIndexSetInteger(0,PLOT_SHIFT,ExtBandsShift);
   PlotIndexSetInteger(1,PLOT_SHIFT,ExtBandsShift);
   PlotIndexSetInteger(2,PLOT_SHIFT,ExtBandsShift);
//--- número de dígitos do valor do indicador
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits+1);
  }
//+------------------------------------------------------------------+
//| Cálculo da média móvel|
//+------------------------------------------------------------------+
double CalculateMovingAverage(int position, int period, const double &price[]) {
    switch(InpMaMethod) {
        case Simple:
            return SimpleMA(position, period, price);
        case Exponential:
            // Corrigindo a chamada da função iMA com os parâmetros corretos
            return iMA(NULL, 0, period, 0, MODE_EMA, PRICE_CLOSE);
        case Smoothed:
            // Implemente sua função SMMA aqui
            break;
        case LinearWeighted:
            return LinearWeightedMA(position, period, price);
    }
    return 0; // Retorno padrão em caso de método indefinido
}

//+------------------------------------------------------------------+
//| Bandas de Bollinger|
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[])
  {
   if(rates_total<ExtPlotBegin)
      return(0);
//--- os índices desenham as configurações do begin, quando recebemos o begin anterior
   if(ExtPlotBegin!=ExtBandsPeriod+begin)
     {
      ExtPlotBegin=ExtBandsPeriod+begin;
      PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,ExtPlotBegin);
      PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,ExtPlotBegin);
      PlotIndexSetInteger(2,PLOT_DRAW_BEGIN,ExtPlotBegin);
     }
//--- cálculo inicial
   int pos;
   if(prev_calculated>1)
      pos=prev_calculated-1;
   else
      pos=0;
//--- ciclo principal
   for(int i=pos; i<rates_total && !IsStopped(); i++)
     {
      //--- linha do meio
      ExtMLBuffer[i]=CalculateMovingAverage(i, ExtBandsPeriod, price);
      //--- calcular e anotar o StdDev
      ExtStdDevBuffer[i]=StdDev_Func(i,price,ExtMLBuffer,ExtBandsPeriod);
      //--- linha superior
      ExtTLBuffer[i]=ExtMLBuffer[i]+ExtBandsDeviations*ExtStdDevBuffer[i];
      //--- linha inferior
      ExtBLBuffer[i]=ExtMLBuffer[i]-ExtBandsDeviations*ExtStdDevBuffer[i];
     }
//--- OnCalculate concluído. Retorna o novo prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Calcular o desvio padrão|
//+------------------------------------------------------------------+
double StdDev_Func(const int position,const double &price[],const double &ma_price[],const int period)
  {
   double std_dev=0.0;
//--- calcular o StdDev
   if(position>=period)
     {
      for(int i=0; i<period; i++)
         std_dev+=MathPow(price[position-i]-ma_price[position],2.0);
      std_dev=MathSqrt(std_dev/period);
     }
//--- retornar o valor calculado
   return(std_dev);
  }
//+------------------------------------------------------------------+




Traduzido do inglês pela MetaQuotes Ltd.
Publicação original: https://www.mql5.com/en/code/49464

Geometric Moving Average Geometric Moving Average

Versão MQL5 da média móvel geométrica.

Get Nth Active Trade from the end in MT5 Get Nth Active Trade from the end in MT5

Esse EA examinará todas as negociações abertas e, em seguida, imprimirá a enésima negociação a partir do final

OHLC Candles with Ask and Bid OHLC Candles with Ask and Bid

Um gráfico de velas que conecta o preço de venda e o preço de compra com a máxima e a mínima das velas

Simple_Three_Inside_Pattern_EA Simple_Three_Inside_Pattern_EA

Um Expert Advisor simples que negocia quando o preço forma o padrão "Three From Within".