MarketAlert – Real-Time Market & Crypto News, Analysis & AlertsMarketAlert – Real-Time Market & Crypto News, Analysis & Alerts
Font ResizerAa
  • Crypto News
    • Altcoins
    • Bitcoin
    • Blockchain
    • DeFi
    • Ethereum
    • NFTs
    • Press Releases
    • Latest News
  • Blockchain Technology
    • Blockchain Developments
    • Blockchain Security
    • Layer 2 Solutions
    • Smart Contracts
  • Interviews
    • Crypto Investor Interviews
    • Developer Interviews
    • Founder Interviews
    • Industry Leader Insights
  • Regulations & Policies
    • Country-Specific Regulations
    • Crypto Taxation
    • Global Regulations
    • Government Policies
  • Learn
    • Crypto for Beginners
    • DeFi Guides
    • NFT Guides
    • Staking Guides
    • Trading Strategies
  • Research & Analysis
    • Blockchain Research
    • Coin Research
    • DeFi Research
    • Market Analysis
    • Regulation Reports
Reading: Moving Average in MQL5 from scratch: Plain and simple
Share
Font ResizerAa
MarketAlert – Real-Time Market & Crypto News, Analysis & AlertsMarketAlert – Real-Time Market & Crypto News, Analysis & Alerts
Search
  • Crypto News
    • Altcoins
    • Bitcoin
    • Blockchain
    • DeFi
    • Ethereum
    • NFTs
    • Press Releases
    • Latest News
  • Blockchain Technology
    • Blockchain Developments
    • Blockchain Security
    • Layer 2 Solutions
    • Smart Contracts
  • Interviews
    • Crypto Investor Interviews
    • Developer Interviews
    • Founder Interviews
    • Industry Leader Insights
  • Regulations & Policies
    • Country-Specific Regulations
    • Crypto Taxation
    • Global Regulations
    • Government Policies
  • Learn
    • Crypto for Beginners
    • DeFi Guides
    • NFT Guides
    • Staking Guides
    • Trading Strategies
  • Research & Analysis
    • Blockchain Research
    • Coin Research
    • DeFi Research
    • Market Analysis
    • Regulation Reports
Have an existing account? Sign In
Follow US
© Market Alert News. All Rights Reserved.
  • bitcoinBitcoin(BTC)$68,384.001.00%
  • ethereumEthereum(ETH)$1,984.980.94%
  • tetherTether(USDT)$1.000.01%
  • rippleXRP(XRP)$1.441.52%
  • binancecoinBNB(BNB)$626.02-0.29%
  • usd-coinUSDC(USDC)$1.00-0.01%
  • solanaSolana(SOL)$85.971.50%
  • tronTRON(TRX)$0.2889081.24%
  • dogecoinDogecoin(DOGE)$0.099375-1.33%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.051.39%
Trading Strategies

Moving Average in MQL5 from scratch: Plain and simple

Last updated: June 30, 2025 7:44 pm
Published: 8 months ago
Share

The moving average is the average price of a currency pair over a certain period of time, expressed in a number of bars. It is one of the oldest technical indicators and perhaps the most popular and most frequently used, as a huge number of other indicators are built on its basis.

Moving averages are widely used to solve various applied problems. Mathematically, a simple moving average is the usual arithmetic mean of a given series of numerical values. When creating various indicators or scripts and EAs for the MetaTrader 5 terminal, moving averages are used in calculations in one way or another. Moving averages are a simple and quite efficient tool for determining the direction of trends, smoothing out minor price fluctuations (noise), or creating trading strategies based on moving averages and other indicators, widely presented both in the client terminal and on mql5.com.

Interestingly, moving averages are widely used not only in financial markets, but also in other fields, such as meteorology and economics. Some machine learning models also use the concept of moving averages as one of the features for time series forecasting.

Moving averages are a powerful tool that, when used correctly, can greatly improve trading results and data analysis.

Simple Moving Average (SMA)

A simple moving average is calculated as the arithmetic mean of a given number of numerical values, such as the closing prices of bars. At each calculation point, the values of the moving average have the same weight in relation to the neighboring points of the calculated numerical series. in relation to the SMA indicator, on each bar of the indicator line (N) we see the average value of the bars adjacent to the left (N + N-1 + N-2 + N-3 + Nx) / x, where x is the averaging period (the number of calculated bars).

