adding missing validations

This commit is contained in:
Miha Kralj
2026-02-26 09:59:44 -08:00
parent 467a8c1cef
commit 9ab37c1200
231 changed files with 60015 additions and 302 deletions
@@ -0,0 +1,155 @@
using TradingPlatform.BusinessLayer;
namespace QuanTAlib.Tests;
public class ReflexIndicatorTests
{
[Fact]
public void ReflexIndicator_Constructor_SetsDefaults()
{
var indicator = new ReflexIndicator();
Assert.Equal(20, indicator.Period);
Assert.Equal(SourceType.Close, indicator.Source);
Assert.True(indicator.ShowColdValues);
Assert.Equal("REFLEX - Ehlers Reflex Indicator", indicator.Name);
Assert.True(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void ReflexIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new ReflexIndicator();
Assert.Equal(0, ReflexIndicator.MinHistoryDepths);
Assert.Equal(0, ((IWatchlistIndicator)indicator).MinHistoryDepths);
}
[Fact]
public void ReflexIndicator_ShortName_IncludesPeriodAndSource()
{
var indicator = new ReflexIndicator { Period = 30 };
Assert.Contains("REFLEX", indicator.ShortName, StringComparison.Ordinal);
Assert.Contains("30", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void ReflexIndicator_SourceCodeLink_IsValid()
{
var indicator = new ReflexIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Reflex.Quantower.cs", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void ReflexIndicator_Initialize_CreatesInternalIndicator()
{
var indicator = new ReflexIndicator { Period = 20 };
indicator.Initialize();
// After init, one line series should exist (Reflex is single output)
Assert.Single(indicator.LinesSeries);
}
[Fact]
public void ReflexIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new ReflexIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
Assert.Equal(1, indicator.LinesSeries[0].Count);
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(0)));
}
[Fact]
public void ReflexIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new ReflexIndicator { Period = 3 };
indicator.Initialize();
var now = DateTime.UtcNow;
indicator.HistoricalData.AddBar(now, 100, 105, 95, 102);
indicator.HistoricalData.AddBar(now.AddMinutes(1), 102, 108, 100, 106);
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
indicator.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
Assert.Equal(2, indicator.LinesSeries[0].Count);
}
[Fact]
public void ReflexIndicator_InternalIndicator_HandlesBarCorrection()
{
// Test the underlying Reflex with isNew=false (bar correction)
var ma = new Reflex(3);
var now = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
ma.Update(new TValue(now.AddMinutes(i).Ticks, 100 + i), isNew: true);
}
double beforeCorrection = ma.Last.Value;
// Correct last bar with a very different value
ma.Update(new TValue(now.AddMinutes(9).Ticks, 200), isNew: false);
double afterCorrection = ma.Last.Value;
Assert.NotEqual(beforeCorrection, afterCorrection);
Assert.True(double.IsFinite(afterCorrection));
}
[Fact]
public void ReflexIndicator_DifferentSourceTypes()
{
foreach (SourceType sourceType in new[] { SourceType.Close, SourceType.Open, SourceType.High, SourceType.Low })
{
var indicator = new ReflexIndicator();
indicator.Source = sourceType;
Assert.Equal(sourceType, indicator.Source);
}
}
[Fact]
public void ReflexIndicator_MultipleHistoricalBars()
{
var indicator = new ReflexIndicator { Period = 5 };
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 20; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 105 + i, 95 + i, 102 + i);
indicator.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
}
Assert.Equal(20, indicator.LinesSeries[0].Count);
// All values should be finite
for (int i = 0; i < 20; i++)
{
Assert.True(double.IsFinite(indicator.LinesSeries[0].GetValue(i)));
}
}
[Fact]
public void ReflexIndicator_PeriodChange_UpdatesConfig()
{
var indicator = new ReflexIndicator();
indicator.Period = 25;
Assert.Equal(25, indicator.Period);
indicator.Period = 50;
Assert.Equal(50, indicator.Period);
}
}
@@ -0,0 +1,56 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class ReflexIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Period", sortIndex: 1, 2, 1000, 1, 0)]
public int Period { get; set; } = 20;
[IndicatorExtensions.DataSourceInput]
public SourceType Source { get; set; } = SourceType.Close;
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Reflex _ma = null!;
private readonly LineSeries _series;
private string _sourceName = null!;
private Func<IHistoryItem, double> _priceSelector = null!;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => $"REFLEX {Period}:{_sourceName}";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/oscillators/reflex/Reflex.Quantower.cs";
public ReflexIndicator()
{
OnBackGround = true;
SeparateWindow = true;
_sourceName = Source.ToString();
Name = "REFLEX - Ehlers Reflex Indicator";
Description = "Measures reversal tendency via Super Smoother pre-filter with linear extrapolation deviation and RMS normalization";
_series = new LineSeries(name: $"REFLEX {Period}", color: Color.Yellow, width: 2, style: LineStyle.Solid);
AddLineSeries(_series);
}
protected override void OnInit()
{
_ma = new Reflex(Period);
_sourceName = Source.ToString();
_priceSelector = Source.GetPriceSelector();
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
var item = HistoricalData[Count - 1, SeekOriginHistory.Begin];
TValue result = _ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew: args.IsNewBar());
_series.SetValue(result.Value, _ma.IsHot, ShowColdValues);
}
}
+436
View File
@@ -0,0 +1,436 @@
namespace QuanTAlib;
public class ReflexTests
{
private const int DefaultPeriod = 20;
private const double Tolerance = 1e-12;
private static TSeries MakeSeries(int count = 500)
{
var gbm = new GBM(startPrice: 100, mu: 0.05, sigma: 0.5, seed: 42);
var bars = gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
return bars.Close;
}
// ========== A) Constructor Validation ==========
[Fact]
public void Constructor_ZeroPeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Reflex(0));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_OnePeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Reflex(1));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_NegativePeriod_ThrowsArgumentOutOfRangeException()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new Reflex(-5));
Assert.Equal("period", ex.ParamName);
}
[Fact]
public void Constructor_ValidPeriod_SetsNameAndWarmup()
{
var indicator = new Reflex(20);
Assert.Equal("Reflex(20)", indicator.Name);
Assert.Equal(20, indicator.WarmupPeriod);
}
[Fact]
public void Constructor_PeriodTwo_IsValid()
{
var indicator = new Reflex(2);
Assert.Equal("Reflex(2)", indicator.Name);
Assert.Equal(2, indicator.WarmupPeriod);
}
// ========== B) Basic Calculation ==========
[Fact]
public void Update_ReturnsTValue_WithValidProperties()
{
var indicator = new Reflex(DefaultPeriod);
var input = new TValue(DateTime.UtcNow, 100.0);
TValue result = indicator.Update(input);
Assert.Equal(input.Time, result.Time);
Assert.True(double.IsFinite(result.Value));
}
[Fact]
public void Update_AfterWarmup_IsHotBecomesTrue()
{
var indicator = new Reflex(DefaultPeriod);
Assert.False(indicator.IsHot);
for (int i = 0; i < 500; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.1));
}
Assert.True(indicator.IsHot);
}
[Fact]
public void Update_LastProperty_MatchesReturnValue()
{
var indicator = new Reflex(DefaultPeriod);
var input = new TValue(DateTime.UtcNow, 42.0);
TValue result = indicator.Update(input);
Assert.Equal(result.Value, indicator.Last.Value, Tolerance);
}
// ========== C) State + Bar Correction ==========
[Fact]
public void IsNew_True_AdvancesState()
{
var indicator = new Reflex(DefaultPeriod);
// Warm up past the period threshold first
for (int i = 0; i < DefaultPeriod + 5; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i * 0.5), isNew: true);
}
TValue r1 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), 120.0), isNew: true);
TValue r2 = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(31), 80.0), isNew: true);
// Two very different bars after warmup must produce different results
Assert.NotEqual(r1.Value, r2.Value);
}
[Fact]
public void IsNew_False_RewritesCurrentBar()
{
var indicator = new Reflex(DefaultPeriod);
for (int i = 0; i < 50; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 200.0), isNew: true);
double afterNew = indicator.Last.Value;
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(50), 150.0), isNew: false);
double afterCorrection = indicator.Last.Value;
Assert.NotEqual(afterNew, afterCorrection);
}
[Fact]
public void IterativeCorrections_RestoreState()
{
var indicator = new Reflex(DefaultPeriod);
TSeries data = MakeSeries();
for (int i = 0; i < 50; i++)
{
indicator.Update(data[i], isNew: true);
}
indicator.Update(data[50], isNew: true);
for (int j = 0; j < 5; j++)
{
indicator.Update(data[50], isNew: false);
}
double afterCorrections = indicator.Last.Value;
var fresh = new Reflex(DefaultPeriod);
for (int i = 0; i <= 50; i++)
{
fresh.Update(data[i], isNew: true);
}
Assert.Equal(fresh.Last.Value, afterCorrections, Tolerance);
}
[Fact]
public void Reset_ClearsState()
{
var indicator = new Reflex(DefaultPeriod);
for (int i = 0; i < 50; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.True(indicator.IsHot);
indicator.Reset();
Assert.False(indicator.IsHot);
Assert.Equal(default, indicator.Last);
}
// ========== D) Warmup/Convergence ==========
[Fact]
public void IsHot_FlipsAtCorrectTime()
{
var indicator = new Reflex(10);
int hotAt = -1;
for (int i = 0; i < 200; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
if (indicator.IsHot && hotAt < 0)
{
hotAt = i;
break;
}
}
Assert.InRange(hotAt, 1, 200);
}
// ========== E) Robustness ==========
[Fact]
public void NaN_Input_UsesLastValidValue()
{
var indicator = new Reflex(DefaultPeriod);
for (int i = 0; i < 30; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
TValue nanResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.NaN));
Assert.True(double.IsFinite(nanResult.Value));
}
[Fact]
public void Infinity_Input_UsesLastValidValue()
{
var indicator = new Reflex(DefaultPeriod);
for (int i = 0; i < 30; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
}
TValue infResult = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(30), double.PositiveInfinity));
Assert.True(double.IsFinite(infResult.Value));
}
[Fact]
public void BatchNaN_DoesNotPropagate()
{
int period = 10;
double[] source = new double[100];
double[] output = new double[100];
for (int i = 0; i < 100; i++)
{
source[i] = 100.0 + i * 0.5;
}
source[50] = double.NaN;
source[51] = double.NaN;
Reflex.Batch(source, output, period);
for (int i = 0; i < 100; i++)
{
Assert.True(double.IsFinite(output[i]), $"Output[{i}] is not finite");
}
}
// ========== F) Consistency (4 API modes) ==========
[Fact]
public void AllModes_ProduceSameResult()
{
int period = 10;
TSeries data = MakeSeries();
// 1. Batch (TSeries)
TSeries batchResults = Reflex.Batch(data, period);
double expected = batchResults.Last.Value;
// 2. Span batch
var tValues = data.Values.ToArray();
var spanOutput = new double[tValues.Length];
Reflex.Batch(new ReadOnlySpan<double>(tValues), spanOutput, period);
double spanResult = spanOutput[^1];
// 3. Streaming
var streaming = new Reflex(period);
for (int i = 0; i < data.Count; i++)
{
streaming.Update(data[i]);
}
double streamingResult = streaming.Last.Value;
// 4. Eventing
var pubSource = new TSeries();
var eventBased = new Reflex(pubSource, period);
for (int i = 0; i < data.Count; i++)
{
pubSource.Add(data[i]);
}
double eventingResult = eventBased.Last.Value;
Assert.Equal(expected, spanResult, precision: 9);
Assert.Equal(expected, streamingResult, precision: 9);
Assert.Equal(expected, eventingResult, precision: 9);
}
// ========== G) Span API Tests ==========
[Fact]
public void SpanBatch_MismatchedLengths_ThrowsArgumentException()
{
double[] source = new double[10];
double[] output = new double[5];
var ex = Assert.Throws<ArgumentException>(() => Reflex.Batch(source, output, 5));
Assert.Equal("output", ex.ParamName);
}
[Fact]
public void SpanBatch_PeriodOne_ThrowsArgumentOutOfRangeException()
{
double[] source = new double[10];
double[] output = new double[10];
Assert.Throws<ArgumentOutOfRangeException>(() => Reflex.Batch(source, output, 1));
}
[Fact]
public void SpanBatch_EmptyInput_ProducesEmptyOutput()
{
double[] source = Array.Empty<double>();
double[] output = Array.Empty<double>();
var ex = Record.Exception(() => Reflex.Batch(source, output, 10));
Assert.Null(ex);
}
[Fact]
public void SpanBatch_LargeData_DoesNotStackOverflow()
{
int size = 5000;
double[] source = new double[size];
double[] output = new double[size];
for (int i = 0; i < size; i++)
{
source[i] = 100.0 + i * 0.1;
}
Reflex.Batch(source, output, 20);
Assert.True(double.IsFinite(output[size - 1]));
}
// ========== H) Chainability ==========
[Fact]
public void Pub_EventFires_OnUpdate()
{
var indicator = new Reflex(DefaultPeriod);
int eventCount = 0;
indicator.Pub += (object? sender, in TValueEventArgs args) => eventCount++;
for (int i = 0; i < 10; i++)
{
indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0 + i));
}
Assert.Equal(10, eventCount);
}
[Fact]
public void EventBased_Chaining_Works()
{
var source = new TSeries();
var indicator = new Reflex(source, 5);
source.Add(new TValue(DateTime.UtcNow, 100));
source.Add(new TValue(DateTime.UtcNow, 110));
source.Add(new TValue(DateTime.UtcNow, 120));
Assert.True(double.IsFinite(indicator.Last.Value));
}
[Fact]
public void Calculate_ReturnsHotIndicator()
{
TSeries data = MakeSeries();
(TSeries results, Reflex indicator) = Reflex.Calculate(data, DefaultPeriod);
Assert.Equal(data.Count, results.Count);
Assert.True(indicator.IsHot);
}
[Fact]
public void StaticCalculate_MatchesInstance()
{
const int period = 10;
int count = 100;
var source = new TSeries();
var indicator = new Reflex(period);
for (int i = 0; i < count; i++)
{
source.Add(new TValue(DateTime.UtcNow.AddMinutes(i), i + 10));
indicator.Update(source.Last);
}
var staticResult = Reflex.Batch(source, period);
Assert.Equal(source.Count, staticResult.Count);
Assert.Equal(indicator.Last.Value, staticResult.Last.Value, 8);
}
// ========== Reflex-specific: Oscillator behavior ==========
[Fact]
public void ConstantInput_OutputConvergesToZero()
{
var indicator = new Reflex(10);
double lastResult = double.NaN;
for (int i = 0; i < 300; i++)
{
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), 100.0));
lastResult = r.Value;
}
// Constant input → zero deviation from linear extrapolation → zero output
Assert.Equal(0.0, lastResult, 1e-10);
}
[Fact]
public void ReflexProducesFiniteValues_OnGBMData()
{
var indicator = new Reflex(10);
TSeries data = MakeSeries(200);
int nonFiniteCount = 0;
for (int i = 0; i < data.Count; i++)
{
TValue r = indicator.Update(data[i]);
if (!double.IsFinite(r.Value))
{
nonFiniteCount++;
}
}
Assert.Equal(0, nonFiniteCount);
}
}
@@ -0,0 +1,178 @@
using Xunit;
using Xunit.Abstractions;
namespace QuanTAlib.Tests;
public sealed class ReflexValidationTests : IDisposable
{
private readonly ITestOutputHelper _output;
private readonly ValidationTestData _testData;
private const int DefaultPeriod = 20;
public ReflexValidationTests(ITestOutputHelper output)
{
_output = output;
_testData = new ValidationTestData(5000);
}
public void Dispose()
{
_testData.Dispose();
}
// ========== Self-consistency Validation ==========
[Fact]
public void Reflex_BatchStreaming_Match()
{
// Streaming
var streaming = new Reflex(DefaultPeriod);
var streamResults = new List<double>(_testData.Data.Count);
for (int i = 0; i < _testData.Data.Count; i++)
{
TValue r = streaming.Update(_testData.Data[i], isNew: true);
streamResults.Add(r.Value);
}
// Batch
TSeries batchResults = Reflex.Batch(_testData.Data, DefaultPeriod);
int mismatchCount = 0;
double maxDiff = 0;
for (int i = 0; i < streamResults.Count; i++)
{
double diff = Math.Abs(streamResults[i] - batchResults[i].Value);
if (diff > 1e-10)
{
mismatchCount++;
maxDiff = Math.Max(maxDiff, diff);
}
}
_output.WriteLine($"Reflex({DefaultPeriod}) Batch vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
Assert.Equal(0, mismatchCount);
}
[Fact]
public void Reflex_SpanBatch_MatchesStreaming()
{
// Streaming
var streaming = new Reflex(DefaultPeriod);
var streamResults = new List<double>(_testData.Data.Count);
for (int i = 0; i < _testData.Data.Count; i++)
{
TValue r = streaming.Update(_testData.Data[i], isNew: true);
streamResults.Add(r.Value);
}
// Span batch
double[] output = new double[_testData.Data.Count];
Reflex.Batch(_testData.Data.Values, output, DefaultPeriod);
int mismatchCount = 0;
double maxDiff = 0;
for (int i = 0; i < streamResults.Count; i++)
{
double diff = Math.Abs(streamResults[i] - output[i]);
if (diff > 1e-10)
{
mismatchCount++;
maxDiff = Math.Max(maxDiff, diff);
}
}
_output.WriteLine($"Reflex({DefaultPeriod}) Span vs Streaming: {mismatchCount} mismatches, max diff = {maxDiff:E3}");
Assert.Equal(0, mismatchCount);
}
[Fact]
public void Reflex_DifferentPeriods_ProduceDifferentResults()
{
TSeries result10 = Reflex.Batch(_testData.Data, 10);
TSeries result20 = Reflex.Batch(_testData.Data, 20);
int lastIdx = _testData.Data.Count - 1;
_output.WriteLine($"Reflex(10) last = {result10[lastIdx].Value:F6}");
_output.WriteLine($"Reflex(20) last = {result20[lastIdx].Value:F6}");
Assert.NotEqual(result10[lastIdx].Value, result20[lastIdx].Value);
}
[Fact]
public void Reflex_ConstantInput_ConvergesToZero()
{
var indicator = new Reflex(10);
double constantVal = 100.0;
double lastResult = double.NaN;
for (int i = 0; i < 1000; i++)
{
TValue r = indicator.Update(new TValue(DateTime.UtcNow.AddSeconds(i), constantVal));
lastResult = r.Value;
}
_output.WriteLine($"Reflex(10) constant input result after 1000 bars: {lastResult:E6}");
Assert.True(Math.Abs(lastResult) < 1e-6, $"Expected near-zero for constant input, got {lastResult}");
}
[Fact]
public void Reflex_Calculate_ReturnsHotIndicator()
{
(TSeries results, Reflex indicator) = Reflex.Calculate(_testData.Data, DefaultPeriod);
Assert.Equal(_testData.Data.Count, results.Count);
Assert.True(indicator.IsHot);
// Verify the indicator can continue streaming
TValue next = indicator.Update(new TValue(DateTime.UtcNow, 100.0), isNew: true);
Assert.True(double.IsFinite(next.Value));
_output.WriteLine($"Reflex({DefaultPeriod}) Calculate: {results.Count} bars, last = {results[results.Count - 1].Value:F6}");
}
[Fact]
public void Reflex_BarCorrection_ProducesConsistentResults()
{
// Build reference: 100 bars then bar 101
var reference = new Reflex(DefaultPeriod);
for (int i = 0; i < 100; i++)
{
reference.Update(_testData.Data[i], isNew: true);
}
reference.Update(new TValue(DateTime.UtcNow, 50.0), isNew: true);
double referenceVal = reference.Last.Value;
// Build test: 100 bars, wrong bar 101, then correct bar 101
var test = new Reflex(DefaultPeriod);
for (int i = 0; i < 100; i++)
{
test.Update(_testData.Data[i], isNew: true);
}
test.Update(new TValue(DateTime.UtcNow, 999.0), isNew: true); // wrong
test.Update(new TValue(DateTime.UtcNow, 50.0), isNew: false); // correct
double testVal = test.Last.Value;
_output.WriteLine($"Reference: {referenceVal:F10}, Corrected: {testVal:F10}");
Assert.Equal(referenceVal, testVal, 1e-10);
}
[Fact]
public void Reflex_SubsetValidation_StableBehavior()
{
using var subset = _testData.CreateSubset(200);
TSeries results = Reflex.Batch(subset.Data, DefaultPeriod);
int nanCount = 0;
for (int i = 0; i < results.Count; i++)
{
if (!double.IsFinite(results[i].Value))
{
nanCount++;
}
}
_output.WriteLine($"Reflex({DefaultPeriod}) on 200-bar subset: {nanCount} non-finite values");
Assert.Equal(0, nanCount);
}
}
+410
View File
@@ -0,0 +1,410 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// REFLEX: Ehlers Reflex Indicator
/// </summary>
/// <remarks>
/// Measures the reversal tendency of price by comparing a Super-Smoother-filtered
/// price against a linear extrapolation from N bars ago. John F. Ehlers (2020).
///
/// Calculation:
/// <c>SSF[n] = c1 * (src + src[1]) * 0.5 + c2 * SSF[1] + c3 * SSF[2]</c>
/// <c>slope = (Filt[N] - Filt) / N</c>
/// <c>Sum = Σ(i=1..N)[(Filt + i*slope) - Filt[i]] / N</c>
/// <c>MS = 0.04 * Sum² + 0.96 * MS[1]</c>
/// <c>Reflex = Sum / √MS</c>
/// </remarks>
/// <seealso href="Reflex.md">Detailed documentation</seealso>
/// <seealso href="reflex.pine">Reference Pine Script implementation</seealso>
[SkipLocalsInit]
public sealed class Reflex : AbstractBase
{
[StructLayout(LayoutKind.Auto)]
private record struct State(
double Filt, double Filt1,
double Src1, double Ms,
int Count, double LastValid)
{
public static State New() => new()
{
Filt = 0,
Filt1 = 0,
Src1 = 0,
Ms = 0,
Count = 0,
LastValid = 0
};
}
private readonly int _period;
private readonly double _c1;
private readonly double _c2;
private readonly double _c3;
private State _s = State.New();
private State _ps = State.New();
// Circular buffer of size period+1 to store filt history for lookback access
private readonly double[] _buf;
private int _head;
private int _snapHead;
private const double RMS_ALPHA = 0.04;
private const double RMS_DECAY = 0.96;
private const int StackallocThreshold = 256;
/// <summary>
/// Creates Reflex with specified period.
/// </summary>
/// <param name="period">Lookback period for reflex measurement (must be &gt; 1)</param>
public Reflex(int period)
{
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 2.");
}
_period = period;
// Super Smoother (2-pole Butterworth) at half-period cutoff
double halfPeriod = period * 0.5;
double a1 = Math.Exp(-1.414 * Math.PI / halfPeriod);
double b1 = 2.0 * a1 * Math.Cos(1.414 * Math.PI / halfPeriod);
_c2 = b1;
_c3 = -(a1 * a1);
_c1 = 1.0 - _c2 - _c3;
// Circular buffer of size period+1; index 0..period
_buf = new double[period + 1];
_head = 0;
_snapHead = 0;
Name = $"Reflex({period})";
WarmupPeriod = period;
}
/// <summary>
/// Creates Reflex with specified source and period.
/// Subscribes to source.Pub event.
/// </summary>
public Reflex(ITValuePublisher source, int period) : this(period)
{
source.Pub += Handle;
}
/// <summary>
/// Creates Reflex with a TSeries source, primes from history, then subscribes.
/// </summary>
public Reflex(TSeries source, int period) : this(period)
{
Prime(source.Values);
if (source.Count > 0)
{
Last = new TValue(source.LastTime, Last.Value);
}
source.Pub += Handle;
}
/// <inheritdoc/>
public override bool IsHot => _s.Count >= _period;
/// <inheritdoc/>
public override void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
if (source.Length == 0)
{
return;
}
_s = State.New();
_ps = State.New();
Array.Clear(_buf);
_head = 0;
_snapHead = 0;
int len = source.Length;
double[]? rented = len > StackallocThreshold ? ArrayPool<double>.Shared.Rent(len) : null;
Span<double> temp = rented != null ? rented.AsSpan(0, len) : stackalloc double[len];
try
{
CalculateCore(source, temp, _period, _c1, _c2, _c3, ref _s, _buf, ref _head);
Last = new TValue(DateTime.MinValue, temp[len - 1]);
_ps = _s;
_snapHead = _head;
}
finally
{
if (rented != null)
{
ArrayPool<double>.Shared.Return(rented);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static double GetValidValue(double input, ref State s)
{
if (double.IsFinite(input))
{
s.LastValid = input;
return input;
}
return s.LastValid;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public override TValue Update(TValue input, bool isNew = true)
{
if (isNew)
{
_ps = _s;
_snapHead = _head;
}
else
{
_s = _ps;
_head = _snapHead;
}
double val = GetValidValue(input.Value, ref _s);
double result = Compute(val, _period, _c1, _c2, _c3, ref _s, _buf, ref _head);
Last = new TValue(input.Time, result);
PubEvent(Last, isNew);
return Last;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public override TSeries Update(TSeries source)
{
if (source.Count == 0)
{
return [];
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
CalculateCore(source.Values, vSpan, _period, _c1, _c2, _c3, ref _s, _buf, ref _head);
source.Times.CopyTo(tSpan);
_ps = _s;
_snapHead = _head;
Last = new TValue(tSpan[len - 1], vSpan[len - 1]);
return new TSeries(t, v);
}
/// <summary>
/// Core streaming computation: SSF → circular buffer → slope + deviation sum → RMS normalization.
/// O(period) per bar for the deviation summation loop.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static double Compute(double input, int period, double c1, double c2, double c3,
ref State s, double[] buf, ref int head)
{
s.Count++;
// --- Super Smoother filter ---
double filt;
if (s.Count <= 2)
{
filt = input;
}
else
{
filt = Math.FusedMultiplyAdd(c1, (input + s.Src1) * 0.5,
Math.FusedMultiplyAdd(c2, s.Filt, c3 * s.Filt1));
}
s.Filt1 = s.Filt;
s.Filt = filt;
s.Src1 = input;
// --- Store current filt in circular buffer ---
// buf has size period+1; head points to the slot to write current value
buf[head] = filt;
int count = Math.Min(s.Count, period);
double result = 0.0;
if (count >= period)
{
// filt[period] is the oldest entry: (head - period + period+1) % (period+1)
int bufSize = period + 1;
int lagIdx = (head - period + bufSize) % bufSize;
double filtLag = buf[lagIdx];
// slope = (filtLag - filt) / period [Pine: (Filt[N] - Filt) / N]
double slope = (filtLag - filt) / period;
// Sum deviations from linear extrapolation
double sum = 0.0;
for (int i = 1; i <= period; i++)
{
int idx = (head - i + bufSize) % bufSize;
// (filt + i*slope) - filt[i]
sum += Math.FusedMultiplyAdd((double)i, slope, filt) - buf[idx];
}
sum /= period;
// RMS normalization
s.Ms = Math.FusedMultiplyAdd(RMS_ALPHA, sum * sum, RMS_DECAY * s.Ms);
result = s.Ms > 0.0 ? sum / Math.Sqrt(s.Ms) : 0.0;
}
// Advance head after storing current value and computing (so filt[1] is buf[prev_head])
head = (head + 1) % (period + 1);
return result;
}
/// <summary>
/// Core batch calculation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void CalculateCore(ReadOnlySpan<double> source, Span<double> output,
int period, double c1, double c2, double c3, ref State s, double[] buf, ref int head)
{
int len = source.Length;
for (int i = 0; i < len; i++)
{
double val = source[i];
if (double.IsFinite(val))
{
s.LastValid = val;
}
else
{
val = s.LastValid;
}
s.Count++;
// Super Smoother
double filt;
if (s.Count <= 2)
{
filt = val;
}
else
{
filt = Math.FusedMultiplyAdd(c1, (val + s.Src1) * 0.5,
Math.FusedMultiplyAdd(c2, s.Filt, c3 * s.Filt1));
}
s.Filt1 = s.Filt;
s.Filt = filt;
s.Src1 = val;
buf[head] = filt;
int count = Math.Min(s.Count, period);
double result = 0.0;
if (count >= period)
{
int bufSize = period + 1;
int lagIdx = (head - period + bufSize) % bufSize;
double filtLag = buf[lagIdx];
double slope = (filtLag - filt) / period;
double sum = 0.0;
for (int j = 1; j <= period; j++)
{
int idx = (head - j + bufSize) % bufSize;
sum += Math.FusedMultiplyAdd((double)j, slope, filt) - buf[idx];
}
sum /= period;
s.Ms = Math.FusedMultiplyAdd(RMS_ALPHA, sum * sum, RMS_DECAY * s.Ms);
result = s.Ms > 0.0 ? sum / Math.Sqrt(s.Ms) : 0.0;
}
head = (head + 1) % (period + 1);
output[i] = result;
}
}
/// <summary>
/// Batch calculation returning a TSeries.
/// </summary>
public static TSeries Batch(TSeries source, int period)
{
var indicator = new Reflex(period);
return indicator.Update(source);
}
/// <summary>
/// Batch calculation writing to a pre-allocated output span. Zero-allocation hot path.
/// </summary>
public static void Batch(ReadOnlySpan<double> source, Span<double> output, int period)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (period < 2)
{
throw new ArgumentOutOfRangeException(nameof(period), period, "Period must be at least 2.");
}
if (source.Length == 0)
{
return;
}
double halfPeriod = period * 0.5;
double a1 = Math.Exp(-1.414 * Math.PI / halfPeriod);
double b1 = 2.0 * a1 * Math.Cos(1.414 * Math.PI / halfPeriod);
double c2 = b1;
double c3 = -(a1 * a1);
double c1 = 1.0 - c2 - c3;
var state = State.New();
var buf = new double[period + 1];
int head = 0;
CalculateCore(source, output, period, c1, c2, c3, ref state, buf, ref head);
}
/// <summary>
/// Creates a hot indicator from historical data, ready for streaming.
/// </summary>
public static (TSeries Results, Reflex Indicator) Calculate(TSeries source, int period)
{
var indicator = new Reflex(period);
TSeries results = indicator.Update(source);
return (results, indicator);
}
/// <inheritdoc/>
public override void Reset()
{
_s = State.New();
_ps = _s;
Array.Clear(_buf);
_head = 0;
_snapHead = 0;
Last = default;
}
}