SiamCafe · Blog
Color MQL4 — คู่มือเทรด Forex ด้วย MQL4
บทความ

Color MQL4 — คู่มือเทรด Forex ด้วย MQL4

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

Color MQL4 Forex

Color MQL4 — คู่มือเทรด Forex ด้วย MQL4

MQL4 MetaQuotes Language MetaTrader 4 Expert Advisor Custom Indicator Color RGB Hex Chart Objects Trading Automation Forex Backtest Strategy Tester

MQL4 Programไฟล์หน้าที่ตัวอย่าง
Expert Advisor.mq4/.ex4เทรดอัตโนมัติMA Crossover EA
Custom Indicator.mq4/.ex4วิเคราะห์กราฟCustom RSI Color
Script.mq4/.ex4สั่งงานครั้งเดียวClose All Orders
Library.mqhไลบรารีTrade Functions

MQL4 Color และ Indicator

=== MQL4 Color Data Type ===

อ่านเพิ่ม: Shopify Hydrogen Best Practices ที่ต้องรู้ — สร้าง Headless · อ่านเพิ่ม: MLOps Pipeline Tech Conference 2026 — สร้าง ML Pipeline สำหร · อ่านเพิ่ม: MLflow Experiment Tech Conference 2026 — จัดการ ML Experimen

Color Formats

color clr1 = clrRed; // Named color

color clr2 = C'255,0,0'; // RGB format

color clr3 = 0xFF0000; // Hex format

=== Custom RSI Indicator with Color ===

#property indicator_separate_window

#property indicator_buffers 3

#property indicator_color1 clrLime // RSI line

#property indicator_color2 clrRed // Overbought zone

#property indicator_color3 clrDodgerBlue // Oversold zone

#property indicator_width1 2

input int RSI_Period = 14;

input int Overbought = 70;

input int Oversold = 30;

input color ColorUp = clrLime;

input color ColorDown = clrRed;

input color ColorNeutral = clrGray;

double RSI_Buffer[];

double ColorUp_Buffer[];

double ColorDown_Buffer[];

int OnInit() {

SetIndexBuffer(0, RSI_Buffer);

SetIndexBuffer(1, ColorUp_Buffer);

SetIndexBuffer(2, ColorDown_Buffer);

SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 2);

SetIndexLabel(0, "RSI(" + IntegerToString(RSI_Period) + ")");

// Level lines

IndicatorSetInteger(INDICATOR_LEVELCOLOR, 0, clrRed);

IndicatorSetInteger(INDICATOR_LEVELCOLOR, 1, clrDodgerBlue);

IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, Overbought);

IndicatorSetDouble(INDICATOR_LEVELVALUE, 1, Oversold);

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(RSI_Period, prev_calculated - 1);

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

RSI_Buffer[i] = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, rates_total - 1 - i);

// Change color based on RSI value

if (RSI_Buffer[i] > Overbought)

SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 2, ColorDown);

else if (RSI_Buffer[i] < Oversold)

SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 2, ColorUp);

else

SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 2, ColorNeutral);

}

return rates_total;

}

MQL4 Color Constants

color_names = {

"clrRed": "0xFF0000 — ขาลง Bearish",

"clrLime": "0x00FF00 — ขาขึ้น Bullish",

"clrBlue": "0x0000FF — Information",

"clrYellow": "0xFFFF00 — Warning Signal",

"clrWhite": "0xFFFFFF — Background Text",

"clrGold": "0xFFD700 — Important Level",

"clrDodgerBlue": "0x1E90FF — Support Level",

"clrOrangeRed": "0xFF4500 — Resistance Level",

}

print("=== MQL4 Color Constants ===")

for name, desc in color_names.items():

print(f" {name}: {desc}")

Expert Advisor Development

=== Simple MA Crossover EA ===

input int FastMA = 10;

input int SlowMA = 20;

input double LotSize = 0.1;

input int StopLoss = 50; // points

input int TakeProfit = 100; // points

input int MagicNumber = 12345;

input color ArrowBuy = clrLime;

input color ArrowSell = clrRed;

int OnInit() {

return INIT_SUCCEEDED;

}

void OnTick() {

// Check if we already have an open order

if (OrdersTotal() > 0) {

for (int i = OrdersTotal() - 1; i >= 0; i--) {

if (OrderSelect(i, SELECT_BY_POS) &&

OrderMagicNumber() == MagicNumber) {

return; // Already have position

}

}

}

// Calculate MA values

double fastMA_current = iMA(NULL, 0, FastMA, 0, MODE_EMA, PRICE_CLOSE, 0);

double fastMA_prev = iMA(NULL, 0, FastMA, 0, MODE_EMA, PRICE_CLOSE, 1);

double slowMA_current = iMA(NULL, 0, SlowMA, 0, MODE_EMA, PRICE_CLOSE, 0);

double slowMA_prev = iMA(NULL, 0, SlowMA, 0, MODE_EMA, PRICE_CLOSE, 1);

// Buy Signal: Fast MA crosses above Slow MA

if (fastMA_prev < slowMA_prev && fastMA_current > slowMA_current) {

double sl = Ask - StopLoss * Point;

double tp = Ask + TakeProfit * Point;

int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3,

sl, tp, "MA Cross Buy", MagicNumber, 0, ArrowBuy);

if (ticket > 0)

Print("BUY Order opened: ", ticket);

}

