IMPORTANT DISCLAIMER: All content on this site is for educational & entertainment purposes only. Nothing herein constitutes investment, trading, or financial advice. Hypothetical or simulated performance results have certain limitations.

← All Market Notes

Unlock Market Insights: Power-Up Your OBV with Custom MA Calculations

In the realm of financial trading, indicators play a crucial role in deciphering market trends and making informed decisions. One such powerful tool is the "On-Balance Volume with Averages" (OBV) indicator, which combines volume flow with price movements to offer insights into potential market direction. This article delves into the intricacies of designing this indicator, with a special focus on the rationale behind calculating moving averages locally rather than referencing core indicators. To skip all this scroll to the bottom to get the C# code for Quantower.

Understanding the OBV Indicator

The OBV indicator is a momentum-based tool that utilizes volume changes to predict stock price movements. The innovator Joseph Granville had the core premise that volume precedes price, making OBV a leading indicator in identifying bullish or bearish trends. The indicator increases with rising prices and decreases when prices fall, assuming that volume is the driving force behind price movements.

Design Philosophy

The "On_balance_Volume_with_averages" class encapsulates the functionality of the OBV indicator. It includes input parameters for setting the periods of fast and slow-moving averages, allowing users to customize the sensitivity of the indicator to market changes. The class also defines methods for initializing the indicator (OnInit), updating its value with new market data (OnUpdate), and calculating different types of moving averages (Simple, Exponential, Modified, and Linear Weighted).

Incorporating a parameter for selecting the type of moving average within the "On-Balance Volume with Averages" (OBV) indicator significantly enhances its versatility and adaptability to different market conditions and trading strategies. The MAType input parameter, offering choices among Simple (SMA), Exponential (EMA), Modified (SMMA), and Linear Weighted (LWMA) moving averages, caters to a broad spectrum of trading preferences and analytical requirements.

The Impact of Multiple Average Types

  1. Adaptability: The inclusion of multiple moving average types allows the indicator to be adaptable to various trading styles and market conditions. For instance, traders looking for more responsiveness to recent price changes might prefer EMA or LWMA, while those interested in a smoother trend analysis might opt for SMA or SMMA.
  2. Customization: This parameter empowers users to customize the indicator according to their specific needs or the characteristics of the asset they are trading. It acknowledges that no single moving average type is universally optimal, offering flexibility instead.
  3. Comparative Analysis: Having access to multiple moving average types within a single indicator framework enables traders to perform comparative analysis without switching between different indicators. This can provide insights into how different averaging methods affect the interpretation of volume and price trends.
  4. Strategic Experimentation: Traders can experiment with various moving average types to fine-tune their strategies. For instance, one might use a faster moving average like EMA for short-term trades and a smoother average like SMA for long-term trend analysis.
  5. Complexity and Learning Opportunity: While this feature introduces a layer of complexity, it also presents a valuable learning opportunity. Users can gain a deeper understanding of how different moving averages behave and influence the indicator's output, enhancing their analytical skills.
  6. Performance Considerations: Each moving average type comes with its own computational demands. More complex calculations like EMA or LWMA might have different performance implications compared to the simpler SMA, which could be a consideration in high-frequency trading environments.

Local Calculation of Moving Averages

One notable design decision in this implementation is the local calculation of moving averages, as opposed to referencing pre-built core indicators. This approach offers several advantages:

  1. Customization: Local calculations provide greater flexibility in customizing the moving average calculations to fit specific needs. It allows for the inclusion of various types of moving averages (SMA, EMA, SMMA, LWMA) within a single indicator, enhancing its adaptability to different trading strategies.
  2. Performance: By computing moving averages directly within the indicator, it potentially reduces overhead associated with calling external core indicator functions. This can lead to improved performance, especially in high-frequency trading environments where every millisecond counts.
  3. Learning and Debugging: Implementing the calculations within the indicator itself offers an educational opportunity to understand the mechanics behind these mathematical models. It also simplifies debugging, as developers can directly trace and modify the calculations within the indicator's codebase.
  4. Integration: Local calculations ensure that the indicator is self-contained, making it easier to share or integrate into different trading platforms without worrying about dependencies on external libraries or core indicators.

Challenges and Considerations

While local calculations offer several benefits, they also come with challenges. Developers must ensure the accuracy and efficiency of the mathematical models used in the calculations. It's crucial to rigorously test the indicator under various market conditions to validate its reliability. Additionally, maintaining and updating the indicator might require a deeper understanding of the mathematical concepts behind moving averages.

While the local calculation of moving averages within the "On-Balance Volume with Averages" (OBV) indicator offers customization, performance benefits, and a deeper understanding of the underlying mathematics, there are also some disadvantages to this approach. Conversely, leveraging core indicators from a platform's built-in library can bring its own set of advantages. Let's explore both sides of this design consideration.

