⚡ Tutorial Avançado

Como Criar um Expert Advisor com IA para MT5 na Deriv

Por Dan Machado · Abril 2026 · 16 min · Nível: Avançado

Expert Advisors (EAs) são robôs de trading que rodam no MetaTrader 5. Com IA, você pode criar EAs sofisticados sem saber MQL5 — basta descrever a estratégia e a IA gera o código completo.

A Deriv oferece MT5 integrado — então você pode criar, testar e rodar EAs diretamente na plataforma, com acesso a Forex, índices sintéticos (V75) e mais.

O que é um Expert Advisor?

É um programa escrito em MQL5 que roda dentro do MetaTrader 5. Ele pode:

  • Analisar o mercado usando indicadores (RSI, MACD, EMAs, etc.)
  • Abrir e fechar posições automaticamente
  • Gerenciar stop loss, take profit e trailing stop
  • Operar 24/7 sem intervenção humana
  • Fazer backtesting com dados históricos

Por que usar MT5 na Deriv?

  • ✅ Acesso a índices sintéticos (V75, Crash/Boom) — 24/7
  • ✅ Forex, commodities e cripto via CFDs
  • ✅ Conta demo com $10.000 virtuais
  • Backtesting integrado no Strategy Tester
  • ✅ Suporte oficial da Deriv para MT5
  • ✅ EA roda no servidor — não precisa manter o computador ligado (com VPS)

Configurando MT5 na Deriv

01

Crie conta Deriv

Acesse deriv.com e crie sua conta (grátis).

02

Ative o Deriv MT5

No Trader’s Hub → seção “CFDs” → clique em “Get” ao lado de Deriv MT5 → crie uma conta MT5 (demo ou real).

03

Baixe o MT5

Baixe o MetaTrader 5 para seu sistema (Windows, Mac, Linux via Wine). Ou use o MT5 web direto no navegador.

04

Faça login

Use as credenciais MT5 fornecidas pela Deriv (login, senha, servidor). O servidor da Deriv é “Deriv-Demo” ou “Deriv-Server”.

Criando um EA com IA

Aqui está o processo completo:

A

Descreva a estratégia para a IA

Abra o ChatGPT ou Claude e use o prompt abaixo.

🤖 Prompt para gerar EA completo

Você é um especialista em MQL5 para MetaTrader 5. Crie um Expert Advisor que: – Opera no Volatility 75 Index (símbolo: “Volatility 75 Index”) – Timeframe: M5 (5 minutos) – Estratégia: Cruzamento de EMA 9 e EMA 21 com confirmação de RSI – Compra quando: EMA 9 cruza acima da EMA 21 E RSI > 40 e < 70 - Vende quando: EMA 9 cruza abaixo da EMA 21 E RSI < 60 e > 30 – Stop Loss: 200 pontos – Take Profit: 400 pontos (risk-reward 1:2) – Trailing Stop: 100 pontos – Risco por operação: 2% do saldo – Máximo de 1 posição aberta por vez – Magic number: 12345 Código MQL5 completo, compilável, com: – OnInit(), OnDeinit(), OnTick() – Funções auxiliares de cálculo de lote – Comentários em português – Tratamento de erros
B

Copie o código MQL5

A IA gera o EA completo (~200-300 linhas). Copie todo o código.

C

Abra o MetaEditor

No MT5 → menu “Ferramentas” → “MetaQuotes Language Editor” (ou pressione F4). Crie um novo arquivo: File → New → Expert Advisor.

D

Cole e compile

Apague o código padrão. Cole o código da IA. Clique em “Compilar” (F7). Se houver erros, cole as mensagens de volta na IA e peça correção.

E

Teste no Strategy Tester

No MT5 → View → Strategy Tester. Selecione seu EA, o ativo (V75), período (1 ano), e rode o backtest. Analise o relatório.

F

Rode em conta demo

Arraste o EA para o gráfico do ativo. Ative “AutoTrading” (botão no topo). O EA começa a operar automaticamente.

EA de exemplo — código pronto

