Overview
In MQL5, indicator outputs are stored in buffers. You access these buffers programmatically using a handle (e.g., from iMA(), iRSI()) and the CopyBuffer() function. This lets your scripts and Expert Advisors consume analytical data directly for decisions.
Ad
What You Will Be Able to Do
- Create an indicator handle (e.g., Moving Average) and manage its lifecycle.
- Read recent values from indicator buffers using
CopyBuffer(). - Interpret buffer indexing (current bar vs. previous bars).
- Print values to the Experts log to verify correctness.
Code Example
//+------------------------------------------------------------------+
//| ReadIndicatorValues.mq5 |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
input int Period = 14;
input ENUM_MA_METHOD Method = MODE_SMA;
input ENUM_APPLIED_PRICE Price = PRICE_CLOSE;
input int Count = 5; // how many recent values to read
void OnStart()
{
// 1) Create a handle for the built-in Moving Average
int ma = iMA(_Symbol, _Period, Period, 0, Method, Price);
if(ma == INVALID_HANDLE)
{
Print("Error: failed to create MA handle");
return;
}
// 2) Prepare a buffer and read values
double buf[];
ArraySetAsSeries(buf, true); // index 0 = most recent bar
int copied = CopyBuffer(ma, 0, 0, Count, buf);
if(copied <= 0)
{
Print("Error: CopyBuffer failed. copied=", copied);
IndicatorRelease(ma);
return;
}
// 3) Print latest values
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
for(int i = 0; i < copied; i++)
Print(StringFormat("MA[%d] = %s", i, DoubleToString(buf[i], digits)));
// i=0 is the current (forming) bar, i=1 previous closed bar, etc.
// 4) Clean up
IndicatorRelease(ma);
}
Ad
Execution Steps
- Open MetaEditor → File → New → Script and name it
ReadIndicatorValues. - Paste the code and press F7 to compile.
- Attach the script to any chart in MetaTrader 5.
- Open the Experts tab to see printed MA values for bars
[0..Count-1]. - (Optional) Change Period/Method or switch to another handle, e.g.,
iRSI(). For multi-buffer indicators such as MACD, select buffer indexes (e.g., main=0, signal=1, hist=2).
Key Point
Indicator outputs live in buffers. Create a handle, call CopyBuffer() for the desired buffer index and bar range, then release the handle with IndicatorRelease(). Use ArraySetAsSeries(true) when you want buf[0] to represent the most recent bar.
Ad
Next Section
→ Next: What Is an Expert Advisor


