Intermediate Trading Tutorial | cTrader Automate C# custom indicators

Two price series can end at the same price while following very different paths. One may contain consecutive upward and downward runs, while another alternates direction almost every bar. Ordinary net price change cannot capture that distinction. This tutorial develops a free cTrader indicator that counts whether successive close-to-close movements retain their direction or reverse it. The resulting run balance oscillator ranges from −100 to +100 and describes directional persistence without relying on the magnitude of individual moves. It is a descriptive statistic, not a prediction of the next bar.

Define transitions rather than count bullish candles

For each completed bar, compare its closing price with the previous closing price. Assign +1 to an increase, −1 to a decrease, and 0 to an unchanged close. These signs are based on consecutive closes, not on whether a candle closes above its own open. A bar with a bullish body can still have a negative close-to-close change when it opens substantially below the preceding close.

For each pair of adjacent signs, count a continuation when both are nonzero and equal. Count a reversal when both are nonzero and opposite. Ignore pairs that contain a zero. Over the last N adjacent transitions, the oscillator is 100 × (continuations − reversals) / (continuations + reversals). If no valid transitions exist, the result is unavailable, not zero. A genuine zero result means that the two counts are equal. The default window contains five transitions, requiring six price changes and seven completed closing prices.

Worked example: six changes and five transitions

Suppose seven consecutive completed closes are 100, 101, 103, 102, 100, 101 and 104. The six signs are UP, UP, DOWN, DOWN, UP, UP. The first pair is a continuation, the second a reversal, the third a continuation, the fourth a reversal and the fifth a continuation.

Build a Closed-Bar Run Balance Indicator in cTrader C#
Figure 1. Three continuations and two reversals produce a run balance of +20.

Pair Directions Classification
1 Up → Up Continuation
2 Up → Down Reversal
3 Down → Down Continuation
4 Down → Up Reversal
5 Up → Up Continuation

The calculation is 100 × (3 − 2) / 5 = 20. If the next change is negative, the oldest continuation leaves the window and a reversal enters. The counts become two continuations and three reversals, resulting in −20. Notice that the oscillator can change sign without a large price movement, since each transition receives the same weight regardless of price distance.

All six signs being negative would produce +100, just as six positive signs would. An alternating sequence of six nonzero signs would produce −100. Consequently, the oscillator describes persistence or alternation, not bullishness or bearishness. A persistent downtrend and a persistent uptrend can have identical positive readings.

Complete cTrader Automate indicator code

using System;
using cAlgo.API;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, TimeZone = TimeZones.UTC,
        AccessRights = AccessRights.None)]
    public class PSRunBalance : Indicator
    {
        [Parameter("Transitions", DefaultValue = 5, MinValue = 1, MaxValue = 500)]
        public int Period { get; set; }

        [Output("Run Balance", LineColor = "RoyalBlue", Thickness = 2)]
        public IndicatorDataSeries Result { get; set; }

        private int Direction(int index)
        {
            return Math.Sign(Bars.ClosePrices[index] -
                Bars.ClosePrices[index - 1]);
        }

        public override void Calculate(int index)
        {
            // Publish only on a new bar using earlier closed prices.
            // P transitions need P+1 changes and P+2 closes.
            Result[index] = double.NaN;
            if (index < Period + 2)
                return;

            int same = 0, flip = 0;
            for (int j = index - Period; j <= index - 1; j++)
            {
                int a = Direction(j - 1);
                int b = Direction(j);
                // Ignore pairs containing a flat close.
                if (a == 0 || b == 0)
                    continue;
                if (a == b)
                    same++;
                else
                    flip++;
            }

            int count = same + flip;
            if (count > 0)
                Result[index] = 100.0 * (same - flip) / count;
        }
    }
}

Indexing and completed-bar design

The cTrader indicator derives from Indicator and implements Calculate(int index). Unlike a cBot that receives a dedicated bar event, an indicator can be recalculated on the latest bar as prices update. The implementation deliberately reads only indices earlier than the output index. When index refers to the currently forming bar, all input closes are already completed. The newest transition compares the direction at index − 1 with the direction at index − 2. The oldest transition needs the close at index − Period − 2. The initial guard prevents any negative array access.

With Period equal to five, the first valid calculation is possible at index seven, assuming at least one valid transition. This is an intentional publication convention: the output is plotted on the bar following the final input observation. Do not shift historical values backward merely to make the indicator appear more timely. A strategy reading the result at the opening of a new bar should use the value at that new bar's index, rather than blindly applying another one-bar delay. Historical and live comparisons should use this same alignment.

Flat closes are ignored only for adjacent pairs containing zero. The algorithm does not bridge across a flat close and compare the preceding and following nonzero movements. That would create a different definition of adjacency. A fixed number of candidate transitions is examined, but the denominator contains only valid pairs. Therefore two windows of equal length may have different effective sample sizes.

Install the indicator

  1. Open cTrader's Algo or Automate workspace and create a C# custom indicator named PSRunBalance.
  2. Replace the editable source with the complete code. Build the project using your installed version of cTrader.
  3. Add the indicator to a chart and retain the default five-transition window for the first test.
  4. Locate a sequence of seven completed closing prices and manually determine the six signs and five adjacent pairs.
  5. Compare the calculated score with the indicator value on the following bar. During that bar's formation, its score should not change merely because its current price changes.

This source uses the native cAlgo.API indicator interface. It has not been compiled or executed inside cTrader for this article. Verify the build and actual chart behavior before integration or live use.

Parameter tradeoffs and edge cases

A five-transition window reacts quickly, but changes in the counts can generate large discrete steps. With five valid pairs, one replacement from continuation to reversal changes the score by 40 points. Longer windows reduce the effect of a single replacement but retain older patterns. The same threshold need not have equivalent meaning across bar types or periods. Tick bars, time bars, and range bars all produce different sequences of closing prices.

Flat closes become especially important in quiet or illiquid instruments. One valid continuation and four ignored transitions can produce +100, even though the evidence is sparse. If the intended application requires greater sample support, a separate valid-pair output or minimum valid-count condition would be a useful extension. Do not treat an unavailable window as a neutral signal. In the provided code, double.NaN represents the absence of a valid calculation.

Validation checklist and limitations

Test a strictly increasing sequence, a strictly decreasing sequence, alternating movements, unchanged closes and a mixture containing flats. Confirm that the score stays within its theoretical bounds. Test the first available index, Period = 1, and the output after reloading a chart. Check that the forming bar does not enter the calculation. Ordinary historical stability depends on unchanged underlying prices and bar construction; data corrections may change past values.

Run balance ignores price magnitude, volume and transaction costs. A sequence of tiny increases followed by one large decrease can look persistent even when the total return is negative. The statistic does not estimate the probability of the next move or establish a profitable trading rule. If using it alongside trend, range or volatility filters, test the resulting hypothesis independently on out-of-sample data.

If you would like separate directional counts, a minimum valid-pair filter, alerts, or integration into a cBot, contact us for Custom cTrader indicator Development Services.

Risk disclosure: This tutorial is educational and does not constitute investment advice. The example uses hypothetical prices, not historical performance. 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.