⚡ Tutorial Lengkap

Expert Advisor MT5 dengan AI di Deriv — Complete Guide

Oleh Dan Machado · 16 menit baca

Expert Advisor (EA) di MetaTrader 5 adalah trading bot yang dapat di-deploy di Deriv MT5. Dengan AI seperti ChatGPT atau Claude, kamu bisa generate MQL5 code lengkap dalam menit — tanpa harus belajar bahasa MQL5 selama berbulan-bulan. Tutorial ini menunjukkan cara dari nol sampai EA running di chart kamu.

Mengapa Pakai EA + AI?

Tanpa AIDengan AI (2026)
Belajar MQL5 3-6 bulanGenerate code dalam 5 menit
Ribuan dolar untuk EA marketCustom EA gratis
Logic terbatas pada libraryCustom logic apapun
Debugging manualAI fix bugs untuk kamu
Static (tidak adapt)Iterate fast, ubah strategy

💡 EA vs Deriv Bot

EA MT5 = kontrol penuh + advanced. Cocok untuk forex CFD, synthetic V75, multi-asset.
Deriv Bot = visual + tanpa coding. Cocok untuk binary options, beginner-friendly.
Lihat tutorial Deriv Bot untuk no-code alternative.

Prerequisites

  • MT5 Deriv terinstall — lihat tutorial install MT5
  • Akun ChatGPT atau Claude (free tier sufficient)
  • Basic understanding trading concepts (RSI, EMA, stop loss)
  • 30 menit waktu

Step 1 — Define Strategy Kamu

Sebelum minta AI generate code, kamu harus tahu strategy apa yang mau di-build. Contoh strategy untuk tutorial ini:

📋 Strategy: RSI + EMA Crossover

BUY (Long): EMA(9) crosses above EMA(21) AND RSI(14) < 70
SELL (Short): EMA(9) crosses below EMA(21) AND RSI(14) > 30
Stop Loss: 50 pips
Take Profit: 100 pips (R/R 1:2)
Risk per trade: 2% balance
Asset: Volatility 75 Index
Timeframe: M5 (5 menit)

Step 2 — Generate Code dengan AI

Pakai prompt ini di ChatGPT atau Claude:

🤖 PROMPT UNTUK AI

You are a senior MQL5 developer specializing in Deriv MT5 Expert Advisors. Create a complete, production-ready MQL5 Expert Advisor with these specs: STRATEGY: – Entry BUY: EMA(9) crosses above EMA(21) AND RSI(14) < 70 – Entry SELL: EMA(9) crosses below EMA(21) AND RSI(14) > 30 – Exit: Stop Loss 50 pips OR Take Profit 100 pips (1:2 R/R) PARAMETERS (inputs): – Magic number: 20260512 – Lot size mode: Risk % per trade (default 2%) – Stop loss in pips: 50 – Take profit in pips: 100 – Max concurrent positions: 1 – Trading hours filter: optional (24/7 for V75) REQUIREMENTS: 1. Full code with #property directives 2. Proper OnInit() with handle validation 3. Robust OnTick() with new-bar detection 4. OnDeinit() with cleanup 5. Helper functions: CalculateLotSize, IsNewBar, CheckTradingTime, GetSpread 6. Position management filtered by magic number 7. Stop level checks (broker minimum SL/TP distance) 8. Slippage protection (deviation parameter) 9. Detailed Print() logging 10. English comments OUTPUT: Complete .mq5 file, ready to compile in MetaEditor. Test broker: Deriv MT5 (Demo) Asset: Volatility 75 Index (R_75) Timeframe: M5

Step 3 — Complete MQL5 Code

Inilah hasil yang AI akan generate (sudah saya verifikasi dan compile sukses):

▸ MQL5 · RSI_EMA_Strategy_EA.mq5 COPY ↗
//+------------------------------------------------------------------+
//|                                       RSI_EMA_Strategy_EA.mq5     |
//|                                            IA Trader Pro (2026)   |
//|                                            https://iatraderpro.com/|
//+------------------------------------------------------------------+
#property copyright "IA Trader Pro 2026"
#property link      "https://iatraderpro.com/"
#property version   "1.00"
#property strict

#include <Trade\Trade.mqh>

//--- Inputs
input int    InpMagic         = 20260512;  // Magic number
input double InpRiskPercent   = 2.0;       // Risk per trade (%)
input int    InpSL_Pips       = 50;        // Stop Loss (pips)
input int    InpTP_Pips       = 100;       // Take Profit (pips)
input int    InpEMA_Fast      = 9;         // EMA Fast period
input int    InpEMA_Slow      = 21;        // EMA Slow period
input int    InpRSI_Period    = 14;        // RSI period
input int    InpRSI_Buy_Max   = 70;        // Max RSI for BUY
input int    InpRSI_Sell_Min  = 30;        // Min RSI for SELL
input int    InpDeviation     = 10;        // Max slippage (points)
input bool   InpUseTimeFilter = false;     // Enable trading hours filter
input int    InpStartHour     = 0;         // Start hour (server time)
input int    InpEndHour       = 23;        // End hour (server time)

//--- Globals
CTrade trade;
int    handleEmaFast = INVALID_HANDLE;
int    handleEmaSlow = INVALID_HANDLE;
int    handleRsi     = INVALID_HANDLE;
datetime lastBarTime = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    trade.SetExpertMagicNumber(InpMagic);
    trade.SetDeviationInPoints(InpDeviation);
    trade.SetTypeFillingBySymbol(_Symbol);
    
    // Initialize indicator handles
    handleEmaFast = iMA(_Symbol, PERIOD_CURRENT, InpEMA_Fast, 0, MODE_EMA, PRICE_CLOSE);
    handleEmaSlow = iMA(_Symbol, PERIOD_CURRENT, InpEMA_Slow, 0, MODE_EMA, PRICE_CLOSE);
    handleRsi     = iRSI(_Symbol, PERIOD_CURRENT, InpRSI_Period, PRICE_CLOSE);
    
    if(handleEmaFast == INVALID_HANDLE || handleEmaSlow == INVALID_HANDLE || handleRsi == INVALID_HANDLE)
    {
        Print("ERROR: Failed to create indicator handles");
        return(INIT_FAILED);
    }
    
    Print("EA initialized successfully | Magic: ", InpMagic,
          " | Risk: ", InpRiskPercent, "%",
          " | SL: ", InpSL_Pips, " pips | TP: ", InpTP_Pips, " pips");
    
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    if(handleEmaFast != INVALID_HANDLE) IndicatorRelease(handleEmaFast);
    if(handleEmaSlow != INVALID_HANDLE) IndicatorRelease(handleEmaSlow);
    if(handleRsi     != INVALID_HANDLE) IndicatorRelease(handleRsi);
    
    Print("EA deinitialized. Reason: ", reason);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Only process new bar (M5 entries based on closed candles)
    if(!IsNewBar()) return;
    
    // Check trading hours filter
    if(InpUseTimeFilter && !IsTradingTime()) return;
    
    // Skip if already have position
    if(HasOpenPosition()) return;
    
    // Get indicator values
    double emaFast[], emaSlow[], rsi[];
    ArraySetAsSeries(emaFast, true);
    ArraySetAsSeries(emaSlow, true);
    ArraySetAsSeries(rsi, true);
    
    if(CopyBuffer(handleEmaFast, 0, 0, 3, emaFast) < 3) return;
    if(CopyBuffer(handleEmaSlow, 0, 0, 3, emaSlow) < 3) return;
    if(CopyBuffer(handleRsi,     0, 0, 3, rsi)     < 3) return;
    
    // Detect crossovers (bar [1] is the last closed bar)
    bool emaCrossUp   = emaFast[2] <= emaSlow[2] && emaFast[1] > emaSlow[1];
    bool emaCrossDown = emaFast[2] >= emaSlow[2] && emaFast[1] < emaSlow[1];
    
    // BUY signal
    if(emaCrossUp && rsi[1] < InpRSI_Buy_Max)
    {
        OpenPosition(ORDER_TYPE_BUY);
    }
    // SELL signal
    else if(emaCrossDown && rsi[1] > InpRSI_Sell_Min)
    {
        OpenPosition(ORDER_TYPE_SELL);
    }
}

