MQL5 — Indicadores Técnicos
Referência dos 38 indicadores técnicos nativos do MQL5: iMA, iRSI, iMACD, iBands, iATR, iADX, iStochastic, iSAR, iCCI, iIchimoku e outros — com assinaturas, parâmetros e exemplos de uso com CopyBuffer.
MQL5 — Indicadores Técnicos
O MQL5 disponibiliza 38 indicadores técnicos nativos acessíveis em Expert Advisors e indicadores customizados. Todos seguem o mesmo padrão: a função retorna um handle e os valores são lidos via CopyBuffer().
Event handlers: MQL5 — Event Handlers | Indicadores customizados: Indicadores Customizados
Padrão de Uso
Todos os indicadores técnicos seguem o mesmo padrão de 3 etapas:
// 1. Criar handle em OnInit()
int handle = iMA(_Symbol, PERIOD_CURRENT, 21, 0, MODE_EMA, PRICE_CLOSE);
if(handle == INVALID_HANDLE)
{
Print("Erro ao criar handle: ", GetLastError());
return(INIT_FAILED);
}
// 2. Ler valores em OnTick() ou OnCalculate()
double buffer[];
ArraySetAsSeries(buffer, true); // índice 0 = valor mais recente
int copied = CopyBuffer(handle, 0, 0, 3, buffer); // 3 últimos valores
if(copied < 3) return; // dados insuficientes
double valorAtual = buffer[0]; // barra atual (em formação)
double valorAnterior = buffer[1]; // barra fechada anterior
double valorPrevio = buffer[2]; // dois barras atrás
// 3. Liberar em OnDeinit()
IndicatorRelease(handle);CopyBuffer — assinatura
int CopyBuffer(int indicator_handle, // handle do indicador
int buffer_num, // índice do buffer (0, 1, 2...)
int start_pos, // posição inicial (0 = mais recente)
int count, // quantidade de valores
double &buffer[]) // array de destinoRetorna o número de valores copiados ou -1 em caso de erro.
Lista Completa dos 38 Indicadores
| Função | Descrição | Buffers |
|---|---|---|
iAC | Accelerator Oscillator | 1 |
iAD | Accumulation/Distribution | 1 |
iADX | Average Directional Index | 3 |
iADXWilder | ADX by Welles Wilder | 3 |
iAlligator | Alligator | 3 |
iAMA | Adaptive Moving Average | 1 |
iAO | Awesome Oscillator | 1 |
iATR | Average True Range | 1 |
iBearsPower | Bears Power | 1 |
iBands | Bollinger Bands | 3 |
iBullsPower | Bulls Power | 1 |
iCCI | Commodity Channel Index | 1 |
iChaikin | Chaikin Oscillator | 1 |
iCustom | Indicador customizado | N |
iDEMA | Double Exponential Moving Average | 1 |
iDeMarker | DeMarker | 1 |
iEnvelopes | Envelopes | 2 |
iForce | Force Index | 1 |
iFractals | Fractals | 2 |
iFrAMA | Fractal Adaptive Moving Average | 1 |
iGator | Gator Oscillator | 4 |
iIchimoku | Ichimoku Kinko Hyo | 5 |
iBWMFI | Market Facilitation Index (B.Williams) | 1 |
iMomentum | Momentum | 1 |
iMFI | Money Flow Index | 1 |
iMA | Moving Average | 1 |
iOsMA | OsMA (MACD Histogram) | 1 |
iMACD | MACD | 2 |
iOBV | On Balance Volume | 1 |
iSAR | Parabolic SAR | 1 |
iRSI | Relative Strength Index | 1 |
iRVI | Relative Vigor Index | 2 |
iStdDev | Standard Deviation | 1 |
iStochastic | Stochastic Oscillator | 2 |
iTEMA | Triple Exponential Moving Average | 1 |
iTriX | Triple Exponential Average | 1 |
iWPR | Williams Percent Range | 1 |
iVIDyA | Variable Index Dynamic Average | 1 |
iVolumes | Volumes | 1 |
Médias Móveis
iMA — Moving Average
int iMA(string symbol,
ENUM_TIMEFRAMES period,
int ma_period,
int ma_shift,
ENUM_MA_METHOD ma_method,
ENUM_APPLIED_PRICE applied_price)ma_method | Descrição |
|---|---|
MODE_SMA | Simples |
MODE_EMA | Exponencial |
MODE_SMMA | Suavizada (Welles Wilder) |
MODE_LWMA | Ponderada linear |
applied_price | Série |
|---|---|
PRICE_CLOSE | Fechamento |
PRICE_OPEN | Abertura |
PRICE_HIGH | Máxima |
PRICE_LOW | Mínima |
PRICE_MEDIAN | (H+L)/2 |
PRICE_TYPICAL | (H+L+C)/3 |
PRICE_WEIGHTED | (H+L+C+C)/4 |
// Cruzamento de médias
int handleFast = iMA(_Symbol, PERIOD_CURRENT, 9, 0, MODE_EMA, PRICE_CLOSE);
int handleSlow = iMA(_Symbol, PERIOD_CURRENT, 21, 0, MODE_EMA, PRICE_CLOSE);
double fast[], slow[];
ArraySetAsSeries(fast, true);
ArraySetAsSeries(slow, true);
CopyBuffer(handleFast, 0, 0, 3, fast);
CopyBuffer(handleSlow, 0, 0, 3, slow);
bool crossUp = (fast[1] > slow[1]) && (fast[2] <= slow[2]);
bool crossDown = (fast[1] < slow[1]) && (fast[2] >= slow[2]);iDEMA — Double EMA
int iDEMA(string symbol, ENUM_TIMEFRAMES period,
int ma_period, int ma_shift, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iTEMA — Triple EMA
int iTEMA(string symbol, ENUM_TIMEFRAMES period,
int ma_period, int ma_shift, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iAMA — Adaptive Moving Average (Kaufman)
int iAMA(string symbol, ENUM_TIMEFRAMES period,
int ama_period, int fast_ma_period, int slow_ma_period,
int ma_shift, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iFrAMA — Fractal Adaptive MA
int iFrAMA(string symbol, ENUM_TIMEFRAMES period,
int ma_period, int ma_shift, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iVIDyA — Variable Index Dynamic Average
int iVIDyA(string symbol, ENUM_TIMEFRAMES period,
int cmo_period, int ema_period,
int ma_shift, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)Osciladores
iRSI — Relative Strength Index
int iRSI(string symbol, ENUM_TIMEFRAMES period,
int ma_period, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0): valores entre 0 e 100int handleRSI = iRSI(_Symbol, PERIOD_CURRENT, 14, PRICE_CLOSE);
double rsi[];
ArraySetAsSeries(rsi, true);
CopyBuffer(handleRSI, 0, 0, 3, rsi);
if(rsi[1] < 30 && rsi[2] >= 30) Print("RSI cruzou sobrevendido para cima");
if(rsi[1] > 70 && rsi[2] <= 70) Print("RSI cruzou sobrecomprado para baixo");iMACD — MACD
int iMACD(string symbol, ENUM_TIMEFRAMES period,
int fast_ema_period, int slow_ema_period,
int signal_period, ENUM_APPLIED_PRICE applied_price)
// Buffer 0: linha MACD
// Buffer 1: linha de sinalint handleMACD = iMACD(_Symbol, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE);
double macdLine[], signalLine[];
ArraySetAsSeries(macdLine, true);
ArraySetAsSeries(signalLine, true);
CopyBuffer(handleMACD, 0, 0, 3, macdLine); // linha MACD
CopyBuffer(handleMACD, 1, 0, 3, signalLine); // linha de sinal
// Histograma = macdLine - signalLine
double hist = macdLine[1] - signalLine[1];iOsMA — OsMA (MACD Histogram)
int iOsMA(string symbol, ENUM_TIMEFRAMES period,
int fast_ema_period, int slow_ema_period,
int signal_period, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0): histograma MACDiStochastic — Stochastic Oscillator
int iStochastic(string symbol, ENUM_TIMEFRAMES period,
int Kperiod, int Dperiod, int slowing,
ENUM_MA_METHOD ma_method,
ENUM_STO_PRICE price_field)
// Buffer 0: %K
// Buffer 1: %Dint handleSto = iStochastic(_Symbol, PERIOD_CURRENT, 14, 3, 3,
MODE_SMA, STO_LOWHIGH);
double K[], D[];
ArraySetAsSeries(K, true);
ArraySetAsSeries(D, true);
CopyBuffer(handleSto, 0, 0, 3, K);
CopyBuffer(handleSto, 1, 0, 3, D);iCCI — Commodity Channel Index
int iCCI(string symbol, ENUM_TIMEFRAMES period,
int ma_period, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iRVI — Relative Vigor Index
int iRVI(string symbol, ENUM_TIMEFRAMES period, int ma_period)
// Buffer 0: linha principal
// Buffer 1: linha de sinaliMomentum — Momentum
int iMomentum(string symbol, ENUM_TIMEFRAMES period,
int mom_period, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)iWPR — Williams Percent Range
int iWPR(string symbol, ENUM_TIMEFRAMES period, int calc_period)
// 1 buffer (índice 0): valores entre -100 e 0iDeMarker — DeMarker
int iDeMarker(string symbol, ENUM_TIMEFRAMES period, int ma_period)
// 1 buffer (índice 0): valores entre 0 e 1iTriX — Triple Exponential Average
int iTriX(string symbol, ENUM_TIMEFRAMES period,
int ma_period, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)Volatilidade
iATR — Average True Range
int iATR(string symbol, ENUM_TIMEFRAMES period, int ma_period)
// 1 buffer (índice 0): ATR em pontos do ativoint handleATR = iATR(_Symbol, PERIOD_CURRENT, 14);
double atr[];
ArraySetAsSeries(atr, true);
CopyBuffer(handleATR, 0, 0, 3, atr);
// Stop baseado em ATR (2x ATR)
double stopDistance = 2.0 * atr[1];
double stopLoss = SymbolInfoDouble(_Symbol, SYMBOL_BID) - stopDistance;iBands — Bollinger Bands
int iBands(string symbol, ENUM_TIMEFRAMES period,
int bands_period, int bands_shift,
double deviation, ENUM_APPLIED_PRICE applied_price)
// Buffer 0: banda superior
// Buffer 1: média central (SMA)
// Buffer 2: banda inferiorint handleBB = iBands(_Symbol, PERIOD_CURRENT, 20, 0, 2.0, PRICE_CLOSE);
double upper[], middle[], lower[];
ArraySetAsSeries(upper, true);
ArraySetAsSeries(middle, true);
ArraySetAsSeries(lower, true);
CopyBuffer(handleBB, 0, 0, 3, upper);
CopyBuffer(handleBB, 1, 0, 3, middle);
CopyBuffer(handleBB, 2, 0, 3, lower);
double squeeze = (upper[1] - lower[1]) / middle[1]; // largura relativaiStdDev — Standard Deviation
int iStdDev(string symbol, ENUM_TIMEFRAMES period,
int ma_period, int ma_shift,
ENUM_MA_METHOD ma_method, ENUM_APPLIED_PRICE applied_price)
// 1 buffer (índice 0)Tendência
iADX — Average Directional Index
int iADX(string symbol, ENUM_TIMEFRAMES period, int adx_period)
// Buffer 0: ADX (força da tendência — 0 a 100)
// Buffer 1: +DI (directional indicator positivo)
// Buffer 2: -DI (directional indicator negativo)int handleADX = iADX(_Symbol, PERIOD_CURRENT, 14);
double adx[], plusDI[], minusDI[];
ArraySetAsSeries(adx, true);
ArraySetAsSeries(plusDI, true);
ArraySetAsSeries(minusDI, true);
CopyBuffer(handleADX, 0, 0, 3, adx); // ADX
CopyBuffer(handleADX, 1, 0, 3, plusDI); // +DI
CopyBuffer(handleADX, 2, 0, 3, minusDI); // -DI
bool trendStrong = adx[1] > 25;
bool bullish = (plusDI[1] > minusDI[1]);iADXWilder — ADX Welles Wilder
int iADXWilder(string symbol, ENUM_TIMEFRAMES period, int adx_period)
// Mesmos 3 buffers que iADX
// Usa suavização de Welles Wilder (SMMA) em vez de EMAiSAR — Parabolic SAR
int iSAR(string symbol, ENUM_TIMEFRAMES period,
double step, double maximum)
// 1 buffer (índice 0): preço do SARint handleSAR = iSAR(_Symbol, PERIOD_CURRENT, 0.02, 0.20);
double sar[];
ArraySetAsSeries(sar, true);
CopyBuffer(handleSAR, 0, 0, 3, sar);
double close1 = iClose(_Symbol, PERIOD_CURRENT, 1);
bool sarBullish = sar[1] < close1; // SAR abaixo do preço = tendência de altaiAlligator — Williams Alligator
int iAlligator(string symbol, ENUM_TIMEFRAMES period,
int jaw_period, int jaw_shift,
int teeth_period, int teeth_shift,
int lips_period, int lips_shift,
ENUM_MA_METHOD ma_method,
ENUM_APPLIED_PRICE applied_price)
// Buffer 0: Jaw (Queixo) — SMMA 13 períodos, shift 8
// Buffer 1: Teeth (Dentes) — SMMA 8 períodos, shift 5
// Buffer 2: Lips (Lábios) — SMMA 5 períodos, shift 3iIchimoku — Ichimoku Kinko Hyo
int iIchimoku(string symbol, ENUM_TIMEFRAMES period,
int tenkan_sen, int kijun_sen, int senkou_span_b)
// Buffer 0: Tenkan-sen (Conversion Line)
// Buffer 1: Kijun-sen (Base Line)
// Buffer 2: Senkou Span A (Leading Span A)
// Buffer 3: Senkou Span B (Leading Span B)
// Buffer 4: Chikou Span (Lagging Span)int handleIchi = iIchimoku(_Symbol, PERIOD_CURRENT, 9, 26, 52);
double tenkan[], kijun[], spanA[], spanB[];
ArraySetAsSeries(tenkan, true);
ArraySetAsSeries(kijun, true);
ArraySetAsSeries(spanA, true);
ArraySetAsSeries(spanB, true);
CopyBuffer(handleIchi, 0, 0, 3, tenkan);
CopyBuffer(handleIchi, 1, 0, 3, kijun);
CopyBuffer(handleIchi, 2, 0, 3, spanA);
CopyBuffer(handleIchi, 3, 0, 3, spanB);
// Kumo (nuvem): SpanA vs SpanB
bool aboveCloud = iClose(_Symbol, PERIOD_CURRENT, 1) > MathMax(spanA[1], spanB[1]);Volume e Preço Médio
iOBV — On Balance Volume
int iOBV(string symbol, ENUM_TIMEFRAMES period,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)
// applied_volume: VOLUME_TICK ou VOLUME_REALiAD — Accumulation/Distribution
int iAD(string symbol, ENUM_TIMEFRAMES period,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)iMFI — Money Flow Index
int iMFI(string symbol, ENUM_TIMEFRAMES period,
int ma_period, ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0): valores entre 0 e 100iVolumes — Volumes
int iVolumes(string symbol, ENUM_TIMEFRAMES period,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)Outros Osciladores
iAO — Awesome Oscillator
int iAO(string symbol, ENUM_TIMEFRAMES period)
// 1 buffer (índice 0)iAC — Accelerator Oscillator
int iAC(string symbol, ENUM_TIMEFRAMES period)
// 1 buffer (índice 0)iBullsPower / iBearsPower
int iBullsPower(string symbol, ENUM_TIMEFRAMES period, int ma_period)
int iBearsPower(string symbol, ENUM_TIMEFRAMES period, int ma_period)
// 1 buffer cada (índice 0)iForce — Force Index
int iForce(string symbol, ENUM_TIMEFRAMES period,
int ma_period, ENUM_MA_METHOD ma_method,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)iChaikin — Chaikin Oscillator
int iChaikin(string symbol, ENUM_TIMEFRAMES period,
int fast_ma_period, int slow_ma_period,
ENUM_MA_METHOD ma_method,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)iBWMFI — Market Facilitation Index (Bill Williams)
int iBWMFI(string symbol, ENUM_TIMEFRAMES period,
ENUM_APPLIED_VOLUME applied_volume)
// 1 buffer (índice 0)iFractals
int iFractals(string symbol, ENUM_TIMEFRAMES period)
// Buffer 0: fractais de alta (upper fractal)
// Buffer 1: fractais de baixa (lower fractal)
// Valor EMPTY_VALUE onde não há fractaliGator — Gator Oscillator
int iGator(string symbol, ENUM_TIMEFRAMES period,
int jaw_period, int jaw_shift,
int teeth_period, int teeth_shift,
int lips_period, int lips_shift,
ENUM_MA_METHOD ma_method, ENUM_APPLIED_PRICE applied_price)
// Buffer 0: histograma acima do zero
// Buffer 1: histograma abaixo do zero (valores negativos)
// Buffer 2: cores do histograma superior
// Buffer 3: cores do histograma inferioriEnvelopes
int iEnvelopes(string symbol, ENUM_TIMEFRAMES period,
int ma_period, int ma_shift,
ENUM_MA_METHOD ma_method,
ENUM_APPLIED_PRICE applied_price,
double deviation)
// Buffer 0: banda superior
// Buffer 1: banda inferioriCustom — Indicador Customizado
int iCustom(string symbol, ENUM_TIMEFRAMES period,
string name, // nome do indicador (sem .ex5)
...) // parâmetros do indicador (variádico)// Carregar indicador "MeuIndicador.ex5" com 2 parâmetros
int handle = iCustom(_Symbol, PERIOD_CURRENT,
"MeuIndicador", // arquivo em MQL5/Indicators/
21, // parâmetro 1
2.0); // parâmetro 2
// Ler buffer 0
double buf[];
ArraySetAsSeries(buf, true);
CopyBuffer(handle, 0, 0, 3, buf);Exemplo Completo: EA com RSI + ATR
#include <Trade/Trade.mqh>
input int RSIPeriod = 14;
input double RSIOversold = 30.0;
input double RSIOverBought = 70.0;
input int ATRPeriod = 14;
input double ATRMultiplier = 2.0;
input double LotSize = 0.1;
int handleRSI, handleATR;
CTrade trade;
int OnInit()
{
handleRSI = iRSI(_Symbol, PERIOD_CURRENT, RSIPeriod, PRICE_CLOSE);
handleATR = iATR(_Symbol, PERIOD_CURRENT, ATRPeriod);
if(handleRSI == INVALID_HANDLE || handleATR == INVALID_HANDLE)
{
Print("Erro ao criar handles");
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
void OnTick()
{
// Executar apenas na abertura de nova barra
static datetime lastBar = 0;
datetime curBar = iTime(_Symbol, PERIOD_CURRENT, 0);
if(curBar == lastBar) return;
lastBar = curBar;
double rsi[], atr[];
ArraySetAsSeries(rsi, true);
ArraySetAsSeries(atr, true);
if(CopyBuffer(handleRSI, 0, 0, 3, rsi) < 3) return;
if(CopyBuffer(handleATR, 0, 0, 3, atr) < 3) return;
if(PositionsTotal() > 0) return;
double close1 = iClose(_Symbol, PERIOD_CURRENT, 1);
double stop = ATRMultiplier * atr[1];
// Compra: RSI cruzando sobrevendido para cima
if(rsi[1] > RSIOversold && rsi[2] <= RSIOversold)
trade.Buy(LotSize, _Symbol,
SymbolInfoDouble(_Symbol, SYMBOL_ASK),
close1 - stop, 0, "RSI Buy");
// Venda: RSI cruzando sobrecomprado para baixo
if(rsi[1] < RSIOverBought && rsi[2] >= RSIOverBought)
trade.Sell(LotSize, _Symbol,
SymbolInfoDouble(_Symbol, SYMBOL_BID),
close1 + stop, 0, "RSI Sell");
}
void OnDeinit(const int reason)
{
IndicatorRelease(handleRSI);
IndicatorRelease(handleATR);
}Boas Práticas
| Prática | Por quê |
|---|---|
Criar handles em OnInit(), não em OnTick() | Evita recriação a cada tick — alto custo computacional |
Verificar INVALID_HANDLE após criação | Previne crashes silenciosos |
Usar ArraySetAsSeries(arr, true) | Garante que índice 0 = valor mais recente |
Verificar retorno de CopyBuffer | Pode retornar menos valores que o solicitado no início |
Liberar com IndicatorRelease() em OnDeinit() | Evita vazamento de memória |
| Guardar handle em variável global | Permite reutilizar o mesmo handle em múltiplas chamadas |
Referências
Referências externas
- MQL5 Reference — Technical Indicators (MetaQuotes)
- MQL5 Reference — iMA (MetaQuotes)
- MQL5 Reference — iRSI (MetaQuotes)
- MQL5 Reference — iMACD (MetaQuotes)
- MQL5 Reference — iBands (MetaQuotes)
- MQL5 Reference — iATR (MetaQuotes)
- MQL5 Reference — iADX (MetaQuotes)
- MQL5 Reference — CopyBuffer (MetaQuotes)
MQL5 — Event Handlers: Estrutura de Execução
Guia completo dos 14 event handlers do MQL5: OnInit, OnDeinit, OnTick, OnCalculate, OnTimer, OnTrade, OnTradeTransaction, OnChartEvent, OnTester e outros — com assinaturas, códigos de retorno e exemplos práticos.
MQL5 — Indicadores Customizados
Como criar indicadores personalizados em MQL5: SetIndexBuffer, estilos de plotagem (DRAW_LINE, DRAW_HISTOGRAM, DRAW_ARROW, DRAW_FILLING, DRAW_CANDLES), buffers, propriedades e exemplos completos.