Disadvantages of Local Calculations

  1. Increased Complexity: Implementing moving average calculations within the indicator increases the overall complexity of the code. This can make the indicator harder to maintain and understand, especially for those who are not the original authors.
  2. Error-Prone: Crafting calculations from scratch opens up room for errors or inaccuracies in the mathematical models, which could lead to misleading indicator readings. Ensuring the correctness of these calculations requires rigorous testing and validation.
  3. Consistency Issues: Different traders or developers might implement the same type of moving average in slightly different ways, leading to inconsistencies in how the indicator behaves across various platforms or versions.
  4. Reinventing the Wheel: Implementing moving averages locally might be seen as "reinventing the wheel" when platforms typically offer well-tested, optimized versions of these calculations as part of their core indicators library.
  5. Lack of Optimization: Trading platforms often optimize their core indicators for performance, taking advantage of platform-specific optimizations that individual developers might not be aware of or able to implement in their local calculations.

Advantages of Using Core Indicator Calls

  1. Simplicity: Calling a platform's core indicators significantly simplifies the code, making the custom indicator easier to read, understand, and maintain. This abstraction allows developers to focus more on the indicator's logic rather than the intricacies of the calculations.
  2. Reliability: Core indicators are typically well-tested and validated across various market conditions, ensuring their reliability and accuracy. Using these pre-built indicators can instill confidence in the results they produce.
  3. Performance: Trading platforms may optimize their core indicators at a low level, potentially offering better performance than locally implemented calculations. These optimizations might include efficient memory management, parallel processing, or hardware acceleration.
  4. Consistency: Utilizing core indicators ensures consistency in how specific calculations are performed, allowing traders to compare results reliably across different strategies, scripts, or platforms that use the same core indicators.
  5. Community Support: Issues, updates, or improvements to core indicators are often handled by the platform's development team or community, ensuring that the indicators stay current with the latest financial analysis methodologies and performance enhancements.
  6. Reduced Development Time: Leveraging pre-built indicators can significantly reduce development time, allowing traders and developers to prototype and deploy their custom indicators more quickly.

Conclusion

The choice between implementing moving average calculations locally within an indicator versus leveraging a trading platform's core indicators involves a trade-off between flexibility, complexity, and reliability. While local calculations offer a deep understanding and customization, they come with challenges in maintenance and the potential for errors. On the other hand, core indicator calls provide simplicity, reliability, and consistency, backed by the platform's optimizations and community support. Developers must weigh these factors based on their specific needs, expertise, and the criticality of performance and accuracy in their trading strategies.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using TradingPlatform.BusinessLayer;

namespace On_balance_Volume_with_averages
{
    public class On_balance_Volume_with_averages : Indicator
    {
        [InputParameter("Fast SMA period", 10, 1, 9999, 1, 0)]
        public int FastPeriod = 10;

        [InputParameter("Slow SMA period", 20, 1, 9999, 1, 0)]
        public int SlowPeriod = 20;

        [InputParameter("MA Type", 30, variants: new object[] {
            "Simple", MaMode.SMA,
            "Exponential", MaMode.EMA,
            "Modified", MaMode.SMMA,
            "Linear Weighted", MaMode.LWMA
        })]
        public MaMode MAType = MaMode.SMA;

        private double previousClose = 0;
        private double obv = 0;
        private List<double> obvValues = new List<double>();

        public On_balance_Volume_with_averages()
        {
            Name = "On_balance_Volume_with_averages";
            Description = "My indicator's annotation";

            AddLineSeries("OBV Line", Color.Blue, 1, LineStyle.Solid);
            AddLineSeries("Fast MA", Color.Orange, 1, LineStyle.Solid);
            AddLineSeries("Slow MA", Color.Magenta, 1, LineStyle.Solid);

            SeparateWindow = true;
        }

        protected override void OnInit()
        {
            ShortName = "OBV Averaged";
        }


        protected override void OnUpdate(UpdateArgs args)
        {
            double currentClose = Close();
            double volume = Volume();

            obv += currentClose > previousClose ? volume : currentClose < previousClose ? -volume : 0;
            obvValues.Add(obv);
            SetValue(obv, 0); // Update the OBV line

            if (obvValues.Count >= FastPeriod)
            {
                double fastMAValue = CalculateMA(obvValues, FastPeriod, MAType);
                SetValue(fastMAValue, 1); // Update the Fast MA line
            }

            if (obvValues.Count >= SlowPeriod)
            {
                double slowMAValue = CalculateMA(obvValues, SlowPeriod, MAType);
                SetValue(slowMAValue, 2); // Update the Slow MA line
            }

            previousClose = currentClose;
        }





        private double CalculateMA(List<double> values, int period, MaMode maType)
        {
            // Select the MA calculation based on the maType
            switch (maType)
            {
                case MaMode.SMA:
                    return values.Skip(Math.Max(0, values.Count - period)).Take(period).Average();
                case MaMode.EMA:
                    // Implement EMA calculation
                    break;
                case MaMode.SMMA:
                    return CalculateSMMA(values, period);
                case MaMode.LWMA:
                    return CalculateLWMA(values, period);
                    break;
                default:
                    return 0;
            }
            return 0;
        }