//+------------------------------------------------------------------+
//| Open position with SL/TP and dynamic lot size                    |
//+------------------------------------------------------------------+
void OpenPosition(ENUM_ORDER_TYPE orderType)
{
    double price  = (orderType == ORDER_TYPE_BUY)
                    ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
                    : SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
    double point  = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
    int    digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    int    pipFactor = (digits == 3 || digits == 5) ? 10 : 1;
    double pipSize = point * pipFactor;
    
    double slPrice, tpPrice;
    if(orderType == ORDER_TYPE_BUY)
    {
        slPrice = NormalizeDouble(price - InpSL_Pips * pipSize, digits);
        tpPrice = NormalizeDouble(price + InpTP_Pips * pipSize, digits);
    }
    else
    {
        slPrice = NormalizeDouble(price + InpSL_Pips * pipSize, digits);
        tpPrice = NormalizeDouble(price - InpTP_Pips * pipSize, digits);
    }
    
    // Validate broker stop level
    double minStopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * point;
    if(MathAbs(price - slPrice) < minStopLevel)
    {
        Print("WARNING: SL too close to price. Min stop level: ", minStopLevel);
        return;
    }
    
    // Calculate lot size based on risk %
    double lotSize = CalculateLotSize(MathAbs(price - slPrice));
    if(lotSize <= 0)
    {
        Print("ERROR: Invalid lot size calculated");
        return;
    }
    
    string comment = (orderType == ORDER_TYPE_BUY) ? "RSI_EMA Long" : "RSI_EMA Short";
    
    bool result = false;
    if(orderType == ORDER_TYPE_BUY)
        result = trade.Buy(lotSize, _Symbol, price, slPrice, tpPrice, comment);
    else
        result = trade.Sell(lotSize, _Symbol, price, slPrice, tpPrice, comment);
    
    if(result)
        Print("✓ ", comment, " opened | Lot: ", lotSize,
              " | Entry: ", price, " | SL: ", slPrice, " | TP: ", tpPrice);
    else
        Print("✗ Order failed: ", trade.ResultRetcode(), " - ", trade.ResultRetcodeDescription());
}

//+------------------------------------------------------------------+
//| Calculate lot size based on risk % and stop distance             |
//+------------------------------------------------------------------+
double CalculateLotSize(double stopDistancePrice)
{
    double balance       = AccountInfoDouble(ACCOUNT_BALANCE);
    double riskAmount    = balance * InpRiskPercent / 100.0;
    double tickValue     = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    double tickSize      = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    
    if(tickValue == 0 || tickSize == 0 || stopDistancePrice == 0) return 0;
    
    double lossPerLot = (stopDistancePrice / tickSize) * tickValue;
    double lotSize    = riskAmount / lossPerLot;
    
    // Normalize to symbol's lot step
    double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
    double lotMin  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
    double lotMax  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
    lotSize = MathFloor(lotSize / lotStep) * lotStep;
    lotSize = MathMax(lotMin, MathMin(lotMax, lotSize));
    
    return NormalizeDouble(lotSize, 2);
}

//+------------------------------------------------------------------+
//| Check if a new bar has formed                                    |
//+------------------------------------------------------------------+
bool IsNewBar()
{
    datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    if(currentBarTime != lastBarTime)
    {
        lastBarTime = currentBarTime;
        return true;
    }
    return false;
}

//+------------------------------------------------------------------+
//| Check if current time within trading hours filter                |
//+------------------------------------------------------------------+
bool IsTradingTime()
{
    MqlDateTime dt;
    TimeCurrent(dt);
    int hour = dt.hour;
    
    if(InpStartHour <= InpEndHour)
        return (hour >= InpStartHour && hour < InpEndHour);
    else
        return (hour >= InpStartHour || hour < InpEndHour);  // wraps midnight
}

//+------------------------------------------------------------------+
//| Check if EA already has open position for this symbol+magic      |
//+------------------------------------------------------------------+
bool HasOpenPosition()
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if(ticket > 0)
        {
            if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
               PositionGetInteger(POSITION_MAGIC) == InpMagic)
                return true;
        }
    }
    return false;
}
//+------------------------------------------------------------------+

Step 4 — Compile di MetaEditor

1

Buka MetaEditor

Di MT5: F4 atau Tools → MetaEditor. Aplikasi terpisah akan launch.

2

Create New EA

File → New → Expert Advisor (template). Beri nama: RSI_EMA_Strategy_EA. Save di MQL5\Experts\.

3

Paste Code

Hapus template content. Paste seluruh MQL5 code di atas. Save (Ctrl+S).

4

Compile (F7)

Tekan F7 atau klik “Compile”. Bottom panel show: “0 error(s), 0 warning(s)”. EA siap.

❌ Compile Errors?

Copy error message lengkap, paste ke AI dengan code, minta fix. Common errors:
• Missing #include: usually solved otomatis by template
• Undefined variables: AI generate sometimes mismatch syntax — minta verify
• Version mismatch: pakai MT5 build terbaru

Step 5 — Test di Strategy Tester

Sebelum live, WAJIB backtest:

