編寫MT5指標
今天寫一個相當簡單的指標,如上圖:
先搞清楚一下思路,需要在圖上畫什么,如何寫。在主圖上需要畫出四個圖標,兩條均線(一個小周期一個大周期),兩個箭頭(一個向上指標,一個向下指),另外一點是當境均線形成金叉時出現向上箭頭,當兩均線死叉時出現在向下箭頭,這是所有的需求了,好簡單吧。
我把帶有注釋的全部代碼先貼上來:
#property indicator_chart_window //指標畫在主圖上
#include <MovingAverages.mqh> //引入標準庫文件
#property indicator_buffers 4 //要用四個緩沖區,也就是四個數組
#property indicator_plots 4 //雨需要畫出的四個圖標
//--- plot redline
#property indicator_label1 "redline" //紅色均線基本樣式
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- plot blueline
#property indicator_label2 "blueline" //藍色均線基本樣式
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrMediumBlue
#property indicator_style2 STYLE_SOLID
#property indicator_width2 1
//--- plot up
#property indicator_label3 "up" //向上箭頭的基本樣式
#property indicator_type3 DRAW_ARROW
#property indicator_color3 clrAqua
#property indicator_style3 STYLE_SOLID
#property indicator_width3 1
//--- plot down
#property indicator_label4 "down" //向下箭頭的基本樣式
#property indicator_type4 DRAW_ARROW
#property indicator_color4 clrYellow
#property indicator_style4 STYLE_SOLID
#property indicator_width4 1
//--- indicator buffers 指標所需的數組
double redlineBuffer[];
double bluelineBuffer[];
double upBuffer[];
double downBuffer[];
//外部可輸入參數變量
input int fastperiod=5;
input int slowperiod=10;
//指標初始化
int OnInit()
{
//綁定指標數據
SetIndexBuffer(0,redlineBuffer,INDICATOR_DATA);
SetIndexBuffer(1,bluelineBuffer,INDICATOR_DATA);
SetIndexBuffer(2,upBuffer,INDICATOR_DATA);
SetIndexBuffer(3,downBuffer,INDICATOR_DATA);
//設置箭頭樣式
PlotIndexSetInteger(2,PLOT_ARROW,233);
PlotIndexSetInteger(3,PLOT_ARROW,234);
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 i,start;
if(prev_calculated==0)start=slowperiod-1;
else start=prev_calculated-1;
//主循環
for(i=start;i<rates_total;i++)
{
//畫均線
redlineBuffer[i]=SimpleMA(i,fastperiod,close);
bluelineBuffer[i]=SimpleMA(i,slowperiod,close);
//畫箭頭
if(redlineBuffer[i]>bluelineBuffer[i] && redlineBuffer[i-1]<bluelineBuffer[i-1]) upBuffer[i]=low[i];
if(redlineBuffer[i]<bluelineBuffer[i] && redlineBuffer[i-1]>bluelineBuffer[i-1]) downBuffer[i]=high[i];
}
return(rates_total);
}