SMA features:

Fig. 1. Simple moving average SMA at Close with the calculation period of 10

Calculation

The calculation of the SMA indicator based on bar closing prices can be expressed as follows:

In the indicator, the calculation of a simple moving average can be as follows:

where:

That is, when calculating the average for the smoothing period of 5, iterate over the loop from the bar with the i index and sum all Close prices of bars with the i-j index (i-0 + i-1 + i-2 + i-3 + i-4).

After summing up all the closing prices of all the bars in the ‘period’ quantity, divide the result by the period value. As a result, we get the usual arithmetic mean of Close prices for period bars.

The indicator code:

This is the simplest indicator that allows you to see on the chart the average Close price values for the period specified in the settings for each bar of history (InpPeriod). The values are displayed as a line on the price chart.

To calculate the average price for a specified number of bars, we need to sum the required number of Close prices in a loop from the current bar (also in a loop) and divide the resulting sum by the number of bars, within which the arithmetic mean is sought.

Thus, going in a loop from the beginning of history, for each bar of the i loop, we calculate the average value of the closing prices of the bars on the left in the j loop. This is why the main loop does not start from zero, but from the value of the number of bars, for which we calculate the average – so that the required number of bars is on the left at the very beginning of the SMA calculation.

Above we looked at the simplest and mostly non-optimal code, which shows the calculation of a simple moving average. This construction of the indicator loop forces it to recalculate the entire history again, while performing another loop of calculating average prices on each bar. With the calculation presented above, sooner or later (but most likely sooner), we will receive the following message in the log:

Naturally, it needs to be optimized. First of all, we should implement a more resource-saving calculation of the indicator.

The SMAonPriceCloseRAW.mq5 indicator file can be found in the files attached to the article.

Optimization of calculations

A resource-saving calculation of the indicator means the following sequence of calculations:

The indicator calculation starts when the Calculate event is received. The OnCalculate() event handler is called.

As we can see, we need the value of the prev_calculated variable to arrange a resource-saving calculation. At the first launch, or change of historical data, this variable will contain a zero value. We can manage it to arrange a full calculation of the indicator during the first launch and the calculation of only the current bar after the entire indicator has been calculated and the values for the entire history have been written to its buffer.

Since the indicator loop goes through historical data, starting from a certain number and up to the rates_total-1 value, then, knowing how many bars were calculated at the last run of the indicator (the value is stored in the prev_calculated value), we can control the value to start the calculation loop from.

Suppose this is the start variable, which is to contain the index of the bar the indicator loop should be started from. On the first run, the prev_calculated variable will store zero. This means we can start a loop from zero to the number of bars of the instrument the indicator is running on.

But there is a caveat here: to calculate the value of the moving average, we should loop back to the beginning of the history from the current bar of the loop and calculate the average price value. But if we start the main loop from zero, then there is nothing to the left of the zero bar (the beginning of the historical data), and we will not be able to get the values of the missing bars of history. Therefore, the main loop should be started with an offset from the beginning of the history by the number of bars required to calculate the average. this is the indicator calculation period (for example, Period).

Setting the number of bars calculated to the start variable should look like this:

When the indicator is first started, an initialization value is first written to its buffer. Here it is EMPTY_VALUE — empty value of the indicator buffer that does not participate in rendering. After that, the index of the bar the main loop of the indicator begins from is set to the ‘start’ variable. If this is not the first launch of the indicator, then the prev_calculated variable contains the number of bars already calculated in the previous call of the OnCalculate() handler. Therefore, in this case, we set the index of the current bar as the bar the loop begins from. In most cases, this is prev_calculated-1.

Since some value is returned from the OnCalculate() handler (usually rates_total), we can regulate the number of bars that need to be calculated on the next call to the handler. If we return the number of calculated bars stored in rates_tota, then on the next call to OnCalculate, this value will be written to the prev_calculated variable. Accordingly, if we specify the bar number for the start of the loop as prev_calculated-1, then on the current bar this will be the index of the current bar, and when opening a new bar, this will be the index of the previous bar. This way we specify the bar index to start the loop:

Let’s look at the full indicator code:

The SMAonPriceCloseECO.mq5 indicator file can be found in the files attached to the article.

Now, when we run the indicator on a symbol chart, we will no longer receive a message that it is too slow. But there is still one optimization issue left: when calculating the indicator on the current bar, the loop of calculating the average price for the Period bars is still performed. Since a simple moving average is simply the sum of some number of bars divided by that number, we can eliminate this loop on the current bar.

Let’s see how the SMA indicator in its current version is calculated on history. As an example, we will show the very beginning of the calculation of a simple moving average with the calculation period of 5 bars.

When launching, the indicator calculation starts not from the zero bar, but from the bar equal to (the number of bars in the SMA calculation period) – 1:

The main loop starts at the bar having the index of 4. To calculate the SMA value on this bar, a loop is performed on bars with indices 4, 3, 2, 1 and 0. The price values on these bars are added up, and then the resulting sum is divided by the number of SMA calculation periods – here it is 5. To simplify the calculations, the figure shows simple integer values 2, 4, 6, 8 and 10 on the corresponding bars as the bar price values. As a result, on the bar with index 4, the SMA value is 6 = (2+4+6+8+10)/5.

After shifting the index of the main SMA calculation loop, the SMA value for the next bar with the index 5 is calculated again in the loop:

In the next iteration of the main loop, the SMA is calculated for the bar with the index 6 in the inner loop again:

Next, we repeat the same pattern – SMA values are calculated in the internal loops for each subsequent bar at each subsequent shift of the main loop index.

And so on, until the main loop reaches the current bar:

Then, when calculating the SMA on the current bar, with the arrival of each subsequent tick, an internal loop will be executed to calculate the SMA on the current bar.

What is SMA? This is the arithmetic mean of prices for a certain period. We already know that to calculate the SMA value on one bar, we need to divide the sum of the previous Period prices by the calculation Period. When launching the indicator, we can calculate the very first SMA value by adding the previous Period prices in the loop and dividing this sum by the Period. And now, when shifting the sliding window for calculating SMA to the right, it is no longer necessary to add up previous prices in the loop and divide by their Period number since we already have the calculated SMA value on the previous bar.

It is sufficient to subtract from this value the very first price of those involved in calculating the average value and add the current price to the result, preliminarily dividing them by Period. All is set. In other words, the very first SMA bar is calculated by adding the prices in the Period loop and dividing the result of the addition by the Period value. Then we only have the arithmetic operations of addition, subtraction and division:

Calculation of the first SMA value:

Next, when shifting the index of the main loop, we simply do the calculation:

Each time we get a new SMA value from the previously calculated one

Let’s consider the following indicator:

We can launch the indicator on a chart and compare it with the standard SMA, having previously set the same calculation periods for them. This indicator uses one loop having the length of the MA Period calculation period at startup, and then, during the first launch in the main loop, it calculates the SMA values based on the very first calculated SMA value for the entire history of the instrument. On the current bar, it performs a mathematical calculation of the SMA value for each current tick.

Find the SMAonPriceClose.mq5 indicator file below.

P-percent exponential moving average will look like:

where:

Let’s write a simple indicator that shows the calculation of the exponential moving average:

Just like for the simple moving average, here is shown the calculation of the EMA without any checks on the inputs as the calculation period and the organization of the resource-saving indicator calculation. When first launched, the indicator calculates the entire available history, and then it recalculates the entire history again at each tick. This inevitably causes the message that the indicator is too slow.

Find the EMAonPriceCloseRAW.mq5 indicator in the attachments.

Optimization of calculations

Let’s implement a resource-saving indicator calculation. During the first launch, it will calculate the entire history, and then it will recalculate only the current bar on each new tick:

If the entered value of the calculated period is less than 1, then we set the default value for moving averages equal to 10.

The Exponential Moving Average calculation uses the previously calculated EMA value on the previous bar.

During the first launch, such a calculation was not yet performed, so we use the price value Close as the primary data .

This indicator implements resource-saving data calculation: at the first launch, all available history is calculated, and on subsequent OnCalculate() calls, only the current bar is calculated.

Find the EMAonPriceClose.mq5 indicator file below.

Smoothed Moving Average (SMMA)

