⚡ Tutorial Avanzado

Cómo Crear un Expert Advisor con IA para MT5 en Deriv

Por Dan Machado · Abril 2026 · 16 min · Nivel: Avanzado

Los Expert Advisors (EAs) son bots de trading que funcionan en MetaTrader 5. Con IA, puedes crear EAs sofisticados sin saber MQL5 — solo describes la estrategia y la IA genera el código completo.

Deriv ofrece MT5 integrado — así que puedes crear, probar y ejecutar EAs directamente en la plataforma, con acceso a Forex, índices sintéticos (V75) y más.

¿Qué es un Expert Advisor?

Es un programa escrito en MQL5 que se ejecuta dentro de MetaTrader 5. Puede:

  • Analizar el mercado usando indicadores (RSI, MACD, EMAs, etc.)
  • Abrir y cerrar posiciones automáticamente
  • Gestionar stop loss, take profit y trailing stops
  • Funcionar 24/7 sin intervención humana
  • Hacer backtest con datos históricos

¿Por qué usar MT5 en Deriv?

  • ✅ Acceso a índices sintéticos (V75, Crash/Boom) — 24/7
  • ✅ Forex, commodities y crypto vía CFDs
  • ✅ Cuenta demo con $10,000 en fondos virtuales
  • Backtesting integrado en el Strategy Tester
  • ✅ Soporte oficial de Deriv para MT5
  • ✅ El EA funciona del lado del servidor — no necesitas mantener la PC encendida (con un VPS)

Configurar MT5 en Deriv

01

Crear cuenta Deriv

Ve a deriv.com y crea tu cuenta (gratis).

02

Habilita Deriv MT5

En Trader’s Hub → sección «CFDs» → haz clic en «Get» junto a Deriv MT5 → crea una cuenta MT5 (demo o real).

03

Descarga MT5

Descarga MetaTrader 5 para tu sistema (Windows, Mac, Linux vía Wine). O usa la versión web de MT5 directamente en el navegador.

04

Inicia sesión

Usa las credenciales MT5 que te proporcionó Deriv (login, contraseña, servidor). El servidor de Deriv es «Deriv-Demo» o «Deriv-Server».

Crear un EA con IA

Aquí está el proceso completo:

A

Describe la estrategia a la IA

Abre ChatGPT o Claude y usa el prompt de abajo.

🤖 Prompt para generar un EA completo

You are an MQL5 specialist for MetaTrader 5. Create an Expert Advisor that: – Trades the Volatility 75 Index (symbol: «Volatility 75 Index») – Timeframe: M5 (5 minutes) – Strategy: EMA 9 and EMA 21 crossover with RSI confirmation – Buy when: EMA 9 crosses above EMA 21 AND RSI > 40 and < 70 – Sell when: EMA 9 crosses below EMA 21 AND RSI < 60 and > 30 – Stop Loss: 200 points – Take Profit: 400 points (1:2 risk-reward) – Trailing Stop: 100 points – Risk per trade: 2% of balance – Max 1 open position at a time – Magic number: 12345 Complete, compilable MQL5 code, with: – OnInit(), OnDeinit(), OnTick() – Helper functions for lot sizing – Comments in English – Error handling
B

Copia el código MQL5

La IA genera el EA completo (~200-300 líneas). Copia todo el código.

C

Abre MetaEditor

En MT5 → menú «Tools» → «MetaQuotes Language Editor» (o presiona F4). Crea un nuevo archivo: File → New → Expert Advisor.

D

Pega y compila

Borra el código por defecto. Pega el código de la IA. Haz clic en «Compile» (F7). Si hay errores, pega los mensajes a la IA y pide la corrección.

E

Prueba en Strategy Tester

En MT5 → View → Strategy Tester. Selecciona tu EA, activo (V75), período (1 año) y ejecuta el backtest. Analiza el reporte.

F

Ejecuta en cuenta demo

