LightningChart JS TraderVariable Moving Average Indicator

ArticleImplement the Variable Moving Average technical indicator with LightningChart JS Trader for Fintech software development.

Written by a human | Updated on April 24th, 2025

About Variable Moving Average Indicator

The Variable Moving Average (VMA) Indicator is a dynamic technical analysis tool designed to enhance traditional moving averages by adjusting itself based on market volatility. Unlike standard moving averages, which use fixed parameters, the VMA adapts its smoothing factor according to recent price momentum, allowing it to be more responsive in volatile markets.

The Variable Moving Average (VMA) is an Exponential Moving Average that automatically adjusts its smoothing based on the volatility of the price, utilizing the Chande Momentum Oscillator (CMO) to measure volatility. This indicator is very similar to the Variable Index Dynamic Average (VIDYA); however, while VMA uses the CMO, VIDYA uses standard deviation for its volatility measurement. This article will explore how the variable moving average indicator functions, delve into its formula and demonstrate its creation using LightningChart JS Trader Interactive Examples for better insights into its practical use.

How Do Variable Moving Averages Work in Technical Analysis?

The variable moving average indicator distinguishes itself through its dynamic approach to price averaging. While traditional moving averages calculate an average price over a set period, the VMA modifies this based on real-time price fluctuations. By leveraging a momentum-based approach, the variable moving average formula adapts to changing market conditions, offering traders a more sensitive indicator, especially in high-volatility environments.

The Variable Moving Average (VMA) adjusts its smoothing based on the volatility of the price. It uses the Chande Momentum Oscillator to measure volatility, making it more dynamic in fast-moving markets. The VMA is often confused with the Variable Index Dynamic Average (VIDYA), which uses a standard deviation for volatility measurement.

VMA Formula Explanation

The variable moving average formula relies on three key elements:

  1. Exponential Moving Average (EMA): Provides a smoothed version of price data, which forms the base of the VMA calculation.
  2. Chande Momentum Oscillator (CMO): Measures the price momentum, reflecting both speed and direction of price changes.
  3. Smoothing Factor Adjustment (α): The smoothing factor is adjusted based on the CMO value, making the VMA more responsive to recent momentum.

Step 1: EMA Calculation

The Exponential Moving Average (EMA) for a period ? is calculated using the formula:

Variable-Moving-Average-EMA-Calculation

Where:

  • EMAt-1 is the previous EMA value.
  • Pricet is the current price.
  • ? is the smoothing constant, calculated as:
Variable-Moving-Average-Smoothing-Constant

where ? is the period length (e.g., 9 days).

Step 2: CMO Calculation (Chande Momentum Oscillator)

The CMO helps the VMA adjust based on recent gains and losses:

  • Gains: The total price increases over the defined period.
  • Losses: The total price decreases over the same period.

The CMO value is calculated as:

Variable-Moving-Average-CMO-Calculation

A high CMO indicates strong positive momentum, while a low or negative CMO indicates weaker momentum or a downtrend.

Step 3: Calculate the Smoothing Factor α

Using the CMO, we derive the smoothing factor α dynamically:

Variable-Moving-Average-Smoothing-Constant-Derive

where Min is the lower limit (e.g., 0.05) and Max is the upper limit (e.g., 0.15):

Variable-Moving-Average-Smoothing-Constant-Min-Max

This ensures that ? dynamically adjusts between 0.05 and 0.15, depending on the CMO value, making the VMA more responsive during periods of high momentum.

Step 4: VMA Calculation

The Variable Moving Average (VMA) is calculated using the adjusted smoothing factor and the EMA:

Variable-Moving-Average-VMA-Calculation

Where:

  • VMAt: The current value of the VMA.
  • EMAt: The current Exponential Moving Average.
  • Pricet: The current day’s price.
  • α (Alpha): Weight factor derived from the CMO, which adjusts based on price momentum.

This formula adjusts the EMA using a factor that reflects market momentum, making the VMA a more sensitive indicator of price changes.

Calculation Example (A 5-day VMA): Given the following prices: 100, 102, 101, 105, 110

Step 1: Calculate EMA for Day 5

For a 9-period EMA:

Variable-Moving-Average-EMA-Calculation-5-Day

