请用MQL写一个移动平均指标
时间: 2024-03-20 20:42:14 浏览: 26
以下是一个简单的 MQL4 代码,用于计算移动平均指标:
```
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Lime
extern int ma_period = 10;
double ma_buffer[];
int init() {
SetIndexBuffer(0, ma_buffer, INDICATOR_DATA);
return(0);
}
int start() {
int limit = Bars - ma_period;
if(limit < 1) {
return(0);
}
for(int i = limit; i >= 0; i--) {
double sum = 0;
for(int j = 0; j < ma_period; j++) {
sum += Close[i+j];
}
ma_buffer[i] = sum / ma_period;
}
return(0);
}
```
在上面的代码中,我们定义了一个 `ma_period` 变量,用于指定移动平均指标的计算周期。在 `init()` 函数中,我们使用 `SetIndexBuffer()` 函数将移动平均数据存储在 `ma_buffer` 数组中,并将其注册为指标缓冲区。在 `start()` 函数中,我们使用两个嵌套的循环来计算移动平均值。外部循环从最新的价格条目开始,向前遍历历史价格数据。内部循环计算指定的移动平均周期内的价格总和,然后将其除以周期数以获得移动平均值。最后,我们将移动平均值存储在 `ma_buffer` 数组中,以便在图表上绘制出指标线。