自訂指標教學:從零開始撰寫 MQL5 移動平均線指標

📌 本文重點:學習撰寫 MQL5 自訂指標,以移動平均線為例,掌握 OnCalculate()、Buffer 設計、在 EA 中呼叫自訂指標的完整流程。

什麼是自訂指標?

MQL5 自訂指標讓你將任何技術分析演算法視覺化,直接繪製在 MT5 圖表上。內建的 MA、RSI、MACD 都是以相同原理實現的。

指標基本結構

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "SMA"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2

input int InpPeriod = 14;
double g_maBuffer[];

int OnInit()
{
    SetIndexBuffer(0, g_maBuffer, INDICATOR_DATA);
    PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpPeriod - 1);
    IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("SMA(%d)", InpPeriod));
    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[])
{
    if (rates_total < InpPeriod) return 0;
    int startPos = (prev_calculated > 0) ? prev_calculated - 1 : InpPeriod - 1;
    for (int i = startPos; i < rates_total; i++)
    {
        double sum = 0;
        for (int j = 0; j < InpPeriod; j++) sum += close[i - j];
        g_maBuffer[i] = sum / InpPeriod;
    }
    return rates_total;
}

在 EA 中呼叫自訂指標

int g_indHandle = INVALID_HANDLE;

int OnInit()
{
    g_indHandle = iCustom(_Symbol, _Period, "SimpleMA", InpPeriod);
    if (g_indHandle == INVALID_HANDLE) return INIT_FAILED;
    return INIT_SUCCEEDED;
}

void OnTick()
{
    double maVal[2];
    ArraySetAsSeries(maVal, true);
    if (CopyBuffer(g_indHandle, 0, 0, 2, maVal) < 2) return;
    Print("MA[1]: ", maVal[1]);  // 使用已完成K線的值
}

void OnDeinit(const int reason) { IndicatorRelease(g_indHandle); }

本文由 James Lee 撰寫。內容僅供教育目的。

Similar Posts

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *