使用当前 K 线的前两根来判断金叉死叉,在当前 K 线刚形成时,输出信号。
//+------------------------------------------------------------------+
//| 双均线.mq4 |
//| Copyright 2023, 100w123 |
//| https://100w123.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, 100w123"
#property link "https://100w123.com"
#property version "1.00"
#property strict
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 clrWhite
#property indicator_color2 clrYellow
#property indicator_color3 clrRed
#property indicator_color4 clrAqua
#property indicator_width3 3
#property indicator_width4 3
input int fastMA_Period = 5;
input int slowMA_Period = 10;
double fastMA[];
double slowMA[];
double GC[];
double DC[];
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit() {
SetIndexBuffer(0, fastMA);
SetIndexBuffer(1, slowMA);
SetIndexBuffer(2, GC);
SetIndexBuffer(3, DC);
//---
SetIndexStyle(0, DRAW_LINE);
SetIndexStyle(1, DRAW_LINE);
SetIndexStyle(2, DRAW_ARROW, STYLE_SOLID);
SetIndexStyle(3, DRAW_ARROW, STYLE_SOLID);
//---
SetIndexLabel(0, "Fast MA");
SetIndexLabel(1, "Slow MA");
//---
SetIndexDrawBegin(0, fastMA_Period);
SetIndexDrawBegin(1, slowMA_Period);
//---
SetIndexArrow(2, 233);
SetIndexArrow(3, 234);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
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 limit;
// 第一次回调计算所有 K 线
if (prev_calculated == 0)
limit = rates_total - 1;
else
limit = rates_total - prev_calculated; // 后续回调,limit = 0 计算最后一根不断更新的 K 线,当新 K 线形成时, limit = 1,需要计算上一根的最终收盘后的价格和最新形成的一根
S_LOG_INFO("limit: %d", limit);
// 因为要绘制金叉死叉符号,需要用前两根 K 线,第一次回调会溢出,必须从第三根开始
if (prev_calculated == 0) {
limit = limit - 2;
}
// 最后最新一根索引是 0,从前往后算
for (int i = limit; i >= 0; i--) {
fastMA[i] = iMA(NULL, 0, fastMA_Period, 0, MODE_SMA, PRICE_CLOSE, i);
slowMA[i] = iMA(NULL, 0, slowMA_Period, 0, MODE_SMA, PRICE_CLOSE, i);
GC[i] = EMPTY_VALUE;
DC[i] = EMPTY_VALUE;
if(fastMA[i + 2] <= slowMA[i + 2] && fastMA[i + 1] > slowMA[i + 1]) {
GC[i] = Low[i] - 30 * Point;
}
if(fastMA[i + 2] >= slowMA[i + 2] && fastMA[i + 1] < slowMA[i + 1]) {
DC[i] = High[i] + 30 * Point;
}
}
return(rates_total);
}
//+------------------------------------------------------------------+