[英]Calculate EMA for MACD with 2 lines indicator in C#
我正在尝试编写一个指标脚本,该脚本将 plot MACD 与练习交易工具中的 2 行。
目前,我正在遵循使用 EMA 公式计算它的公式。
我能够 plot 图表。 但不知何故,我的指标结果与 meta trader 4 或交易视图中的结果并不完全相同。 这些应用程序的指标结果完全相同。
当我尝试从公式转换为实际代码时,我想我错过了一些东西。 请帮我修一下。 谢谢你。
这是计算 EMA 的部分。
/// ==================================================================
/// ======================== calculations ============================
/// ==================================================================
public void Calculate()
{
for (int i = 0; i < Bars.Length; i++){
if (i >= SlowEMA) {
MACD[i] = CalculateEMA(FastEMA, i) - CalculateEMA(SlowEMA, i);
Signal[i] = CalculateEMA_MACD(MACD, SignalEMA, i);
Histogram[i] = MACD[i] - Signal[i];
}
}
}
private double CalculateEMA(int Period, int index)
{
var currentValue = 0d;
var currentEMA = 0d;
var yesterdayEMA = 0d;
var smooth = 2d;
var multiplier = smooth / (1 + Period);
for (int i = 0; i < Period; i++){
currentValue = GetPrice(index + i - Period);
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
yesterdayEMA = currentEMA;
};
return yesterdayEMA;
}
private double CalculateEMA_MACD(double[] MACD, int Period, int index)
{
var currentValue = 0d;
var currentEMA = 0d;
var yesterdayEMA = 0d;
var smooth = 2d;
var multiplier = smooth / (1 + Period);
for (int i = 0; i < Period; i++){
currentValue = MACD[index + i - Period];
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
yesterdayEMA = currentEMA;
};
return yesterdayEMA;
}
private double GetPrice(int index)
{
Bar bar = Bars[index];
switch (Source)
{
case Sources.Close:
return bar.Close;
case Sources.Open:
return bar.Open;
case Sources.High:
return bar.High;
case Sources.Low:
return bar.Low;
case Sources.MedianPrice:
return (bar.High + bar.Low) / 2;
case Sources.TypicalPrice:
return (bar.High + bar.Low + bar.Close) / 3;
case Sources.WeightedClose:
return (bar.High + bar.Low + bar.Close + bar.Close) / 4;
}
throw new NotSupportedException("Unsupported price source type: " + Source);
}
看起来您的 EMA 计算逻辑是错误的。 根据您的代码,“yesterdayEMA”始终为 0,因此 EMA 方程的右侧部分也是 0。
private double CalculateEMA(int Period, int index){
...
var yesterdayEMA = 0d;
...
...
currentEMA = (currentValue * multiplier) + (yesterdayEMA * (1 - multiplier));
currentEMA = (currentValue * multiplier) + 0
...
}
您需要在方法之外存储“yesterdayEMA”并将其作为递归计算的参数传递。
我认为这就是为什么您没有像其他交易视图那样获得正确结果的原因。
0 在第一个周期成立,但昨天EMA = current EMA;
由于其相等性,它在下一个循环中开始取不同于 0 的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.