MQL5 — Expert Advisor📋 Copiar
//+------------------------------------------------------------------+
//| EA EMA Cross + RSI — Gerado por IA                               |
//| IA Trader Pro — iatraderpro.com                                  |
//| AVISO: Use apenas em conta DEMO!                                 |
//+------------------------------------------------------------------+
#property copyright "IA Trader Pro"
#property version   "1.00"
#property strict
 
// Parâmetros de entrada
input int      EMA_Fast     = 9;       // Período EMA rápida
input int      EMA_Slow     = 21;      // Período EMA lenta
input int      RSI_Period   = 14;      // Período RSI
input int      RSI_Lower    = 40;      // RSI mínimo para compra
input int      RSI_Upper    = 60;      // RSI máximo para venda
input double   RiskPercent  = 2.0;     // Risco por trade (%)
input int      StopLoss     = 200;     // Stop Loss em pontos
input int      TakeProfit   = 400;     // Take Profit em pontos
input int      TrailingStop = 100;     // Trailing Stop em pontos
input int      MagicNumber  = 12345;   // Magic number
 
// Handles dos indicadores
int handleEmaFast, handleEmaSlow, handleRsi;
 
//+------------------------------------------------------------------+
//| Inicialização                                                    |
//+------------------------------------------------------------------+
int OnInit()
{
   handleEmaFast = iMA(_Symbol, PERIOD_CURRENT, EMA_Fast, 0, MODE_EMA, PRICE_CLOSE);
   handleEmaSlow = iMA(_Symbol, PERIOD_CURRENT, EMA_Slow, 0, MODE_EMA, PRICE_CLOSE);
   handleRsi     = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period, PRICE_CLOSE);
   
   if(handleEmaFast == INVALID_HANDLE || handleEmaSlow == INVALID_HANDLE || handleRsi == INVALID_HANDLE)
   {
      Print("❌ Erro ao criar indicadores");
      return INIT_FAILED;
   }
   
   Print("✅ EA IA Trader Pro iniciado com sucesso");
   return INIT_SUCCEEDED;
}
 
//+------------------------------------------------------------------+
//| Desinicialização                                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   IndicatorRelease(handleEmaFast);
   IndicatorRelease(handleEmaSlow);
   IndicatorRelease(handleRsi);
   Print("EA encerrado. Motivo: ", reason);
}
 
//+------------------------------------------------------------------+
//| Tick principal                                                   |
//+------------------------------------------------------------------+
void OnTick()
{
   // Verificar se já tem posição aberta
   if(PositionsTotal() > 0)
   {
      // Aplicar trailing stop
      ApplyTrailingStop();
      return;
   }
   
   // Obter valores dos indicadores
   double emaFast[], emaSlow[], rsi[];
   CopyBuffer(handleEmaFast, 0, 0, 3, emaFast);
   CopyBuffer(handleEmaSlow, 0, 0, 3, emaSlow);
   CopyBuffer(handleRsi, 0, 0, 2, rsi);
   
   ArraySetAsSeries(emaFast, true);
   ArraySetAsSeries(emaSlow, true);
   ArraySetAsSeries(rsi, true);
   
   // Cruzamento para cima (sinal de compra)
   bool crossUp = emaFast[1] <= emaSlow[1] && emaFast[0] > emaSlow[0];
   bool crossDown = emaFast[1] >= emaSlow[1] && emaFast[0] < emaSlow[0];
   
   double lot = CalculateLot();
   
   // Sinal de COMPRA
   if(crossUp && rsi[0] > RSI_Lower && rsi[0] < 70)
   {
      double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double sl = price - StopLoss * _Point;
      double tp = price + TakeProfit * _Point;
      
      MqlTradeRequest req = {};
      MqlTradeResult  res = {};
      req.action    = TRADE_ACTION_DEAL;
      req.symbol    = _Symbol;
      req.volume    = lot;
      req.type      = ORDER_TYPE_BUY;
      req.price     = price;
      req.sl        = sl;
      req.tp        = tp;
      req.magic     = MagicNumber;
      req.comment   = "IA Trader Pro BUY";
      
      if(OrderSend(req, res))
         Print("🟢 COMPRA: ", lot, " lotes @ ", price);
      else
         Print("❌ Erro compra: ", res.retcode);
   }
   
   // Sinal de VENDA
   if(crossDown && rsi[0] < RSI_Upper && rsi[0] > 30)
   {
      double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double sl = price + StopLoss * _Point;
      double tp = price - TakeProfit * _Point;
      
      MqlTradeRequest req = {};
      MqlTradeResult  res = {};
      req.action    = TRADE_ACTION_DEAL;
      req.symbol    = _Symbol;
      req.volume    = lot;
      req.type      = ORDER_TYPE_SELL;
      req.price     = price;
      req.sl        = sl;
      req.tp        = tp;
      req.magic     = MagicNumber;
      req.comment   = "IA Trader Pro SELL";
      
      if(OrderSend(req, res))
         Print("🔴 VENDA: ", lot, " lotes @ ", price);
      else
         Print("❌ Erro venda: ", res.retcode);
   }
}
 
