应用指令以自定义绘图

到目前为止,我们一直使用PlotIndexSetInteger函数调用来自定义图形绘图。MQL5 允许你使用#property预处理器指令实现相同的功能。这两种方法的主要区别在于,指令在编译时处理,使用它们定义的特性在加载时从可执行文件中读取,甚至早于OnInit处理程序的执行(如果存在的话)换言之,指令提供了一些默认值,如果你不需要更改它们,则可以直接使用。

另一方面,PlotIndexSetInteger函数调用允许你在程序执行期间动态更改特性。通过函数动态更改特性,你可以创建更灵活的指标使用场景。指令和相关 PlotIndexSetInteger函数调用如下表所示。

指令

函数

说明

indicator_colorN

PlotIndexSetInteger(N-1, PLOT_LINE_COLOR, color)

设置绘图的颜色

indicator_styleN

PlotIndexSetInteger(N-1, PLOT_LINE_STYLE, type)

设置风格(来自 ENUM_LINE_STYLE 枚举)

indicator_typeN

PlotIndexSetInteger(N-1, PLOT_DRAW_TYPE, type)

设置类型(来自 ENUM_DRAW_TYPE 枚举)

indicator_widthN

PlotIndexSetInteger(N-1, PLOT_LINE_WIDTH, width)

设置线条粗细(像素,范围 1-5)

请注意,指令中的绘图编号从 1 开始,而函数中的编号从 0 开始。例如,指令 #property indicator_type1 DRAW_ZIGZAG等效于调用 PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_ZIGZAG)

此外,值得注意的是,通过函数可以设置的特性比通过指令多得多: ENUM_PLOT_PROPERTY_INTEGER 枚举提供了十个元素。

通过指令定义的特性,即使在指标第一次添加到图表时,也会显示在指标设置对话框中(用户可查看和编辑)。具体而言,这些特性包括线条的粗细、颜色和风格(Colors选项卡),以及水平层级的数量和位置(Levels 选项卡)。而通过函数设置的相同特性(且在指令中没有默认值的情况下),仅会在指标第二次及后续添加到图表时才会出现在对话框中。

让我们调整IndHighLowClose.mq5指标,改用指令。新版本文件名为IndPropHighLowClose.mq5。使用指令简化了 OnInit处理程序;OnCalculate 保持不变。

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 2
   
// High-Low histogram rendering settings (change index 0 to 1 in the directive)
#property indicator_type1   DRAW_HISTOGRAM2
#property indicator_style1  STYLE_SOLID // by default, can be omitted
#property indicator_color1  clrBlue
#property indicator_width1  5
   
// close line drawing settings (change index 1 to 2 in the directive)
#property indicator_type2   DRAW_LINE
#property indicator_style2  STYLE_SOLID // by default, can be omitted
#property indicator_color2  clrRed
#property indicator_width2  2
   
double highs[];
double lows[];
double closes[];
   
int OnInit()
{
   // arrays for buffers for 3 price types
   SetIndexBuffer(0highs);
   SetIndexBuffer(1lows);
   SetIndexBuffer(2closes);
   
   return INIT_SUCCEEDED;
}

新指标的外观与旧版本完全一致。