PATTERNSMART / cTRADER AUTOMATE / FREE C# SOURCE
cTrader Confirmed Fair Value Gap Indicator: ATR-Filtered Three-Candle Zones in C#
Level: Trading Tips · Platform: cTrader Automate · Tool: overlay indicator · Example: schematic, not historical market data
A gap-looking area is easy to draw retrospectively. The engineering challenge is deciding when the pattern becomes knowable, proving its width is meaningful in the instrument’s own units, and preventing a live bar from leaving phantom zones. This standalone indicator treats those three questions as a single, auditable detection pipeline.
A three-candle imbalance is not an exchange gap
In the popular three-candle fair value gap (FVG) convention, compare the first candle (A) with the third candle (C). A bullish candidate exists when C’s low is strictly above A’s high; a bearish candidate exists when C’s high is strictly below A’s low. Candle B sits between them. The prices traded during B may bridge the apparent separation: this is an analytical three-candle price-inefficiency pattern, not proof that no trade occurred in that area, and not a claim about exchange-level liquidity.
Many scripts evaluate candle C while it is still forming. Its low can fall back into A’s range before the close, making a previously drawn bull zone vanish. For a research indicator, the more defensible rule is to identify C only after it closes, then draw a fixed-duration, explanatory rectangle. This tool deliberately uses no orders, targets, or implied fills.
The decision rule: geometry, pips, then volatility
Define the bullish width as Low(C) − High(A); define the bearish width as Low(A) − High(C). A candidate must be strictly positive and must clear both a minimum absolute width in pips and a minimum width relative to the current ATR. Equivalently, the code requires gapWidth ≥ max(MinGapPips × PipSize, MinAtrRatio × ATR). An optional filter asks the middle candle to close in the direction of the zone. ATR uses the confirmed C bar and the cTrader built-in exponential-smoothed Average True Range.
Contrast two rejected cases. A 3-pip gap against 12-pip ATR fails the 4-pip minimum. A 9-pip gap against 30-pip ATR passes the absolute threshold but measures only 0.30 ATR, failing the 0.40 ratio. These examples show why the filters answer different questions: “large enough for the instrument?” and “unusual enough relative to its recent range?” Neither alone defines a trade.
Why the closed-bar guard is written this way
cTrader calls an indicator’s Calculate(int index) across historical bars and again as the newest live bar updates. Simply testing index == Bars.Count - 2 is fragile because the callback often concerns the forming bar. Instead, this program derives lastClosed = Math.Min(index, Bars.Count - 2). Its private cursor remembers the last finished index already evaluated and processes each eligible closed bar once. On a new bar, the previous forming candle has become closed and may now be assessed as C. On a tick updating the same forming bar, nothing new is drawn.
Each accepted zone gets a stable name derived from C’s opening time and its direction. The code draws a rectangle from candle A to a configurable number of bars after C. It keeps a first-in-first-out list of its own object names and removes older rectangles when the MaximumZones limit is reached. This is a bounded chart-display budget, not a rolling-performance statistic. Reinitialization or historical backfill may rebuild what you see; it does not retroactively validate an earlier live alert.
Complete cTrader Automate C# source
Create an indicator rather than a cBot, name it PSConfirmedFvgAtrZones, and replace the template with this entire program. It uses documented Indicator.Calculate, Indicators.AverageTrueRange, Chart.DrawRectangle, and Chart.RemoveObject. The indicator is a visual study and never submits orders.
// cTrader Automate C# indicator: PS Confirmed FVG / ATR Zones
// Visual research tool. It never submits orders.
using System;
using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = true, TimeZone = TimeZones.UTC,
AccessRights = AccessRights.None)]
public class PSConfirmedFvgAtrZones : Indicator
{
[Parameter("ATR Period", DefaultValue = 14, MinValue = 2)]
public int AtrPeriod { get; set; }
[Parameter("Minimum Gap (pips)", DefaultValue = 4.0,
MinValue = 0.1, Step = 0.1)]
public double MinimumGapPips { get; set; }
[Parameter("Minimum Gap / ATR", DefaultValue = 0.40,
MinValue = 0.0, Step = 0.05)]
public double MinimumAtrRatio { get; set; }
[Parameter("Require Middle Candle Direction", DefaultValue = true)]
public bool RequireMiddleDirection { get; set; }
[Parameter("Extend Zone (bars)", DefaultValue = 8,
MinValue = 1, MaxValue = 100)]
public int ExtendBars { get; set; }
[Parameter("Maximum Drawn Zones", DefaultValue = 60,
MinValue = 1, MaxValue = 500)]
public int MaximumZones { get; set; }
private AverageTrueRange _atr;
private int _lastProcessedClosedBar = -1;
private readonly Queue<string> _objectNames = new Queue<string>();
protected override void Initialize()
{
_atr = Indicators.AverageTrueRange(
AtrPeriod, MovingAverageType.Exponential);
}
public override void Calculate(int index)
{
// Calculate can be called many times for the forming bar.
// Evaluate the last completed bar, never the forming bar.
int lastClosed = Math.Min(index, Bars.Count - 2);
if (lastClosed <= _lastProcessedClosedBar)
return;
int first = Math.Max(_lastProcessedClosedBar + 1,
AtrPeriod + 2);
for (int k = first; k <= lastClosed; k++)
DetectAtClosedBar(k);
_lastProcessedClosedBar = lastClosed;
}
private void DetectAtClosedBar(int k)
{
double atr = _atr.Result[k];
if (double.IsNaN(atr) || atr <= 0.0)
return;
// A = k-2, B = k-1, C = k (now fully closed).
double aHigh = Bars.HighPrices[k - 2];
double aLow = Bars.LowPrices[k - 2];
double cHigh = Bars.HighPrices[k];
double cLow = Bars.LowPrices[k];
double minimumWidth = Math.Max(
MinimumGapPips * Symbol.PipSize,
MinimumAtrRatio * atr);
double bullishWidth = cLow - aHigh;
double bearishWidth = aLow - cHigh;
bool middleBullish = Bars.ClosePrices[k - 1] >
Bars.OpenPrices[k - 1];
bool middleBearish = Bars.ClosePrices[k - 1] <
Bars.OpenPrices[k - 1];
// First test geometric separation; then size and direction.
bool bull = bullishWidth > 0.0 &&
bullishWidth >= minimumWidth &&
(!RequireMiddleDirection || middleBullish);
bool bear = bearishWidth > 0.0 &&
bearishWidth >= minimumWidth &&
(!RequireMiddleDirection || middleBearish);
if (!bull && !bear)
return;
// Bull gap: A high..C low. Bear gap: C high..A low.
double lower = bull ? aHigh : cHigh;
double upper = bull ? cLow : aLow;
string name = "PS_FVG_" + (bull ? "B_" : "S_") +
Bars.OpenTimes[k].Ticks;
Color zoneColor = Color.FromArgb(
60, bull ? Color.Green : Color.Red);
var rectangle = Chart.DrawRectangle(
name, k - 2, lower, k + ExtendBars, upper, zoneColor);
rectangle.IsFilled = true;
rectangle.IsInteractive = false;
// Bound chart-object count; do not delete objects we do not own.
_objectNames.Enqueue(name);
while (_objectNames.Count > MaximumZones)
Chart.RemoveObject(_objectNames.Dequeue());
}
}
}
Parameters that materially change the output
| Input | Default | Research consequence |
|---|---|---|
| ATR Period | 14 | Shorter periods track volatility quickly but vary more across regimes; the first eligible C is delayed until ATR is established. |
| Minimum Gap (pips) | 4.0 | Rejects microscopic separations regardless of the recent ATR; note PipSize varies by symbol. |
| Minimum Gap / ATR | 0.40 | Rejects gaps that are small versus recent range; higher values reduce candidate frequency. |
| Require Middle Candle Direction | true | Requires B to close up for bullish FVG and down for bearish FVG. Dojis fail both directions. |
| Extend Zone (bars) | 8 | Sets a bounded horizontal display interval. Does not imply an order, stop, fill, or invalidation event. |
| Maximum Drawn Zones | 60 | Caps chart object memory and visual clutter; old objects are explicitly removed. |
Installation and inspection workflow
- Open cTrader Algo, create a new C# Indicator, paste the full source, and build it. Confirm that the API members resolve in your installed cTrader version.
- Attach the indicator to a standard candle chart. Initially keep the defaults and ensure sufficient historical bars are loaded for ATR.
- Choose a candle triplet. Read A’s high/low, B’s direction and C’s high/low from the platform data window, and calculate the gap manually in the instrument’s PipSize.
- Compare gap / ATR against the inputs. Verify that only the correct bullish or bearish bounded rectangle appears. Toggle the middle-candle-direction filter to understand its effect.
- Keep the chart running through a live candle close. Confirm that a developing C does not create a premature zone and that a new accepted zone appears only after its candle finishes.
- Change MaximumZones to a low value and inspect that older indicator-owned rectangles disappear while unrelated chart drawings remain.
Failure modes and validation traps
Two implementation subtleties deserve special attention. First, ATR is price-denominated and the pip parameter is pip-denominated; the conversion uses Symbol.PipSize, not a hardcoded five-digit FX assumption. In the published schematic, 0.0001 is appropriate for the stated EURUSD example, not every FX cross or CFD. Second, live and historical calculations may differ if the loaded history changes, spreads widen, or a symbol’s feed has missing bars. This indicator has no forward-looking requests: nevertheless, backfilled or corrected historical bars can change a retrospectively reconstructed chart.
The chart object limit protects readability but does not implement a complete cache of all qualifying patterns. If you need a persistent dataset or alerts, keep an immutable event log with time, gap boundaries, ATR, symbol, timeframe, and input settings. If you later transform a zone into an automated strategy, separately specify what constitutes entry, invalidation, position size, stop, execution model, and acceptable drawdown. None of those judgments is encoded here.
Validation checklist before relying on a zone
- Check bull and bear geometry against actual bar highs and lows, including equality (zero-width gaps are rejected).
- Verify both absolute and normalized thresholds and middle-candle direction with manually computed examples.
- Watch a live incomplete C change its high and low without creating or deleting an accepted closed-bar zone.
- Test sparse history, low-volatility bars, feed interruptions, different PipSize values and a rapid sequence of gap events.
- Compare multiple chart timeframes; the signal should use only the active chart timeframe and its closed candles.
- Review terminal build warnings, chart-object names and maximum-zone trimming on the cTrader version you actually run.
Interested in this free indicator or the underlying detection idea and want to tailor zone rules, alerts, persistence, or strategy integration to your workflow? Our Custom Trading Software Development Services can help you discuss a precise specification.
This source is an educational example and has not been compiled or forward-tested in your specific cTrader build. Perform your own platform-side build and visual verification. FVG patterns and volatility filters do not guarantee market direction or profitability. Trading, particularly with leverage, can result in substantial losses; never size positions from an unvalidated visual indicator alone.