SiamCafe · Blog
Prado MQL5 — คู่มือเทรด Forex ด้วย MQL5 ฉบับสมบูรณ์
บทความ

Prado MQL5 — คู่มือเทรด Forex ด้วย MQL5 ฉบับสมบูรณ์

เผยแพร่ 28 พฤษภาคม 2569

Prado MQL5 Forex

Prado MQL5 — คู่มือเทรด Forex ด้วย MQL5 ฉบับสมบูรณ์

MQL5 MetaTrader 5 OOP Expert Advisor Indicator Prado Machine Learning Technical Analysis Triple Barrier Fractional Differentiation Strategy Tester Multi-currency

FeatureMQL4MQL5
ProgrammingProceduralOOP + Procedural
MarketsForexForex, Stocks, Futures, Crypto
TesterSingle CurrencyMulti-currency
AccountHedgingNetting + Hedging
Speedช้ากว่าเร็วกว่า 5-20x
Cloudไม่มีMQL5 Cloud Network

MQL5 Indicator Development

=== Prado-inspired Custom Indicator ===

#property indicator_separate_window

#property indicator_buffers 4

#property indicator_plots 2

#property indicator_color1 clrLime

#property indicator_color2 clrRed

#property indicator_width1 2

#property indicator_width2 2

input int Period = 20;

input double Threshold = 0.5;

input ENUM_APPLIED_PRICE PriceType = PRICE_CLOSE;

double SignalBuffer[];

double UpperBuffer[];

double LowerBuffer[];

double TrendBuffer[];

int OnInit() {

SetIndexBuffer(0, SignalBuffer, INDICATOR_DATA);

SetIndexBuffer(1, TrendBuffer, INDICATOR_DATA);

SetIndexBuffer(2, UpperBuffer, INDICATOR_CALCULATIONS);

SetIndexBuffer(3, LowerBuffer, INDICATOR_CALCULATIONS);

PlotIndexSetString(0, PLOT_LABEL, "Prado Signal");

PlotIndexSetString(1, PLOT_LABEL, "Trend");

IndicatorSetString(INDICATOR_SHORTNAME,

"Prado(" + IntegerToString(Period) + ")");

return INIT_SUCCEEDED;

}

int OnCalculate(const int rates_total,

const int prev_calculated,

const datetime &time[],

const double &open[],

const double &high[],

const double &low[],

const double &close[],

const long &tick_volume[],

const long &volume[],

const int &spread[]) {

int start = MathMax(Period, prev_calculated - 1);

for (int i = start; i < rates_total; i++) {

// Calculate rolling statistics

double sum = 0, sumSq = 0;

for (int j = i - Period + 1; j <= i; j++) {

sum += close[j];

sumSq += close[j] * close[j];

}

double mean = sum / Period;

double std = MathSqrt(sumSq / Period - mean * mean);

// Fractional differentiation approximation

double diff = (close[i] - close[i-1]) / (std > 0 ? std : 1);

SignalBuffer[i] = diff;

UpperBuffer[i] = Threshold;

LowerBuffer[i] = -Threshold;

TrendBuffer[i] = (diff > Threshold) ? 1 :

(diff < -Threshold) ? -1 : 0;

}

return rates_total;

}

from dataclasses import dataclass

from typing import List

@dataclass

class MQL5Indicator:

name: str

type: str

buffers: int

inputs: List[str]

description: str

indicators = [

MQL5Indicator("Prado Signal", "Separate Window", 4,

["Period=20", "Threshold=0.5"],

"Fractional diff + std normalization"),

MQL5Indicator("Triple Barrier", "Chart Window", 3,

["TP_pips=50", "SL_pips=30", "MaxBars=100"],

"Triple barrier labeling visualization"),

MQL5Indicator("Volume Clock", "Separate Window", 2,

["VolumeThreshold=1000"],

"Volume-based sampling bars"),

MQL5Indicator("CUSUM Filter", "Separate Window", 2,

["Threshold=0.01"],

"Cumulative sum event detection"),

]