// Sell Signal: Fast MA crosses below Slow MA

if (fastMA_prev > slowMA_prev && fastMA_current < slowMA_current) {

double sl = Bid + StopLoss * Point;

double tp = Bid - TakeProfit * Point;

int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3,

sl, tp, "MA Cross Sell", MagicNumber, 0, ArrowSell);

if (ticket > 0)

Print("SELL Order opened: ", ticket);

}

}

Chart Objects with Color

void DrawLine(string name, datetime time1, double price1,

datetime time2, double price2, color clr) {

ObjectCreate(0, name, OBJ_TREND, 0, time1, price1, time2, price2);

ObjectSetInteger(0, name, OBJPROP_COLOR, clr);

ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);

ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, false);

}

void DrawArrow(string name, datetime time, double price,

int code, color clr) {

ObjectCreate(0, name, OBJ_ARROW, 0, time, price);

ObjectSetInteger(0, name, OBJPROP_ARROWCODE, code);

ObjectSetInteger(0, name, OBJPROP_COLOR, clr);

ObjectSetInteger(0, name, OBJPROP_WIDTH, 2);

}

from dataclasses import dataclass

@dataclass

class EAConfig:

Color MQL4 — คู่มือเทรด Forex ด้วย MQL4

name: str

strategy: str

timeframe: str

pairs: str

risk_pct: float

backtest_profit_factor: float

eas = [

EAConfig("MA Crossover", "EMA 10/20 Cross", "H1", "EURUSD GBPUSD", 2.0, 1.45),

EAConfig("RSI Reversal", "RSI 14 OB/OS", "", "EURUSD USDJPY", 1.5, 1.32),

EAConfig("Breakout", "Bollinger Bands Break", "H4", "GBPUSD AUDUSD", 2.0, 1.58),

EAConfig("Scalper", "Stochastic + MA Filter", "M5", "EURUSD", 1.0, 1.25),

]

print("\n=== Expert Advisors ===")

for ea in eas:

print(f" [{ea.name}] {ea.strategy}")

print(f" TF: {ea.timeframe} | Pairs: {ea.pairs}")

print(f" Risk: {ea.risk_pct}% | PF: {ea.backtest_profit_factor}")

Backtesting

# backtest_results.py — Strategy Tester Results
from dataclasses import dataclass

@dataclass
class BacktestResult:
    ea_name: str
    symbol: str
    timeframe: str
    period: str
    initial_deposit: float
    net_profit: float
    profit_factor: float
    max_drawdown_pct: float
    total_trades: int
    win_rate: float
    sharpe_ratio: float

results = [
    BacktestResult("MA Crossover", "EURUSD", "H1", "2023-2024",
                   10000, 2350, 1.45, 12.3, 156, 58.3, 1.2),
    BacktestResult("RSI Reversal", "EURUSD", "", "2023-2024",
                   10000, 1850, 1.32, 15.7, 312, 52.1, 0.9),
    BacktestResult("Breakout", "GBPUSD", "H4", "2023-2024",
                   10000, 3100, 1.58, 10.5, 89, 61.8, 1.5),
    BacktestResult("Scalper", "EURUSD", "M5", "2023-2024",
                   10000, 1200, 1.25, 18.2, 520, 55.0, 0.7),
]

print("=== Backtest Results ===\n")
for r in results:
    roi = (r.net_profit / r.initial_deposit) * 100
    print(f"  [{r.ea_name}] {r.symbol} {r.timeframe} ({r.period})")
    print(f"    Profit:  (ROI: {roi:.1f}%)")
    print(f"    PF: {r.profit_factor} | DD: {r.max_drawdown_pct}% | "
          f"Win: {r.win_rate}% | Trades: {r.total_trades}")
    print(f"    Sharpe: {r.sharpe_ratio}\n")

# Risk Management Rules
risk_rules = [
    "Risk ไม่เกิน 1-2% ต่อ Trade",
    "Max Drawdown ไม่เกิน 20%",
    "ใช้ Stop Loss ทุก Order",
    "Profit Factor ต้อง > 1.3",
    "Win Rate ต้อง > 50%",
    "Backtest อย่างน้อย 1 ปี",
    "Forward Test 3 เดือนก่อนใช้จริง",
    "เริ่มด้วย Lot Size เล็ก",
]

print("Risk Management Rules:")
for i, rule in enumerate(risk_rules, 1):
    print(f"  {i}. {rule}")

เคล็ดลับ

  • Color: ใช้สีสม่ำเสมอ เขียว=ซื้อ แดง=ขาย น้ำเงิน=ข้อมูล
  • Backtest: ใช้ Every Tick Model ผลลัพธ์แม่นที่สุด
  • Risk: ไม่เกิน 2% ต่อ Trade ใช้ Stop Loss เสมอ
  • Forward Test: ทดสอบ Demo 3 เดือนก่อนใช้เงินจริง
  • Optimization: ระวัง Over-fitting เมื่อ Optimize Parameters

MQL4 คืออะไร

MetaQuotes Language 4 MetaTrader 4 Expert Advisors Custom Indicators Scripts Libraries คล้ายภาษา C Trading Order Management