// Copyright (c) 2026 fxtradingguide.com
// SPDX-License-Identifier: MIT
using FxTradingGuide.Studies;
namespace FxTradingGuide.Strategies.DonchianBreakout;
///
/// Close-confirmed channel. The current observation is not part of its own
/// channel. On this sample, high, low and close are the same reference rate.
///
public static class DonchianBreakout
{
public const int Entry = 20;
public const int Exit = 10;
public static double?[] PriorExtreme(IReadOnlyList values, int window, bool highest)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(window);
var result = new double?[values.Count];
for (var index = window; index < values.Count; index++)
{
var extreme = values[index - window];
for (var cursor = index - window + 1; cursor < index; cursor++)
{
var price = values[cursor];
if (highest ? price > extreme : price < extreme)
{
extreme = price;
}
}
result[index] = extreme;
}
return result;
}
public static int?[] Signals(
IReadOnlyList high,
IReadOnlyList low,
IReadOnlyList close,
int entry = Entry,
int exitWindow = Exit)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(entry);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(exitWindow);
if (high.Count != low.Count || low.Count != close.Count)
{
throw new ArgumentException("high, low and close must be the same length");
}
var entryHigh = PriorExtreme(high, entry, highest: true);
var entryLow = PriorExtreme(low, entry, highest: false);
var exitHigh = PriorExtreme(high, exitWindow, highest: true);
var exitLow = PriorExtreme(low, exitWindow, highest: false);
var position = 0;
var desired = new int?[close.Count];
for (var index = 0; index < close.Count; index++)
{
if (entryHigh[index] is null || exitLow[index] is null)
{
desired[index] = null;
continue;
}
var price = close[index];
if (position == 1 && price < exitLow[index])
{
position = 0;
}
else if (position == -1 && price > exitHigh[index])
{
position = 0;
}
if (position <= 0 && price > entryHigh[index])
{
position = 1;
}
else if (position >= 0 && price < entryLow[index])
{
position = -1;
}
desired[index] = position;
}
return desired;
}
public static void AssertFixture()
{
var highest = PriorExtreme(new[] { 1d, 3d, 2d, 5d }, 2, highest: true);
if (highest[0] is not null || highest[1] is not null || highest[2] != 3d || highest[3] != 3d)
{
throw new InvalidOperationException("channel fixture failed");
}
}
}
public static class Program
{
public static void Main()
{
DonchianBreakout.AssertFixture();
var observations = SampleSeries.Load();
var rates = observations.Select(item => item.Rate).ToArray();
StudyReport.AssertCausal(rates.Length, end =>
{
var slice = new double[end];
Array.Copy(rates, slice, end);
return DonchianBreakout.Signals(slice, slice, slice);
});
StudyReport.Write("donchian-breakout", observations, DonchianBreakout.Signals(rates, rates, rates));
}
}