272 lines
15 KiB
MQL5
//+------------------------------------------------------------------+
| |||
//| TutorialSMA.mq5 |
| |||
//| Learning example: Simple Moving Average |
| |||
//| Written by MetaTrader Assistant |
| |||
//+------------------------------------------------------------------+
| |||
//#property copyright "MetaTrader Assistant - learning example"
| |||
//#property link "https://www.mql5.com"
| |||
#property version "1.00"
| |||
#property description "Simple Moving Average (SMA) - step by step commented indicator."
| |||
#property description "How to use: drag it from Navigator > Indicators onto a chart."
| |||
#property description "Press Ctrl+D to open the Data Window and watch the buffer values."
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| WHAT THIS FILE TEACHES |
| |||
//| |
| |||
//| Every MQL5 indicator is built from the same three blocks: |
| |||
//| 1. PROPERTIES - metadata that tells the terminal HOW to show it |
| |||
//| 2. BUFFERS - the arrays that hold your calculated values |
| |||
//| 3. OnCalculate - the function that fills those arrays |
| |||
//| |
| |||
//| The terminal calls OnCalculate() again and again: first for the |
| |||
//| whole history, then only for the newest bars as prices arrive. |
| |||
//| Your job is to fill the buffer for every bar, exactly once. |
| |||
//+------------------------------------------------------------------+
| |||
| |||
//==================================================================
| |||
// PART 1 - PROPERTIES
| |||
// -----------------------------------------------------------------
| |||
// These are not code that runs. They are instructions to the
| |||
// terminal, read when the indicator is loaded.
| |||
//==================================================================
| |||
| |||
//--- Where the indicator is drawn.
| |||
// indicator_chart_window = on top of the price candles.
| |||
// indicator_separate_window = in its own panel below the chart
| |||
// (use that one for oscillators like RSI or MACD).
| |||
#property indicator_chart_window
| |||
| |||
//--- How many calculation buffers we declare, and how many of them
| |||
// are actually drawn on the screen. Here: 1 buffer, 1 plot.
| |||
#property indicator_buffers 1
| |||
#property indicator_plots 1
| |||
| |||
//--- Appearance of plot number 1 (plots are numbered 1,2,3... in
| |||
// #property lines, but 0,1,2... inside the code - watch out!).
| |||
#property indicator_label1 "SMA" // name shown in Data Window / tooltip
| |||
#property indicator_type1 DRAW_LINE // DRAW_LINE, DRAW_HISTOGRAM, DRAW_ARROW...
| |||
#property indicator_color1 clrDodgerBlue // line colour
| |||
#property indicator_style1 STYLE_SOLID // STYLE_SOLID, STYLE_DASH, STYLE_DOT...
| |||
#property indicator_width1 2 // line thickness in pixels
| |||
| |||
//==================================================================
| |||
// PART 2 - INPUTS
| |||
// -----------------------------------------------------------------
| |||
// "input" variables appear in the indicator's Properties dialog
| |||
// (Inputs tab) and can be optimised in the Strategy Tester.
| |||
// The text after // becomes the label shown to the user.
| |||
//==================================================================
| |||
input int InpMAPeriod = 14; // Averaging period (bars)
| |||
input ENUM_APPLIED_PRICE InpPrice = PRICE_CLOSE; // Price to average
| |||
| |||
//==================================================================
| |||
// PART 3 - THE BUFFER
| |||
// -----------------------------------------------------------------
| |||
// A plain dynamic double array. It becomes an indicator buffer
| |||
// only after SetIndexBuffer() is called in OnInit(). Once bound,
| |||
// the terminal and the buffer share the same memory: whatever you
| |||
// write into this array is drawn on the chart.
| |||
// Do NOT resize it manually afterwards - the terminal owns its size.
| |||
//==================================================================
| |||
double SmaBuffer[];
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| OnInit - runs ONCE when the indicator is attached (or inputs |
| |||
//| are changed). Use it to validate inputs and set everything up. |
| |||
//+------------------------------------------------------------------+
| |||
int OnInit()
| |||
{
| |||
//--- Always validate user inputs. A period below 1 is meaningless
| |||
//--- and would make our averaging loop divide by zero.
| |||
if(InpMAPeriod < 1)
| |||
{
| |||
Print("TutorialSMA: InpMAPeriod must be at least 1 (received ", InpMAPeriod, ")");
| |||
//--- INIT_PARAMETERS_INCORRECT makes the terminal refuse to load
| |||
//--- the indicator instead of drawing garbage.
| |||
return(INIT_PARAMETERS_INCORRECT);
| |||
}
| |||
| |||
//--- Bind SmaBuffer to plot index 0 as calculation data.
| |||
//--- INDICATOR_DATA = a value that is drawn/read by other programs.
| |||
//--- INDICATOR_CALCULATIONS = a hidden helper buffer.
| |||
//--- SetIndexBuffer returns false if the array could not be bound.
| |||
if(!SetIndexBuffer(0, SmaBuffer, INDICATOR_DATA))
| |||
{
| |||
Print("TutorialSMA: failed to bind buffer 0");
| |||
return(INIT_FAILED);
| |||
}
| |||
| |||
//--- Do not start drawing before the first bar that has a full
| |||
//--- window of prices. With period 14 the first valid bar is index 13
| |||
//--- (0..13 = 14 bars), hence "period - 1".
| |||
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpMAPeriod - 1);
| |||
| |||
//--- Tell the terminal which value means "no data here".
| |||
//--- EMPTY_VALUE makes the line break instead of jumping to zero (It means your line stops cleanly on the chart instead of crashing down to the bottom of the screen).
| |||
//---For plot 0, whenever the buffer holds the value EMPTY_VALUE, do not draw anything on the chart and do not show a number in the Data Window.
| |||
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
| |||
| |||
//--- Name shown in the chart's top-left corner and in the Data Window.
| |||
IndicatorSetString(INDICATOR_SHORTNAME, "Tutorial SMA(" + string(InpMAPeriod) + ")");
| |||
| |||
//--- How many decimals to display in the Data Window.
| |||
//--- _Digits is the symbol's price precision, so we reuse it.
| |||
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
| |||
| |||
return(INIT_SUCCEEDED);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| OnDeinit - runs ONCE when the indicator is removed or the chart |
| |||
//| is closed. Nothing to clean up here (no handles, files or chart |
| |||
//| objects were created), but the function is kept so you can see |
| |||
//| where cleanup belongs in your own indicators. |
| |||
//+------------------------------------------------------------------+
| |||
void OnDeinit(const int reason)
| |||
{
| |||
//--- "reason" tells you why we are unloading
| |||
//--- (REASON_REMOVE, REASON_CHARTCHANGE, REASON_PARAMETERS...).
| |||
//--- If you had created an indicator handle with iMA() you would call
| |||
//--- IndicatorRelease(handle) here. We do not use handles in this file.
| |||
Print("TutorialSMA: removed, reason code = ", reason);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| AppliedPrice - returns the price we want to average for one bar. |
| |||
//| |
| |||
//| "index" is a bar index where 0 = OLDEST bar in history and |
| |||
//| rates_total-1 = the newest (still forming) bar. |
| |||
//| This is the same indexing as our indicator buffer, which is why |
| |||
//| we can write SmaBuffer[i] using the same i. |
| |||
//+------------------------------------------------------------------+
| |||
double AppliedPrice(const int index,
| |||
const double &open[],
| |||
const double &high[],
| |||
const double &low[],
| |||
const double &close[])
| |||
{
| |||
switch(InpPrice)
| |||
{
| |||
case PRICE_CLOSE: return(close[index]); // close only
| |||
case PRICE_OPEN: return(open[index]); // open only
| |||
case PRICE_HIGH: return(high[index]); // high only
| |||
case PRICE_LOW: return(low[index]); // low only
| |||
case PRICE_MEDIAN: return((high[index] + low[index]) / 2.0); // (H+L)/2
| |||
case PRICE_TYPICAL: return((high[index] + low[index] + close[index]) / 3.0); // (H+L+C)/3
| |||
case PRICE_WEIGHTED: return((high[index] + low[index] + 2.0 * close[index]) / 4.0); // (H+L+2C)/4
| |||
}
| |||
//--- Fallback: if a future enum value is added and not handled above,
| |||
//--- we still return a valid price instead of an undefined value.
| |||
return(close[index]);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| OnCalculate - the heart of the indicator. It is called by the |
| |||
//| terminal every time new prices arrive. |
| |||
//| |
| |||
//| rates_total = number of bars currently available |
| |||
//| prev_calculated = how many bars were already processed last call |
| |||
//| (0 means "recalculate everything") |
| |||
//| open/high/low/close/tick_volume/volume/spread = price history |
| |||
//+------------------------------------------------------------------+
| |||
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[])
| |||
{
| |||
//--- Guard 1: we need at least one full window of bars.
| |||
//--- Returning 0 tells the terminal "nothing was calculated yet",
| |||
//--- so it will call us again when more history is available.
| |||
if(rates_total < InpMAPeriod)
| |||
return(0);
| |||
| |||
//--- Guard 2: if history was reloaded or the bar count shrank
| |||
//--- (prev_calculated > rates_total, e.g. after switching timeframe),
| |||
//--- we cannot trust the previous values and must start over.
| |||
const bool recalculate_all = (prev_calculated <= 0 || prev_calculated > rates_total);
| |||
| |||
int start; //--- index of the first bar we are going to calculate
| |||
| |||
if(recalculate_all)
| |||
{
| |||
//--- Full recalculation: clear every cell first so that bars we
| |||
//--- never touch (the first period-1 bars) show no value at all (Every single one of those existing values is immediately overwritten and replaced with EMPTY_VALUE).
| |||
ArrayInitialize(SmaBuffer, EMPTY_VALUE);
| |||
start = InpMAPeriod - 1; //--- first bar with a complete window
| |||
}
| |||
else
| |||
{
| |||
//--- Incremental update: only the newest bar can have changed,
| |||
//--- but we recalculate from prev_calculated-1 to be safe, because
| |||
//--- that last bar was still forming during the previous call.
| |||
start = prev_calculated - 1;
| |||
if(start < InpMAPeriod - 1)
| |||
start = InpMAPeriod - 1;
| |||
}
| |||
| |||
//--- Main loop: one iteration per bar that needs a value.
| |||
//--- !IsStopped() lets the terminal abort a long calculation when the
| |||
//--- indicator is being removed, so we do not block the terminal.
| |||
for(int i = start; i < rates_total && !IsStopped(); i++)
| |||
{
| |||
//--- Sum the last InpMAPeriod prices ending at bar i.
| |||
//--- k = 0 is bar i, k = 1 is the bar before it, and so on,
| |||
//--- so the window always ends on the bar we are drawing.
| |||
double sum = 0.0;
| |||
for(int k = 0; k < InpMAPeriod; k++)
| |||
sum += AppliedPrice(i - k, open, high, low, close);
| |||
| |||
//--- The simple moving average: arithmetic mean of the window.
| |||
SmaBuffer[i] = sum / InpMAPeriod;
| |||
}
| |||
| |||
//--- Returning rates_total tells the terminal that everything up to
| |||
//--- this bar is done, so next time prev_calculated = rates_total.
| |||
//---(prev_calculated==rates_total*It jumps all at once, it does not increase gradually bar-by-bar.*)
| |||
return(rates_total);
| |||
}
| |||
//+------------------------------------------------------------------+
| |||
//| HOW TO EXTEND THIS FILE (your next steps as a learner) |
| |||
//| |
| |||
//| 1) Add a second line: |
| |||
//| - declare double SlowBuffer[]; |
| |||
//| - change #property indicator_buffers 2 / indicator_plots 2 |
| |||
//| - add #property indicator_label2 "SMA slow" |
| |||
//| #property indicator_type2 DRAW_LINE |
| |||
//| #property indicator_color2 clrOrange |
| |||
//| - call SetIndexBuffer(1, SlowBuffer, INDICATOR_DATA) |
| |||
//| and repeat the same calculation with a second input period. |
| |||
//| |
| |||
//| 2) Change the smoothing method (EMA / SMMA / LWMA): |
| |||
//| - EMA is a running value: |
| |||
//| alpha = 2.0 / (period + 1.0); |
| |||
//| ema[i] = price[i] * alpha + ema[i-1] * (1.0 - alpha); |
| |||
//| The first ema value is normally seeded with an SMA. |
| |||
//| |
| |||
//| 3) Draw in a subwindow instead: |
| |||
//| - replace indicator_chart_window with indicator_separate_window |
| |||
//| - buffer values outside the visible range are clipped, so |
| |||
//| also set IndicatorSetDouble(INDICATOR_MINIMUM / MAXIMUM, ..).|
| |||
//| |
| |||
//| 4) Reuse a built-in average instead of writing the maths yourself: |
| |||
//| - in OnInit: m_handle = iMA(_Symbol, _Period, period, 0, |
| |||
//| MODE_SMA, InpPrice); |
| |||
//| - check it: if(m_handle == INVALID_HANDLE) return(INIT_FAILED);|
| |||
//| - in OnCalculate: if(BarsCalculated(m_handle) < rates_total) |
| |||
//| return(0); |
| |||
//| CopyBuffer(m_handle, 0, 0, rates_total, buf);|
| |||
//| - in OnDeinit: IndicatorRelease(m_handle); |
| |||
//| Creating a handle once in OnInit (never inside OnCalculate) is |
| |||
//| what keeps such indicators fast. |
| |||
//| |
| |||
//| 5) IMPORTANT: the newest bar is still forming. Its SMA value will |
| |||
//| keep changing until the bar closes, so a signal based on the |
| |||
//| current bar can repaint. For non-repainting logic, read the |
| |||
//| value of a closed bar instead. |
| |||
//+------------------------------------------------------------------+
|