Intermediate Trading Tutorial | PowerLanguage .NET C# indicators

A green candle is often described as an up bar, but that description depends on which reference price is being used. A candle that opens below the preceding close and subsequently rises may still finish below that preceding close. Conversely, a red candle can close above the previous close after a sufficiently large upward opening gap. This distinction becomes particularly important when an analysis mixes candle-body filters with close-to-close momentum. In this tutorial we develop a free MultiCharts .NET indicator that measures how frequently the two directional definitions disagree across completed bars. A second output reports the number of valid observations, allowing users to distinguish a well-supported percentage from a small-sample extreme.

Two different reference prices

For each candle, define the body movement as its closing price minus its opening price. Define the close-to-close movement as its closing price minus the immediately preceding candle's close. Assign a positive or negative direction to each movement according to its sign. If both are nonzero and their signs differ, record a disagreement. If both are nonzero and their signs match, record agreement. A zero in either movement makes the pair ineligible under this implementation. Do not silently count a flat movement as bullish or bearish.

Over the last N completed candles, the disagreement percentage is 100 multiplied by the number of disagreeing pairs divided by the number of eligible pairs. The denominator is not necessarily N. If there are no eligible pairs, the percentage is undefined and the plot is suppressed. A separate count plot shows zero in that situation. The percentage always lies between zero and 100 whenever it is defined.

Worked example: five completed bars

Consider an initial closing price of 100, followed by five hypothetical candles. The open, close, and preceding close values below form a consistent sequential example.

Bar Prior close Open Close Body Close change Pair
1 100 100 102 +2 +2 Same
2 102 98 101 +3 −1 Different
3 101 102 99 −3 −2 Same
4 99 104 101 −3 +2 Different
5 101 103 103 0 +2 Excluded
Build a Closed-Bar Body and Close Direction Disagreement Indicator
Figure 1. Two disagreements out of four eligible pairs produce 50%. The flat-bodied fifth candle is excluded.

Bar two rises from 98 to 101 but remains below the preceding close of 102. Bar four falls from 104 to 101 but remains above the preceding close of 99. Both demonstrate genuine disagreement, despite having opposite body directions. The fourth eligible comparison brings the count to two agreements and two disagreements. Dividing two by four gives 50%, not 40%. Dividing by all five candidates would incorrectly treat the excluded observation as an agreement.

Complete PowerLanguage .NET indicator

using System;
using System.Drawing;

namespace PowerLanguage.Indicator
{
    public class PSBodyCloseDisagreement : IndicatorObject
    {
        private IPlotObject disagreement;
        private IPlotObject validCount;

        [Input]
        public int Period { get; set; }

        public PSBodyCloseDisagreement(object ctx) : base(ctx)
        {
            Period = 5;
        }

        protected override void Create()
        {
            disagreement = AddPlot(new PlotAttributes(
                "DisagreementPct", EPlotShapes.Line, Color.RoyalBlue));
            validCount = AddPlot(new PlotAttributes(
                "ValidPairs", EPlotShapes.Line, Color.Gray));
        }

        protected override void CalcBar()
        {
            // Set MaxBarsBack >= Period + 1 in study settings.
            if (Period < 1 || Period > 500)
            {
                disagreement.Reset();
                validCount.Reset();
                return;
            }

            int eligible = 0, different = 0;

            // Start at 1: all inputs precede the calculation bar.
            for (int j = 1; j <= Period; j++)
            {
                double body = Bars.Close[j] - Bars.Open[j];
                double change = Bars.Close[j] - Bars.Close[j + 1];

                // Do not treat a flat direction as agreement.
                if (body == 0.0 || change == 0.0)
                    continue;

                eligible++;
                if ((body > 0.0) != (change > 0.0))
                    different++;
            }

            validCount.Set(eligible);
            if (eligible == 0)
                disagreement.Reset();
            else
                disagreement.Set(100.0 * different / eligible);
        }
    }
}

Study lifecycle and indexing

The indicator inherits IndicatorObject. Its constructor defines the default five-bar input, and Create allocates two plot objects. CalcBar performs the calculation in the context of the bar being processed. In MultiCharts .NET positive historical offsets access earlier bars. The loop deliberately begins at offset one, never at offset zero, so the latest input candle is already completed even when the study is updated during a forming bar. The oldest read is Bars.Close[Period + 1]. Configure the study's maximum bars back manually to at least Period + 1 before running it; for the default Period of five, set six or more. This requirement is important because indexed historical access beyond the available lookback can stop the study. If the input changes, update that setting accordingly, or allocate 501 bars for the full supported range.

The displayed reading belongs to the calculation bar following the final input candle. It is not backdated to the preceding candle. If the study runs only on bar close, the value is published at the close of that calculation bar; if intrabar updating is enabled, it can be available earlier in the same bar. The formula itself is unchanged because it excludes the forming bar. For a consistent integration, explicitly choose and test the desired calculation mode rather than assuming that a plotted historical value was available at the opening instant.

Installation and testing

  1. Open PowerLanguage .NET Editor, create a C# indicator named PSBodyCloseDisagreement, and replace the editable template with the complete class.
  2. Compile the study and insert it into a chart. Set the lookback input to five and the maximum bars back to at least six.
  3. Use a separate subchart. The blue line is the percentage; the gray line is the valid-pair count. For long periods, the count can exceed 100, so use the status line or configure separate scales if necessary.
  4. Manually identify a sequence of six completed candles, calculate the five pairs, and inspect the subsequent calculation bar.
  5. Verify both ordinary historical calculations and the behavior of the indicator during live or playback updates.

The implementation follows the native study and plot interfaces described in the official MultiCharts .NET help. No compilation or live execution was performed for this article, so check the installed version and editor settings before deployment.

Parameter decisions and edge cases

A short window reacts rapidly but can produce coarse increments. With four eligible pairs, each disagreement represents 25 percentage points. A single eligible disagreement would produce 100%, even though the observation count is weak. The second plot is therefore not merely decorative: it provides context for judging the estimate. A larger window typically gives more observations, but can mix different market conditions. An optional minimum valid-pair filter may be appropriate if the statistic is later used in screening.

If every opening price equals the previous close exactly, the two movements are identical and all nonflat pairs agree. Conversely, repeated opening discontinuities may raise the disagreement percentage. Session definitions, corporate actions, futures rollover and data corrections can influence the result. The exact zero comparison assumes valid price values from the chart; a tick-based tolerance would change the definition and must be tested as an explicit variant. The calculation intentionally ignores the magnitude of the moves.

Validation checklist and interpretation

Test all agreement, all disagreement, one eligible pair, and no eligible pairs. Confirm that invalid input lengths suppress the output, and that sufficient history is loaded. Check the five-bar worked example and compare a live forming candle with the prior completed sequence. A data reload may change past inputs if the provider revises the underlying bars. Neither a high nor a low disagreement rate predicts future returns by itself. Treat it as a diagnostic for the difference between body-based and momentum-based rules, then independently evaluate any proposed trading filter using transaction costs and out-of-sample data.

If you would like separate upward and downward disagreement counts, session-aware calculations, alerts or integration into a custom study, contact us for Custom MultiCharts .NET indicator Development Services.

Risk disclosure: This tutorial is educational, not investment advice. Examples are hypothetical and do not establish profitability. Trading involves risk of loss.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.