MT4 写KD指标的方法,举例
时间: 2024-01-26 10:05:01 浏览: 31
以下是在MT4中编写计算随机指标(KD指标)的示例代码:
```
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Red
#property indicator_color2 Lime
extern int KPeriod = 14;
extern int DPeriod = 3;
extern int Slowing = 3;
double KBuffer[];
double DBuffer[];
void calculateKDJ(int rates_total, int prev_calculated, double price[])
{
int limit;
double high, low, RSV, K, D;
if(prev_calculated == 0)
{
limit = KPeriod + DPeriod;
for(int i = limit; i >= 0; i--)
{
high = iHighest(NULL, 0, MODE_HIGH, KPeriod, i);
low = iLowest(NULL, 0, MODE_LOW, KPeriod, i);
RSV = (price[i] - low) / (high - low) * 100;
KBuffer[i] = RSV;
}
limit = KPeriod + DPeriod + Slowing - 2;
}
else
{
limit = prev_calculated - 1;
}
for(int i = limit; i < rates_total; i++)
{
high = iHighest(NULL, 0, MODE_HIGH, KPeriod, i);
low = iLowest(NULL, 0, MODE_LOW, KPeriod, i);
RSV = (price[i] - low) / (high - low) * 100;
K = (2 * KBuffer[i-1] + RSV) / (2 + 1);
D = (2 * DBuffer[i-1] + K) / (2 + 1);
KBuffer[i] = K;
DBuffer[i] = D;
}
}
int init()
{
SetIndexStyle(0, DRAW_LINE);
SetIndexBuffer(0, KBuffer);
SetIndexLabel(0, "K");
SetIndexStyle(1, DRAW_LINE);
SetIndexBuffer(1, DBuffer);
SetIndexLabel(1, "D");
return(0);
}
int start()
{
int limit;
double price[];
ArrayResize(price, Bars);
limit = Bars - 1 - IndicatorCounted();
if(limit > KPeriod + DPeriod + Slowing)
{
limit = KPeriod + DPeriod + Slowing;
}
if(limit > 0)
{
for(int i = 0; i < limit; i++)
{
price[i] = iClose(NULL, 0, i);
}
calculateKDJ(limit, 0, price);
}
return(0);
}
```
在这个示例中,我们定义了三个参数:KPeriod、DPeriod和Slowing,它们分别对应KD指标中的周期、D线的周期和减速因子。我们还定义了两个指标缓冲区:KBuffer和DBuffer,它们用于存储计算出的K线和D线的值。
在init()函数中,我们设置了指标的样式、缓冲区和标签。在start()函数中,我们获取当前价格并调用calculateKDJ()函数来计算K线和D线的值。calculateKDJ()函数使用iHighest()和iLowest()函数来获取指定周期内的最高价和最低价,并计算出RSV值。然后,它使用KBuffer和DBuffer中的上一个值来计算当前的K线和D线的值,并将它们存储在缓冲区中。
请注意,这只是一个简单的示例,如果您要使用它来进行交易,请务必进行测试和优化。