//+------------------------------------------------------------------+
//| Calcular lote baseado no risco                                   |
//+------------------------------------------------------------------+
double CalculateLot()
{
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   double riskAmount = balance * RiskPercent / 100.0;
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double lot = riskAmount / (StopLoss * tickValue);
   
   double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   
   lot = MathFloor(lot / lotStep) * lotStep;
   lot = MathMax(minLot, MathMin(maxLot, lot));
   
   return lot;
}
 
//+------------------------------------------------------------------+
//| Trailing Stop                                                    |
//+------------------------------------------------------------------+
void ApplyTrailingStop()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(PositionGetSymbol(i) != _Symbol) continue;
      if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue;
      
      double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double currentSL = PositionGetDouble(POSITION_SL);
      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      long type = PositionGetInteger(POSITION_TYPE);
      
      if(type == POSITION_TYPE_BUY)
      {
         double newSL = bid - TrailingStop * _Point;
         if(newSL > currentSL && newSL > openPrice)
         {
            MqlTradeRequest req = {};
            MqlTradeResult  res = {};
            req.action   = TRADE_ACTION_SLTP;
            req.position = PositionGetInteger(POSITION_TICKET);
            req.symbol   = _Symbol;
            req.sl       = newSL;
            req.tp       = PositionGetDouble(POSITION_TP);
            OrderSend(req, res);
         }
      }
      else if(type == POSITION_TYPE_SELL)
      {
         double newSL = ask + TrailingStop * _Point;
         if(newSL < currentSL && newSL < openPrice)
         {
            MqlTradeRequest req = {};
            MqlTradeResult  res = {};
            req.action   = TRADE_ACTION_SLTP;
            req.position = PositionGetInteger(POSITION_TICKET);
            req.symbol   = _Symbol;
            req.sl       = newSL;
            req.tp       = PositionGetDouble(POSITION_TP);
            OrderSend(req, res);
         }
      }
   }
}

✅ Este EA faz:

Cruzamento EMA 9/21 + filtro RSI → compra/venda automática → stop loss 200pts → take profit 400pts (1:2) → trailing stop 100pts → lote baseado em 2% de risco → máximo 1 posição. Pronto para compilar e rodar no MT5 da Deriv.

Turbinando com IA

Depois de rodar o EA básico, peça à IA para adicionar:

  • Filtro de horário: "Opere apenas entre 08:00 e 17:00 GMT"
  • Multi-timeframe: "Confirme a direção no timeframe H1 antes de operar no M5"
  • MACD como filtro: "Só compre se MACD histogram for positivo"
  • Breakeven automático: "Mova SL para o preço de entrada quando lucro atingir 100 pontos"
  • Dashboard no gráfico: "Mostre um painel com status dos indicadores, último trade, P&L"

🚀 Para rodar EAs no MT5, crie sua conta Deriv MT5 grátis:

Criar Conta Deriv MT5 →
DM

Dan Machado

Mais em Comece Aqui.

⚠️ Educacional. Trading envolve risco. EAs podem perder dinheiro. Teste em demo. Disclaimer.

Posts Similares