print("=== MQL5 Custom Indicators ===")

for ind in indicators:

print(f"\n [{ind.name}] Type: {ind.type}")

print(f" Buffers: {ind.buffers}")

print(f" Inputs: {', '.join(ind.inputs)}")

print(f" {ind.description}")

Expert Advisor OOP

=== MQL5 OOP Expert Advisor ===

#include <trade trade.mqh="">

#include <trade positioninfo.mqh="">

class CTradeStrategy {

private:

CTrade m_trade;

CPositionInfo m_position;

int m_fastMA_handle;

int m_slowMA_handle;

double m_fastMA[];

double m_slowMA[];

public:

int FastPeriod;

int SlowPeriod;

double LotSize;

int StopLoss;

int TakeProfit;

ulong MagicNumber;

bool Init() {

m_trade.SetExpertMagicNumber(MagicNumber);

m_fastMA_handle = iMA(_Symbol, PERIOD_CURRENT,

FastPeriod, 0, MODE_EMA, PRICE_CLOSE);

m_slowMA_handle = iMA(_Symbol, PERIOD_CURRENT,

SlowPeriod, 0, MODE_EMA, PRICE_CLOSE);

if (m_fastMA_handle == INVALID_HANDLE) return false;

if (m_slowMA_handle == INVALID_HANDLE) return false;

ArraySetAsSeries(m_fastMA, true);

ArraySetAsSeries(m_slowMA, true);

return true;

}

void CheckSignal() {

CopyBuffer(m_fastMA_handle, 0, 0, 3, m_fastMA);

CopyBuffer(m_slowMA_handle, 0, 0, 3, m_slowMA);

// Buy: Fast crosses above Slow

if (m_fastMA[1] &lt; m_slowMA[1] &amp;&amp; m_fastMA[0] &gt; m_slowMA[0]) {

if (!HasPosition(POSITION_TYPE_BUY))

OpenBuy();

}

// Sell: Fast crosses below Slow

if (m_fastMA[1] &gt; m_slowMA[1] &amp;&amp; m_fastMA[0] &lt; m_slowMA[0]) {

if (!HasPosition(POSITION_TYPE_SELL))

OpenSell();

}

}

void OpenBuy() {

double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

double sl = ask - StopLoss * _Point;

double tp = ask + TakeProfit * _Point;

m_trade.Buy(LotSize, _Symbol, ask, sl, tp, "MA Cross Buy");

}

bool HasPosition(ENUM_POSITION_TYPE type) {

for (int i = PositionsTotal() - 1; i &gt;= 0; i--) {

if (m_position.SelectByIndex(i) &amp;&amp;

m_position.Magic() == MagicNumber &amp;&amp;

m_position.PositionType() == type)

return true;

}

return false;

}

};

CTradeStrategy strategy;

int OnInit() {

strategy.FastPeriod = 10;

strategy.SlowPeriod = 20;

strategy.LotSize = 0.1;

strategy.StopLoss = 500;

strategy.TakeProfit = 1000;

strategy.MagicNumber = 54321;

return strategy.Init() ? INIT_SUCCEEDED : INIT_FAILED;

}

void OnTick() { strategy.CheckSignal(); }

@dataclass

class BacktestResult:

Prado MQL5 — คู่มือเทรด Forex ด้วย MQL5 ฉบับสมบูรณ์

ea: str

symbol: str

period: str

net_profit: float

profit_factor: float

max_drawdown: float

win_rate: float

trades: int

sharpe: float

results = [

BacktestResult("Prado MA Cross", "EURUSD", "2023-2024", 4250, 1.62, 8.5, 61.2, 145, 1.4),

BacktestResult("Triple Barrier", "GBPUSD", "2023-2024", 3800, 1.48, 11.2, 57.8, 198, 1.1),

BacktestResult("Volume Clock", "USDJPY", "2023-2024", 2900, 1.35, 13.5, 54.3, 267, 0.9),

BacktestResult("CUSUM Breakout", "EURUSD", "2023-2024", 5100, 1.72, 7.8, 63.5, 112, 1.6),

]