1

View → Strategy Tester

Atau Ctrl+R. Panel akan terbuka di bottom.

2

Settings

Expert: RSI_EMA_Strategy_EA
Symbol: Volatility 75 Index (atau pair lain)
Period: M5
Date range: 6 bulan terakhir
Modeling: “Every tick based on real ticks” (paling akurat)

3

Klik Start

MT5 akan simulate strategy pada data historical. Wait 1-5 menit.

4

Analyze Results

Tabs: Results (P/L per trade), Graph (equity curve), Report (metrics lengkap).

Step 6 — Deploy ke Demo Chart

Setelah backtest oke, deploy ke live demo chart. Lihat tutorial install EA untuk step-by-step.

Quick steps:

  1. Buka chart V75 di MT5, set timeframe M5
  2. Drag EA dari Navigator ke chart
  3. Configure inputs (risk %, SL, TP)
  4. Enable “Algo Trading” (toolbar atas)
  5. Verify EA active (smiley face top-right chart)

Step 7 — Monitor & Iterate

Track EA performance dengan Journal & Experts tabs (Ctrl+T):

  • Trade tab: Active positions
  • History tab: Closed trades dengan P/L
  • Experts tab: EA logs — useful untuk debug

Setelah 1-2 minggu data demo, return ke AI dengan results:

🔄 PROMPT UNTUK ITERASI

Saya jalankan EA RSI_EMA Strategy ini di demo MT5 Deriv selama 2 minggu. Berikut hasilnya: – Total trades: 47 – Win rate: 51% – Net profit: -$12 (rugi tipis) – Max drawdown: 8% – Average win: $4.50 – Average loss: $5.20 Issue saya identifikasi: – Banyak whipsaws di sideways market – Stop loss kena terlalu sering saat news event Tolong: 1. Identifikasi weakness strategy ini 2. Suggest 2-3 improvements parameter 3. Kalau perlu, rewrite code dengan ATR-based stop loss 4. Add filter untuk avoid trade saat low-volatility Output: code MQL5 v2 yang updated.

Advanced Topics

1. ATR-Based Dynamic Stop Loss

Stop loss fix 50 pips terlalu rigid. Better: use ATR (Average True Range) untuk adapt dengan volatility. Minta AI rewrite dengan: slPrice = price - (atr * 1.5).

2. Trailing Stop

Setelah trade in profit X pips, trail stop di belakang harga. Lock-in profit, give room to grow.

3. Multi-Timeframe Confirmation

Entry M5 hanya kalau M1 EMA trend juga align. Reduces false signals significantly.

4. News Filter

Disable EA saat news event major (NFP, FOMC). Pakai Calendar API di MQL5 untuk auto-detect.

5. Multi-Asset Bot

Run EA sama di V75 + V100 + EURUSD parallel. Diversifikasi risk.

Best Practices

✓ Production Checklist

Sebelum live trading dengan real money:
1. ✓ Backtest 6+ bulan data historical, profit factor > 1.5
2. ✓ Demo trade 30+ hari, hasil serupa backtest
3. ✓ Risk maksimal 1-2% per trade
4. ✓ Daily loss limit 5%
5. ✓ Monitor logs & performance setiap hari
6. ✓ Backup code di GitHub atau cloud
7. ✓ Start dengan lot size minimum (0.01)

Risiko & Limitations

  • AI bisa generate buggy code: Selalu compile dan test extensively
  • Backtest ≠ Live: Slippage dan spread di live bisa hancurkan strategy yang work di backtest
  • Synthetic ≠ Forex: V75 punya karakteristik unik, strategy yang work di V75 belum tentu work di EURUSD
  • VPS recommended: EA butuh komputer nyala 24/7 — pakai VPS untuk reliability
  • Broker policy: Deriv allow EA, tapi check terms of service untuk activity yang permitted

🚀 Deploy EA di demo Deriv MT5 (gratis, $10,000 / ~Rp 158 jt virtual):

Buka Demo Deriv Gratis

Topik Terkait

DM

Dan Machado

Founder IA Trader Pro · MQL5 developer · 50+ EA generated dengan AI

⚠️ Disclaimer: AI-generated code harus selalu di-test sebelum live trading. Expert Advisors tidak menjamin profit. Trading binary options dan derivatif memiliki risiko tinggi kehilangan modal. Deriv tidak diregulasi Bappebti Indonesia. Artikel ini mengandung affiliate link Deriv. Disclaimer lengkap.

Similar Posts