Calculating the EMA for Each Day: For simplicity, we assume the EMA for Day 1 is the same as the closing price, of 100.

  • Day 2: Price = 102
    • EMA= 100 + 0.2 x (102 – 100) = 100 + 0.4 = 100.4
  • Day 3: Price = 101
    • EMA= 100.4 + 0.2 x (101 – 100.4) = 100.4 + 0.12 = 100.52
  • Day 4: Price = 105
    • EMA= 100.52 + 0.2 x (105 – 100.52) = 100.52 + 0.896 = 101.416
  • Day 5: Price = 110
    • EMA= 101.416 + 0.2 x (110 – 101.416) = 101.416 + 1.7168 = 103.1328

So, Calculating the EMA for Day 5 yields 103.1328.

Step 2: Calculate CMO for 5-Day Period:

  • Gains:

Day 2: +2 (102 – 100),

Day 4: +4 (105 – 101),

Day 5: +5 (110 – 105)

Sum of Gains: 2 + 4 + 5 = 11

  • Losses:

Day 3: -1 (101 – 102)

Sum of Losses: 1

CMO:

Variable-Moving-Average-CMO-Example

Step 3: Adjust the Smoothing Factor (α) Based on CMO

The smoothing factor α in the Variable Moving Average (VMA) is typically derived from the Chande Momentum Oscillator (CMO) value, with α dynamically adjusted based on the CMO to make the VMA more or less responsive to price movements. Here’s a common approach to calculate α:

  1. Define the Range for α:

The range for α depends on how responsive you want the VMA to be. A typical range might be between 0.05 and 0.15, where:

  • A lower α (closer to 0.05) makes the VMA less sensitive, and useful in low-volatility conditions.
  • A higher α (closer to 0.15) makes the VMA more sensitive, and useful in high-volatility conditions.
  1. Set Up a Scaling Formula for α:

Since the CMO oscillates between -100 and +100, a linear scaling formula can map the CMO to a corresponding value of α within its defined range. Here’s how:

Variable-Moving-Average-Scaling-Formula

Where:

  • Min is the lower limit of α (0.05).
  • Max is the upper limit of α (0.15).
  • CMO is the current value of the Chande Momentum Oscillator.
  1. Example Calculation

Suppose:

  • CMO is 83.33 (from the previous example),
  • Min is 0.05,
  • Max is 0.15.

Substitute these values into the formula:

Variable-Moving-Average-CMO-Calculation-Example

Calculate step-by-step:

  1. Calculate the adjusted CMO range: (83.33 + 100) / 200 = 0.91665
  2. Scale to the α range: 0.91665 × (0.15 − 0.05) = 0.091665
  3. Add to the Min value: α = 0.05 + 0.091665 = 0.1417

So, α would be approximately 0.14 for a CMO of 83.33. This dynamically calculated α (0.14) is high, reflecting strong momentum (indicated by a high CMO), so the VMA will be more responsive to recent price changes.

Step 4: Calculate VMA for Day 5

Using the EMA value from Step 1 and the adjusted α:

Variable-Moving-Average-VMA-Calculation-5-Day

Given:

  • EMA5 = 103.1328
  • Price6 = 112
  • α = 0.1417
Variable-Moving-Average-VMA-Calculation-Result

The Variable Moving Average (VMA) for Day 6 is approximately 104.389, calculated using the dynamically adjusted smoothing factor based on the CMO.

Interpretation of Results

  • EMA Calculation: The EMA for Day 5 was calculated using a 9-period EMA, resulting in 103.1328.
  • CMO Calculation: The CMO for the 5-day period was 83.33, indicating strong momentum.
  • Adjustment of ?: The CMO-adjusted ? was 0.1417, reflecting the market’s momentum.
  • VMA Calculation: Using the adjusted ? and the price data, the VMA for Day 6 was calculated as 104.389.

The Exponential Moving Average (EMA) for Day 5, calculated as 103.1328, serves as the basis for the Variable Moving Average (VMA). Using the Chande Momentum Oscillator (CMO), which indicated strong momentum with a value of 83.33, the smoothing factor α was adjusted to 0.1417. This adjustment made the VMA for Day 6 more responsive to price changes, resulting in a value of 104.389. The higher α allows the VMA to closely track the actual price, effectively capturing short-term trends and reflecting the market’s upward movement.

