今天写一个相当简单的指标,如上图:
先搞清楚一下思路,需要在图上画什么,如何写。在主图上需要画出四个图标,两条均线(一个小周期一个大周期),两个箭头(一个向上指标,一个向下指),另外一点是当境均线形成金叉时出现向上箭头,当两均线死叉时出现在向下箭头,这是所有的需求了,好简单吧。
我把带有注释的全部代码先贴上来:
#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);
}