Function Simple Moving Average
Apr 11, 2016

The Function Simple Moving Average tool provides a custom-coded implementation of the standard moving average calculation to offer traders a transparent and flexible way to smooth price data for trend analysis.
Usage
The Usage section describes how the script can be used to interpret market direction. Traders typically utilize the Simple Moving Average (SMA) to filter out market noise and identify the primary trend. When the price persists above the SMA, it indicates a bullish environment, whereas a price below the SMA indicates a bearish environment.
The indicator can be used in the following ways:
- Trend Identification: Use the slope and position of the SMA to determine the current market bias.
- Support and Resistance: The SMA often acts as a dynamic level where price may find support during an uptrend or resistance during a downtrend.
- Crossover Signals: The script includes built-in alert conditions for when the price crosses over or under the SMA, which can signal potential entries or exits.
Details
The script features a custom function, f_sma, which calculates the average price over a specific lookback period using a loop-based logic. This implementation calculates the sum of the source price over the defined length and divides it by that length to produce the average.
While most platforms provide a built-in SMA function, this script serves as a foundational template for developers to understand the mathematical construction of moving averages. It plots both the built-in calculation and the custom function output to ensure parity and accuracy. This logic was originally developed by @RicardoSantos and refactored for modern script standards.
Settings
- Source: Specifies the price data used for the calculation (e.g., Close, Open, High, Low, HL2).
- Length: Sets the lookback window for the moving average. A larger length produces a smoother line with more lag, while a shorter length reacts faster to price changes.
FAQ
What is the benefit of using a custom SMA function versus the built-in one? The custom function allows for greater transparency in how the indicator is calculated and provides a framework that can be modified for more complex, non-standard smoothing calculations.
How do the alerts work in this script? Alerts are triggered whenever the closing price crosses the SMA line. You can configure these alerts to notify you once per bar close to avoid repetitive signals during volatile price action.
How do I access the Function Simple Moving Average? You can get access on the LuxAlgo Library for charting platforms like TradingView, MetaTrader (MT4/MT5), and NinjaTrader for free.
Free indicator
Get free access to this indicator on the platforms below.
Unlock the entire LuxAlgo Library
Every indicator, every strategy, full charts, and complete access to Quant — our AI agent.