The Role of LightningChart JS Trader in Financial Analysis

Trader-JS-page

Financial analysis involves examining historical data to forecast future trends, make informed decisions, and assess risk. In this domain, applications like LightningChart JS Trader serve a critical role by providing real-time, high-performance data visualization tools that help traders and analysts better interpret complex datasets. It enables traders to track market trends using built-in indicators.

The platform’s ability to handle large datasets and real-time updates makes it essential for fast decision-making in dynamic markets. Additionally, its customization options allow users to create tailored charts and apply statistical indicators, enhancing both the precision of analysis and risk management. This tool helps streamline financial analysis and supports more informed, data-driven trading strategies.

Implementation with LightningChart JS Trader

Advanced charting platforms like LightningChart JS offer traders a range of technical indicators, including the Variable Moving Average (VMA) indicator. LightningChart JS allows traders to create interactive, high-performance charts, ensuring real-time data visualization. This platform is particularly useful for traders who rely on technical indicators such as the Variable Moving Average (VMA) indicator to make quick, informed decisions.

Step 1: Get LightningChart JS Trader

To begin, you’ll need access to LightningChart JS Trader. This library provides the tools necessary to create advanced technical indicators, including the Variable Moving Average (VMA) indicator. Visit the LightningChart JS Trader page to download the required components and review the documentation.

Step 2: Review the Interactive Example

LightningChart JS Trader includes interactive examples that demonstrate how to create custom technical indicators. Start by reviewing the documentation, focusing on how to integrate the Variable Moving Average (VMA) indicator into your chart setup. The interactive examples will guide you through the process of setting up the Variable Moving Average (VMA) indicator, from importing the necessary modules to modify the chart settings.

Step 3: Code Explanation

In this step, we will break down the code that creates the chart with the Variable Moving Average (VMA) indicator, as shown in the image, using LightningChart JS Trader. The code demonstrates how to initialize a trading chart, apply the Variable Moving Average (VMA) indicator, and customize its appearance.

Variable-Moving-Average-VMA-Indicator-Chart

Here’s a detailed breakdown of each section:

A. Importing the Required Libraries:

   const lcjsTrader = require('@arction/lcjs-trader')
   const lcjs = require('@arction/lcjs')
   const { Themes } = lcjs
  • lcjsTrader: This library provides access to the LightningChart JS Trader functionalities, allowing you to create advanced financial charts.
  • lcjs: The main LightningChart JS library is used for general charting functionality.
  • Themes: A property within lcjs that provides access to pre-built themes. In this case, we are using the darkGold theme to style the chart.

B. Initializing the Trading Chart:

lcjsTrader.trader(TRADER_LICENSE).then(async (trader) => {
    // Create a trading chart.
    const tradingChart = trader.tradingChart({ loadFromStorage: false, colorTheme: Themes.darkGold })
  • trader(TRADER_LICENSE): Initializes the LightningChart JS Trader with the provided license key (TRADER_LICENSE). This is required to access the charting functionalities for financial data.

Note you can request a LightningChart JS Trader trial license, which is free.

  • tradingChart(): This function creates a trading chart with certain options. In this example:
  • loadFromStorage: false: This disables the loading of previously stored chart data from local storage, ensuring a fresh chart setup.
  • colorTheme: Themes.darkGold: This applies the darkGold theme to the chart which influences the background color, grid lines, and other visual elements.

C. Adding and Customizing the Indicator

    // Add a Variable Moving Average indicator
    const vma = tradingChart.indicators().addVariableMovingAverage()
    vma.setPeriodCount(9)
    vma.setLineColor('#FFFFDC')
    vma.setLineWidth(2)
  • addVariableMovingAverage(): VMA is an Exponential Moving Average that automatically adjusts its smoothing based on the volatility of the price. Uses Chande Momentum Oscillator to measure the volatility.
  • setPeriodCount(9): Sets the period count of the VMA to 9, meaning the VMA will calculate its moving average based on the last 9 data points. This relatively short period allows the VMA to be more responsive to recent price changes, giving traders a closer view of short-term trends.
  • setLineColor('#46FFFA): Changes the VMA line’s color to a pale yellow. This distinct color improves visibility on the chart, allowing traders to easily differentiate the VMA line from other indicators or price movement lines.
  • vma.setLineWidth(2): Sets the thickness of the VMA line to 2 pixels. This thicker line enhances the visual prominence of the VMA on the chart, making it easier for traders to spot the VMA and analyze trends effectively.

D. Loading Data from a CSV File

    // Reading data from a file.
    await fetch(`${document.head.baseURI}examples/assets/0000/Alphabet Inc (GOOGL).csv`).then((res) => res.text()).then((text) => {
        tradingChart.readCsvString(text, 'Alphabet Inc (GOOGL)')
    })
  • fetch(): This function retrieves a CSV file containing historical data for Alphabet Inc. (GOOGL). The CSV file includes pricing information for the company’s stock, which is plotted on the chart.
  • readCsvString(): This function reads the CSV data and interprets it as pricing data for Alphabet Inc. The second argument (‘Alphabet Inc (GOOGL)’) sets the label for the chart, as seen at the top of the chart image.

E. Setting the Currency for the Chart

    tradingChart.setCurrency('USD')
   })
  • setCurrency('USD'): This sets the currency of the chart to USD, ensuring that the pricing data is interpreted and displayed in US dollars.

Advantages and Limitations of the Time-Series Moving Average

Benefits of Using Variable Moving Average

The variable moving average indicator offers several advantages for traders, especially those navigating volatile markets:

  • Enhanced Responsiveness: Unlike traditional moving averages that often lag, the VMA adapts swiftly to price changes, reflecting real-time volatility. This is especially useful for short-term traders looking for precise entry and exit points in volatile markets.
  • Improved Trend Detection: By adjusting for momentum, the VMA enables more accurate trend analysis. Traders can identify bullish or bearish trends more effectively, reducing potential false signals in choppy markets.
  • Increased Flexibility: The VMA’s adaptable nature means it is suitable for various asset classes, including stocks, forex, and cryptocurrencies, where volatility is high. 

Advantages and Limitations of the Indicator

  • Advantages:
    • Higher Sensitivity to Market Movements: The VMA’s dynamic response to volatility allows traders to capture trends more accurately than static moving averages.
    • Reduces Lag in Fast-Moving Markets: By adjusting the smoothing factor, the VMA minimizes the lag, allowing traders to respond more promptly to significant price shifts.
    • Flexible Application Across Assets: The VMA is compatible with multiple markets and assets, making it a versatile tool for diversified trading.
  • Limitations:
    • Risk of Over-Sensitivity: In highly volatile markets, the VMA may produce excessive signals, leading to potential false alarms.
    • Increased Complexity: The variable moving average formula is more complex than traditional moving averages, which can make it harder to interpret for new traders.
    • Confusion with VIDYA Indicator: The VMA is often mistaken for the Variable Index Dynamic Average (VIDYA), a related indicator. Unlike the VMA, VIDYA uses standard deviation to measure volatility, making its response slightly different.

Conclusion

The Variable Moving Average (VMA) is an adaptable and dynamic tool that helps traders respond more effectively to market trends, especially in volatile environments. By incorporating the Chande Momentum Oscillator (CMO) to adjust its smoothing factor, the VMA can offer timely insights and act as a reliable indicator of trend direction and strength. This adaptability sets it apart from traditional moving averages, making it highly valuable for traders seeking accuracy in entry and exit points.

Using LightningChart JS Trader for calculating and visualizing the Variable Moving Average enhances the trading experience by offering interactive, real-time examples that are customizable. This platform allows traders to adjust parameters dynamically, experiment with different market scenarios, and witness how the VMA responds to fluctuations. It provides a practical edge in understanding the VMA’s behaviour and makes complex indicators more accessible through a hands-on approach.

Key Takeaways:

  • The Variable Moving Average Indicator is a valuable technical analysis tool that adjusts its sensitivity based on market volatility.
  • CMO plays a critical role in calculating the VMA by influencing the smoothing factor (α), making the indicator more reactive to price changes.
Omid Ahmad

Ahmad Omid

Data Science Developer

LinkedIn icon
divider-light

Continue learning with LightningChart

Lighting

This article covers basics of Lighting in Data Visualization.

High-Performance WPF Charts : The Truth

What about manufacturers’ claims about Fastest rendering charts? There are a lot of false marketing terms used in the industry, so we are going to tell the truth, based on facts that anyone can reproduce and verify.