Arrastra el EA al gráfico del activo. Habilita «AutoTrading» (botón superior). El EA empieza a operar automáticamente.

EA de ejemplo — código listo

MQL5 — Expert Advisor📋 Copiar
//+------------------------------------------------------------------+
//| EA EMA Cross + RSI — AI-generated                                |
//| IA Trader Pro — iatraderpro.com/                                  |
//| WARNING: Use only on a DEMO account!                             |
//+------------------------------------------------------------------+
#property copyright "IA Trader Pro"
#property version   "1.00"
#property strict

// Input parameters
input int      EMA_Fast     = 9;       // Fast EMA period
input int      EMA_Slow     = 21;      // Slow EMA period
input int      RSI_Period   = 14;      // RSI period
input int      RSI_Lower    = 40;      // RSI minimum for buy
input int      RSI_Upper    = 60;      // RSI maximum for sell
input double   RiskPercent  = 2.0;     // Risk per trade (%)
input int      StopLoss     = 200;     // Stop Loss in points
input int      TakeProfit   = 400;     // Take Profit in points
input int      TrailingStop = 100;     // Trailing Stop in points
input int      MagicNumber  = 12345;   // Magic number

// Indicator handles
int handleEmaFast, handleEmaSlow, handleRsi;

//+------------------------------------------------------------------+
//| Initialization                                                   |
//+------------------------------------------------------------------+
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("❌ Error creating indicators");
      return INIT_FAILED;
   }

   Print("✅ EA IA Trader Pro started successfully");
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Deinitialization                                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   IndicatorRelease(handleEmaFast);
   IndicatorRelease(handleEmaSlow);
   IndicatorRelease(handleRsi);
   Print("EA stopped. Reason: ", reason);
}

//+------------------------------------------------------------------+
//| Main tick                                                        |
//+------------------------------------------------------------------+
void OnTick()
{
   // Check if there's an open position
   if(PositionsTotal() > 0)
   {
      // Apply trailing stop
      ApplyTrailingStop();
      return;
   }

   // Get indicator values
   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);

   // Crossover up (buy signal)
   bool crossUp = emaFast[1] <= emaSlow[1] && emaFast[0] > emaSlow[0];
   bool crossDown = emaFast[1] >= emaSlow[1] && emaFast[0] < emaSlow[0];

   double lot = CalculateLot();

   // BUY signal
   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("🟢 BUY: ", lot, " lots @ ", price);
      else
         Print("❌ Buy error: ", res.retcode);
   }

   // SELL signal
   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("🔴 SELL: ", lot, " lots @ ", price);
      else
         Print("❌ Sell error: ", res.retcode);
   }
}

//+------------------------------------------------------------------+
//| Calculate lot based on risk                                      |
//+------------------------------------------------------------------+
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 hace:

Cruce de EMA 9/21 + filtro RSI → compra/venta automática → stop loss de 200pt → take profit de 400pt (1:2) → trailing stop de 100pt → tamaño de lot al 2% de riesgo → máx 1 posición. Listo para compilar y ejecutar en Deriv MT5.

Potenciarlo con IA

Tras ejecutar el EA básico, pídele a la IA que añada:

  • Filtro de horario: «Trade only between 08:00 and 17:00 GMT»
  • Multi-timeframe: «Confirm direction on the H1 timeframe before trading on M5»
  • MACD como filtro: «Only buy if MACD histogram is positive»
  • Auto-breakeven: «Move SL to entry price when profit reaches 100 points»
  • Dashboard en el gráfico: «Show a panel with indicator status, last trade, P&L»

🚀 Para ejecutar EAs en MT5, crea tu cuenta Deriv MT5 gratis:

Crear Cuenta Deriv MT5 →
DM

Dan Machado

Más en Empieza Aquí.

⚠️ Educativo. El trading implica riesgo. Los EAs pueden perder dinero. Prueba en demo. Aviso Legal.