⚙️ MQL5 Tutorial

Expert Advisor AI cho MT5 (Deriv) — Tutorial MQL5 Đầy Đủ

Bởi Dan Machado · 16 phút đọc · Code production-ready

Expert Advisor (EA) là automated trading robot cho MT5. Khác với Deriv Bot (drag-drop) và Python (external), EA chạy native trong MT5 platform, integration tight với charts và execution. Tutorial này show cách build EA MQL5 với AI assistance.

📋 Prerequisites

1. MT5 installed (download từ Deriv: link)
2. Deriv MT5 demo account (free)
3. Basic understanding của OOP concepts
4. ChatGPT/Claude cho code generation

MT5 EA vs Deriv Bot vs Python

  • Deriv Bot: Easiest, no-code, browser-only, binary options focused
  • MT5 EA: Native, fast execution, forex/synthetic CFDs, runs without browser
  • Python: Most flexible, ML integration, requires VPS

EA best for: trader manual MT5 trước đây muốn automate, hoặc cần backtest sâu với Strategy Tester built-in.

Anatomy của MQL5 EA

Mọi EA có 3 functions chính:

▸ MQL5 · EA Structure
// Triggered once khi EA attached to chart
int OnInit() {
    // Initialize: set parameters, validate inputs
    return INIT_SUCCEEDED;
}

// Triggered on every tick (price update)
void OnTick() {
    // Main logic: check conditions, place trades
}

// Triggered khi EA removed
void OnDeinit(const int reason) {
    // Cleanup: close positions, save state
}

AI Prompt để Generate EA

Pakai prompt này với ChatGPT/Claude:

📋 PROMPT

“Bạn là MQL5 expert. Tạo EA cho MT5 với specifications:
– Asset: Volatility 75 Index (Deriv)
– Strategy: RSI(14) — Buy khi < 30, Sell khi > 70
– Position sizing: 2% balance per trade
– Stop loss: 50 pips, Take profit: 100 pips
– Max concurrent positions: 1
– Trading hours: 24/7 (Deriv synthetic)
– Magic number: 20260513
Include: OnInit validation, OnTick logic, position sizing function, error handling. Output complete .mq5 file ready compile.”

Code Complete EA

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

#include <Trade\Trade.mqh>

// === INPUT PARAMETERS ===
input group "=== Strategy ==="
input int    RSI_Period = 14;
input double RSI_Oversold = 30.0;
input double RSI_Overbought = 70.0;

input group "=== Risk Management ==="
input double RiskPercent = 2.0;       // Risk per trade %
input int    StopLossPips = 50;       // SL in pips
input int    TakeProfitPips = 100;    // TP in pips
input int    MaxPositions = 1;        // Max concurrent positions

input group "=== EA Settings ==="
input ulong  MagicNumber = 20260513;  // Unique identifier
input int    Slippage = 10;           // Max slippage in pips

