//+------------------------------------------------------------------+
//| EMA计算.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 2
#property indicator_color1 clrRed
#property indicator_width1 2
#property indicator_color2 clrYellow
#property indicator_width2 2
extern int SMA_Period = 10;
extern int EMA_Period = 20;
double buf[];
double ema[];
//+------------------------------------------------------------------+
int OnInit() {
SetIndexBuffer(0, buf);
SetIndexStyle(0, DRAW_LINE);
SetIndexBuffer(1, ema);
SetIndexStyle(1, DRAW_LINE);
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, j;
int limit;
if (prev_calculated == 0)
limit = rates_total - 1;
else
limit = rates_total - prev_calculated;
for (i = limit; i >= 0; i--) {
// SMA
if (i + SMA_Period - 1 <= Bars - 1) {
buf[i] = 0;
for (j = 0; j < SMA_Period; j++) buf[i] += Close[i + j];
buf[i] /= SMA_Period;
}
/*
// 一般的EMA
if (i + EMA_Period - 1 <= Bars - 1)
{
if(i + EMA_Period - 1 == Bars - 1)
{
ema[i] = 0;
for (j=0; j<EMA_Period; j++) ema[i] += Close[i+j];
ema[i] /= EMA_Period;
}
else
{
ema[i] = ema[i+1] * (EMA_Period - 1) + Close[i] * 2;
ema[i] /= EMA_Period + 1;
}
}
*/
// MT4的EMA
if (i == Bars - 1) ema[i] = Close[i];
else {
ema[i] = ema[i + 1] * (EMA_Period - 1) + Close[i] * 2;
ema[i] /= EMA_Period + 1;
}
}
return(rates_total);
}
暂无评论