        private double CalculateEMA(List<double> values, int period)
        {
            double k = 2.0 / (period + 1); // Smoothing constant
            double ema = 0;

            // Start with an SMA for the first period's EMA calculation
            if (values.Count >= period)
            {
                ema = values.Take(period).Average();

                // Apply the EMA formula for each value beyond the initial period
                for (int i = period; i < values.Count; i++)
                {
                    ema = (values[i] * k) + (ema * (1 - k));
                }
            }

            return ema;
        }

        private double CalculateSMMA(List<double> values, int period)
        {
            if (values.Count < period) return 0; // Not enough data

            // Initialize SMMA with the first period's SMA
            double smma = values.Take(period).Average();
            double multiplier = 1.0 / period;

            // Start calculating SMMA from the next point after the initial SMA
            for (int i = period; i < values.Count; i++)
            {
                smma = (smma * (period - 1) + values[i]) * multiplier;
            }

            return smma;
        }

        private double CalculateLWMA(List<double> values, int period)
        {
            if (values.Count < period) return 0; // Not enough data

            double sum = 0;
            double weightSum = 0;

            // Start from the point where the full period is available
            for (int i = values.Count - period; i < values.Count; i++)
            {
                int weight = (i - (values.Count - period) + 1); // Weight increases from 1 to 'period'
                sum += values[i] * weight;
                weightSum += weight;
            }

            return sum / weightSum;
        }



        public enum MaMode
        {
            SMA,
            EMA,
            SMMA,
            LWMA
        }
    }
}

References:

  1. Granville, J. E. (1963). Granville’s New Key to Stock Market Profits. Prentice-Hall. This book by Joseph Granville introduces the On-Balance-Volume (OBV) indicator, providing foundational knowledge on its use and significance in market analysis.
  2. Murphy, J. J. (1999). Technical Analysis of the Financial Markets: A Comprehensive Guide to Trading Methods and Applications. New York Institute of Finance. Murphy’s book is a staple in the field of technical analysis, offering insights into various indicators, including the OBV. It’s an excellent resource for understanding technical analysis’s theoretical and practical aspects.
  3. Achelis, S. B. (2000). Technical Analysis from A to Z, 2nd Edition. McGraw-Hill. Achelis provides an encyclopedia of technical indicators, including the OBV. The book is useful for traders and analysts looking to deepen their understanding of technical indicators and their applications.
  4. Colby, R. W. (2003). The Encyclopedia of Technical Market Indicators, Second Edition. McGraw-Hill. This comprehensive guide includes detailed explanations of various technical indicators, including the OBV, and discusses their practical applications in trading.
  5. Trading Platforms and Software Documentation: Many trading platforms and software include built-in technical analysis tools, such as the OBV indicator and moving averages. Referencing the specific platform or software documentation can provide insights into how these tools are implemented and used in real-world trading scenarios.
  6. Featured image by copilot.microsoft.com

No Copyright

  1. The person who associated a work with this deed has dedicated the work to the public domain by waiving all of his or her rights to the work worldwide under copyright law, including all related and neighboring rights, to the extent allowed by law.
  2. You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission. See Other Information below.

Other Information

  1. In no way are the patent or trademark rights of any person affected by CC0, nor are the rights that other persons may have in the work or in how the work is used, such as publicity or privacy rights.
  2. Unless expressly stated otherwise, the person who associated a work with this deed makes no warranties about the work, and disclaims liability for all uses of the work, to the fullest extent permitted by applicable law.
  3. When using or citing the work, you should not imply endorsement by the Valent.com

Disclaimer

The “On_balance_Volume_with_averages” indicator and the concepts discussed herein are provided for informational and educational purposes only. The content is not intended to serve as financial, investment, trading, or any other type of advice. Trading in financial markets involves significant risk, including the potential loss of all invested capital. It is important to conduct your own research and consider seeking advice from independent financial advisors before making any investment decisions.

Please be aware that while the On-Balance-Volume (OBV) indicator and its enhancements with moving averages can provide insights into market dynamics, they do not guarantee profitable trading outcomes. The financial markets are influenced by a multitude of factors, and the performance of any trading strategy or indicator can vary widely.

It is well-documented that a majority of traders and investors may lose money in the markets, due to the inherent risks and the complexity of financial trading. The use of any trading strategy, including the “On_balance_Volume_with_averages” indicator, should be approached with caution and with full awareness of the risks involved.

Users of the “On_balance_Volume_with_averages” indicator or any trading strategy discussed are solely responsible for their investment and trading decisions. The creators, developers, and distributors of the indicator or the content herein cannot be held liable for any financial losses or damages arising from the use of this information.

Always remember that past performance is not indicative of future results. Market conditions can change, and what worked in the past may not work in the future. Exercise prudent risk management, including setting appropriate stop-loss orders to protect your capital against significant losses.

By using the “On_balance_Volume_with_averages” indicator or applying the concepts discussed, you acknowledge and agree to this disclaimer and assume full responsibility for your trading and investment decisions.

Please consult with a qualified financial professional before making any investment or financial decisions. The information presented should not be construed as financial advice or recommendations.

Disclaimer: This material is provided for educational and entertainment purposes only. It does not constitute trading or investment advice.