// === GLOBAL VARIABLES ===
CTrade trade;
int rsi_handle;
double rsi_buffer[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
    // Validate inputs
    if (RSI_Period < 2) {
        Print("ERROR: RSI_Period must be >= 2");
        return INIT_FAILED;
    }
    if (RiskPercent <= 0 || RiskPercent > 10) {
        Print("ERROR: RiskPercent must be between 0 and 10");
        return INIT_FAILED;
    }
    
    // Initialize RSI indicator
    rsi_handle = iRSI(_Symbol, PERIOD_M5, RSI_Period, PRICE_CLOSE);
    if (rsi_handle == INVALID_HANDLE) {
        Print("ERROR: Failed to create RSI indicator");
        return INIT_FAILED;
    }
    
    // Set buffer as series
    ArraySetAsSeries(rsi_buffer, true);
    
    // Configure trade object
    trade.SetExpertMagicNumber(MagicNumber);
    trade.SetDeviationInPoints(Slippage);
    trade.SetTypeFilling(ORDER_FILLING_FOK);
    
    Print("✓ IATraderPro EA initialized for ", _Symbol);
    Print("  RSI Period: ", RSI_Period, " | Risk: ", RiskPercent, "%");
    Print("  SL: ", StopLossPips, " pips | TP: ", TakeProfitPips, " pips");
    
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
    IndicatorRelease(rsi_handle);
    Print("EA deinitialized. Reason: ", reason);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
    // Only process on new bar to avoid over-trading
    static datetime last_bar_time = 0;
    datetime current_bar_time = iTime(_Symbol, PERIOD_M5, 0);
    if (current_bar_time == last_bar_time) return;
    last_bar_time = current_bar_time;
    
    // Check max positions
    if (CountOpenPositions() >= MaxPositions) return;
    
    // Get RSI value
    if (CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer) < 3) {
        Print("ERROR: Failed to copy RSI buffer");
        return;
    }
    
    double rsi_current = rsi_buffer[0];
    double rsi_previous = rsi_buffer[1];
    
    // BUY signal: RSI crosses up from oversold
    if (rsi_previous <= RSI_Oversold && rsi_current > RSI_Oversold) {
        OpenPosition(ORDER_TYPE_BUY);
    }
    // SELL signal: RSI crosses down from overbought
    else if (rsi_previous >= RSI_Overbought && rsi_current < RSI_Overbought) {
        OpenPosition(ORDER_TYPE_SELL);
    }
}

//+------------------------------------------------------------------+
//| Open position with calculated lot size                           |
//+------------------------------------------------------------------+
void OpenPosition(ENUM_ORDER_TYPE order_type) {
    double price = (order_type == ORDER_TYPE_BUY) ? 
                   SymbolInfoDouble(_Symbol, SYMBOL_ASK) :
                   SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
    double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
    int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
    double sl_distance = StopLossPips * point * 10;
    double tp_distance = TakeProfitPips * point * 10;
    
    double sl_price, tp_price;
    if (order_type == ORDER_TYPE_BUY) {
        sl_price = NormalizeDouble(price - sl_distance, digits);
        tp_price = NormalizeDouble(price + tp_distance, digits);
    } else {
        sl_price = NormalizeDouble(price + sl_distance, digits);
        tp_price = NormalizeDouble(price - tp_distance, digits);
    }
    
    double lot_size = CalculateLotSize(sl_distance);
    
    // Place order
    bool result = false;
    if (order_type == ORDER_TYPE_BUY) {
        result = trade.Buy(lot_size, _Symbol, price, sl_price, tp_price, "IATraderPro RSI");
    } else {
        result = trade.Sell(lot_size, _Symbol, price, sl_price, tp_price, "IATraderPro RSI");
    }
    
    if (result) {
        string dir = (order_type == ORDER_TYPE_BUY) ? "BUY" : "SELL";
        Print("✓ ", dir, " order placed. Lot: ", lot_size, " SL: ", sl_price, " TP: ", tp_price);
    } else {
        Print("✗ Order failed. Error: ", trade.ResultRetcode(), " - ", trade.ResultComment());
    }
}

//+------------------------------------------------------------------+
//| Calculate lot size based on risk percent                        |
//+------------------------------------------------------------------+
double CalculateLotSize(double sl_distance) {
    double balance = AccountInfoDouble(ACCOUNT_BALANCE);
    double risk_amount = balance * RiskPercent / 100.0;
    
    double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    
    double lot_size = risk_amount / (sl_distance / tick_size * tick_value);
    
    // Normalize to broker constraints
    double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
    double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
    
    lot_size = MathRound(lot_size / lot_step) * lot_step;
    lot_size = MathMax(min_lot, MathMin(max_lot, lot_size));
    
    return lot_size;
}

//+------------------------------------------------------------------+
//| Count current open positions for this EA                        |
//+------------------------------------------------------------------+
int CountOpenPositions() {
    int count = 0;
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        ulong ticket = PositionGetTicket(i);
        if (PositionSelectByTicket(ticket)) {
            if (PositionGetInteger(POSITION_MAGIC) == MagicNumber &&
                PositionGetString(POSITION_SYMBOL) == _Symbol) {
                count++;
            }
        }
    }
    return count;
}
//+------------------------------------------------------------------+