The smoothed moving average, unlike the simple one, has less sensitivity to price fluctuations, placing more emphasis on the overall direction of the price movement.

SMMA:

Fig. 3. Smoothed moving average. SMMA at Close with the calculation period of 10

Calculation

Let’s write a simple indicator that calculates a smoothed moving average:

The indicator only displays the SMMA calculation, at the first launch and on each new tick, fully calculating all the bars on the entire available history. This is not optimal and incorrect, as the indicator will be too slow. We should optimize the calculation.

Optimization of calculations

We need to control the input value of the SMMA calculation period, a full calculation of the entire history at the first launch, and then perform the calculation only on the current bar on each new tick:

Now the indicator will economically calculate the history and the current bar. Find the SMMAonPriceClose.mq5 indicator file below.

Optimize the indicator calculation so that the entire history is not recalculated on each tick, and add a check for the entered value of the LWMA calculation period:

The principles of source-saving calculation of indicators are described in detail in the section about simple moving average optimization.

Find the indicator file below.

Pros and cons of the four types of moving averages

Over time, different types of moving averages have emerged, such as simple, exponential, weighted, and many other moving averages, some using their own unique calculations, others based on SMA, each serving different purposes and can open up new and interesting perspectives on the data being analyzed.

Here is a brief summary of the pros and cons of the four basic moving averages:

Conclusion

We have reviewed the principles of calculating the main types of moving averages available in the settings of the standard Moving Average indicator in the client terminal. The calculations presented in the article can be used both in indicators with calculation optimization (which is also shown in the article), while the presented codes can be used as an independent calculation of average values of a sequential data set in your programs.

The figure above shows the difference between moving averages with the same calculation period (10), but different types:

Red – SMA, green – EMA, golden – SMMA, blue – LWMA.

It is clear that the smoothed moving average is less susceptible to the influence of small price fluctuations than the others, and displays the general trend of price movement more clearly.

Exponential and linear weighted moving averages are more responsive to market fluctuations because they place the greatest weight on current data in their calculations.

Let’s sum it all up:

A moving average (SMA) is a statistical method used to analyze time series and smooth data, which allows identifying trends and short-term directional movements, dynamic support/resistance levels, channel boundaries, etc. The first applications of the moving average concept date back to the early 20th century, when economists and engineers began using it to analyze data and predict future values. Interestingly, in World War II, anti-aircraft gun crews used SMA calculation methods for target designation.

Moving averages became widely used in financial analysis, especially with the development of stock market trading in the mid-20th century. At this time, investors began to look for methods to smooth out fluctuations in stock prices and identify long-term trends. Since then, moving averages have become a standard tool in technical analysis considered both by both traders and analysts.

Moving averages with the same calculation period but different types will display data differently on the same price chart:

The choice between these types of moving averages depends on the specific strategy and market conditions. It is important to consider your trading objectives, timeframe, and asset volatility when using moving averages in trading. Traders often combine different types of moving averages to maximize the efficiency of their analysis.

Read more on mql5.com

This news is powered by mql5.com mql5.com

Share this:

  • Share on X (Opens in new window) X
  • Share on Facebook (Opens in new window) Facebook

Like this:

Like Loading...

Related

DeFi Technologies Provides Monthly Corporate Update: Valour Reports US$947 Million (C$1.3 Billion) in AUM, and Monthly Net Inflows of US$14.4 Million (C$19.8 Million) in July 2025, Among Other Key Developments – DeFi Technologies (NASDAQ:DEFT), Nuvve Holding (NASDAQ:NVVE)
Bitcoin at $90K — Bullish Turn or Warning Sign?
Crypto Investors Eye Lyno AI for 2025’s Biggest ROI Opportunity
10 Best Crypto Trading Bot 2025 for Smarter Trades
Abaxx Exchange to Extend Trading Access Through TMX Trayport’s Joule Platform – SME & Entrepreneurship Magazine

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Email Copy Link Print
Previous Article Former Standard Chartered Executive Launches New RWA L1 Chain for “Serious Finance Apps”
Next Article HKEX Welcomes Launch Of 30-Year Swaps Trading In Northbound Swap Connect
© Market Alert News. All Rights Reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Prove your humanity


Lost your password?

%d