print("\n=== Backtest Results ===")

for r in results:

roi = (r.net_profit / 10000) * 100

print(f" [{r.ea}] {r.symbol} {r.period}")

print(f" Profit: (ROI: {roi:.1f}%) | PF: {r.profit_factor}")

print(f" DD: {r.max_drawdown}% | Win: {r.win_rate}% | Sharpe: {r.sharpe}")</trade></trade>

Risk Management

# risk_management.py — Position Sizing & Risk
from dataclasses import dataclass

@dataclass
class RiskManager:
 balance: float
 risk_pct: float
 stop_loss_pips: int
 pip_value: float

 @property
 def risk_amount(self) -> float:
 return self.balance * (self.risk_pct / 100)

 @property
 def lot_size(self) -> float:
 if self.stop_loss_pips == 0:
 return 0
 return round(self.risk_amount / (self.stop_loss_pips * self.pip_value), 2)

 @property
 def max_loss(self) -> float:
 return self.lot_size * self.stop_loss_pips * self.pip_value

rm = RiskManager(balance=10000, risk_pct=2, stop_loss_pips=50, pip_value=10)

print("=== Risk Management ===")
print(f" Balance: ")
print(f" Risk: {rm.risk_pct}% = ")
print(f" SL: {rm.stop_loss_pips} pips")
print(f" Lot Size: {rm.lot_size}")
print(f" Max Loss: ")

# Kelly Criterion
def kelly_criterion(win_rate, avg_win, avg_loss):
 if avg_loss == 0:
 return 0
 b = avg_win / avg_loss
 p = win_rate / 100
 q = 1 - p
 kelly = (b * p - q) / b
 return max(0, kelly)

strategies = [
 {"name": "Conservative", "win": 60, "avg_w": 100, "avg_l": 80},
 {"name": "Balanced", "win": 55, "avg_w": 150, "avg_l": 100},
 {"name": "Aggressive", "win": 50, "avg_w": 200, "avg_l": 100},
]

print(f"\n\nKelly Criterion:")
for s in strategies:
 k = kelly_criterion(s["win"], s["avg_w"], s["avg_l"])
 print(f" [{s['name']}] Win: {s['win']}% | "
 f"W/L: {s['avg_w']}/{s['avg_l']} | "
 f"Kelly: {k:.1%} | Half-Kelly: {k/2:.1%}")

เคล็ดลับ

  • OOP: ใช้ OOP ใน MQL5 จัด Code เป็น Classes Reusable
  • Multi-currency: ทดสอบ Strategy หลายคู่เงินพร้อมกัน
  • Kelly: ใช้ Half-Kelly สำหรับ Position Sizing ปลอดภัยกว่า
  • Cloud: ใช้ MQL5 Cloud Network สำหรับ Optimization เร็วขึ้น
  • Forward Test: ทำ Forward Test 3 เดือน Demo ก่อนใช้จริง

MQL5 คืออะไร

MetaQuotes Language 5 MetaTrader 5 OOP Standard Library Multi-currency Forex Stocks Futures Crypto MQL5 Cloud Optimization

Prado Indicator คืออะไร

Marcos Lopez de Prado Machine Learning Technical Analysis Triple Barrier Fractional Differentiation Meta-labeling Strategy ประสิทธิภาพ

MQL5 กับ MQL4 ต่างกันอย่างไร

MQL5 OOP Classes Multi-currency Netting Hedging หลายตลาด เร็วกว่า MQL4 Procedural Single Currency Hedging Forex แนะนำ MQL5

Backtest MQL5 ต่างจาก MQL4 อย่างไร

Multi-currency Forward Testing Genetic Algorithm Cloud Network Visual Mode Real Tick Mode แม่นยำ ดีกว่า MQL4 ทุกด้าน

สรุป

MQL5 MetaTrader 5 OOP Prado Indicator Machine Learning Triple Barrier Expert Advisor Strategy Tester Multi-currency Risk Management Kelly Criterion Position Sizing Forward Test Cloud Optimization