Install EA trong MT5

  1. Mở MetaEditor: Trong MT5, click Tools → MetaQuotes Language Editor (F4)
  2. Tạo new EA: File → New → Expert Advisor
  3. Đặt tên: “IATraderPro_V75_RSI”
  4. Replace code: Paste code trên thay default template
  5. Compile: F7. Phải hiển thị “0 errors, 0 warnings”
  6. Back to MT5: Reload Navigator panel. EA sẽ xuất hiện ở “Expert Advisors”
  7. Attach to chart: Drag EA vào chart V75
  8. Configure inputs trong popup window
  9. Allow algorithmic trading: Click “Algo Trading” button trong toolbar

Detail install: MT5 Deriv: Cách Install & Run EA.

Backtest với Strategy Tester

Trước khi live, backtest:

  1. Trong MT5: View → Strategy Tester (Ctrl+R)
  2. Select EA: IATraderPro_V75_RSI
  3. Symbol: Volatility 75 Index
  4. Period: M5
  5. Date range: 3-6 tháng historical
  6. Modeling: “Every tick based on real ticks” (most accurate)
  7. Click “Start”
  8. Wait — backtest có thể mất 5-30 phút

Results phải show:

  • Profit factor > 1.3: Lý tưởng > 1.5
  • Max drawdown < 20%: Sustainable
  • Win rate 55-70%: Realistic
  • 30+ trades: Statistical significance

Optimize Parameters

Strategy Tester có “Optimization” mode để find best parameters:

  1. Enable “Optimization” trong Strategy Tester
  2. Check inputs có thể vary (RSI_Period, RSI_Oversold)
  3. Define ranges (RSI_Period: 10-20 step 2)
  4. Run — MT5 test mọi combination
  5. Top results displayed sorted by Profit Factor

⚠️ Overfitting Warning

Đừng optimize quá. Best params trên historical data thường fail forward. Rule of thumb: 2-3 parameters max, ranges reasonable, walk-forward test sau optimization.

Improvements Advanced

  • Trailing Stop: Move SL theo price favorable
  • News filter: Pause EA trước/sau major news (FOMC, NFP)
  • Trading hours filter: Chỉ trade certain hours
  • Multiple indicators: RSI + MACD + EMA confluence
  • Telegram alerts: Send notifications khi trade open/close
  • Equity protection: Stop EA khi daily loss > 5%

Run EA 24/7

EA chỉ chạy khi MT5 mở. Để chạy 24/7:

  1. Local PC: Không khuyến nghị — sleep mode, power off issues
  2. VPS recommended:
    • Deriv VPS ($25/month, automatic setup)
    • Beeks Financial Cloud ($35/month, low latency)
    • Generic VPS (DigitalOcean $6/month + manual MT5 install)
  3. Setup: Install MT5 trên VPS, attach EA, leave running
  4. Monitor: Mobile MT5 app để check positions remotely

Common Errors & Fixes

🐛 Troubleshooting

“Trade is disabled”: Click “Algo Trading” button trong MT5 toolbar.
“Not enough money”: Lot size quá lớn cho balance. Reduce RiskPercent.
“Invalid stops”: SL/TP quá gần price (less than broker min). Increase StopLossPips.
“Compile error”: Pakai MQL5 (không MQL4) version. Check #property strict.
“No quotes”: Symbol không in Market Watch. Right-click → “Show all”.

🚀 Cần MT5 Deriv account? Mở demo miễn phí:

Mở Demo Deriv MT5

Bài Liên Quan

DM

Dan Machado

Founder IA Trader Pro · MQL5 developer · 50+ EAs built

⚠️ Disclaimer: Code production-ready nhưng cần backtest + demo test 30+ ngày trước live. Trading có rủi ro mất vốn cao. Deriv không được cấp phép bởi SBV. Bài viết này có chứa affiliate link Deriv. Disclaimer đầy đủ.