As an exercise to learn MQL4
, I'm writing a custom indicator which just replicates the Simple Moving Average, but without using the builtin iMA()
function. The code below paints the indicator onto the chart, but every part of the line except the ending is showing extremely low values. For instance, on the AUD/CAD
chart, which is usually, in 0.80-0.90 range, the SMA line is around 0.20-0.30.
The line moves up and down in-sync with the price, and the very last bar seems to have an accurate reading ( as the SMA spikes towards the current price at that point ), but everything else is way low. I've exhausted every possible reason for why this may be happening, and nothing is changing it. Can somebody help me to figure out what is going wrong?
/*
SELF-CODED 5-DAY SMA
Set up buffer with style, indexbegin, and color
for each bar:
calculate closing price of last 4 bars and current price
use to find SMA value at that bar
update last value after every tick
lock each bar's SMA value once the bar has close
*/
#property strict
#property indicator_chart_window
#property indicator_buffers 1
double buffer[];
int OnInit()
{
IndicatorBuffers(1);
SetIndexBuffer(0, buffer);
SetIndexStyle(0, 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 limit = rates_total - prev_calculated;
buffer[0] = iClose(NULL, 0, 0);
for(int b = 1; b<5; b++)
{
buffer[0] = buffer[0] + iClose(NULL, 0, b);
}
buffer[0] = buffer[0]/5;
for(int i = 1; i<limit; i++)
{
buffer[i] = iClose(NULL, 0, i); // Placeholder in first for loop interation
for(int a = 1; a<4; a++) {
{
buffer[i] = buffer[i] + iClose(NULL, 0, i+a);
}
buffer[i] = buffer[i]/5.0;
}
}
return(rates_total);
}
MQL4
– user3666197Print( "SYMBOL:", _Symbol," PERIOD:", PERIOD_CURRENT, " Last 6 Bars Close[i] := [ ", Close[5], ", ", Close[4], ", ", Close[3], ", ", Close[2], ", ", Close[1], ", ", Close[0]," ], SmaToTEST[1] = ", iCustom( _Symbol, PERIOD_CURRENT, "SMA", 0, 1 ), "SmaToTEST[0] = ", iCustom( _Symbol, PERIOD_CURRENT, "SMA", 0, 0 ) );
? – user3666197