Add TTM Scalper indicator implementation in C# and Pine Script; update Blma class for average calculation; remove missing indicators report and oscillator docs rewrite plans.

This commit is contained in:
Miha Kralj
2026-02-16 21:26:44 -08:00
parent b3a64f18fa
commit 63ae2c9ab2
68 changed files with 16069 additions and 587 deletions
@@ -0,0 +1,127 @@
using TradingPlatform.BusinessLayer;
using QuanTAlib;
namespace QuanTAlib.Tests;
public sealed class PivotfibIndicatorTests
{
[Fact]
public void PivotfibIndicator_Constructor_SetsDefaults()
{
var indicator = new PivotfibIndicator();
Assert.True(indicator.ShowColdValues);
Assert.Contains("PIVOTFIB", indicator.Name, StringComparison.Ordinal);
Assert.False(indicator.SeparateWindow);
Assert.True(indicator.OnBackGround);
}
[Fact]
public void PivotfibIndicator_MinHistoryDepths_EqualsZero()
{
var indicator = new PivotfibIndicator();
Assert.Equal(0, PivotfibIndicator.MinHistoryDepths);
IWatchlistIndicator watchlistIndicator = indicator;
Assert.Equal(0, watchlistIndicator.MinHistoryDepths);
}
[Fact]
public void PivotfibIndicator_ShortName_IsPivotfib()
{
var indicator = new PivotfibIndicator();
indicator.Initialize();
Assert.Contains("PIVOTFIB", indicator.ShortName, StringComparison.Ordinal);
}
[Fact]
public void PivotfibIndicator_SourceCodeLink_IsValid()
{
var indicator = new PivotfibIndicator();
Assert.Contains("github.com", indicator.SourceCodeLink, StringComparison.Ordinal);
Assert.Contains("Pivotfib", indicator.SourceCodeLink, StringComparison.Ordinal);
}
[Fact]
public void PivotfibIndicator_Initialize_CreatesInternalIndicator()
{
var indicator = new PivotfibIndicator();
indicator.Initialize();
// 7 line series: PP, R1, R2, R3, S1, S2, S3
Assert.Equal(7, indicator.LinesSeries.Count);
}
[Fact]
public void PivotfibIndicator_ProcessUpdate_HistoricalBar_ComputesValue()
{
var indicator = new PivotfibIndicator();
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 10; i++)
{
double basePrice = 100 + i * 2;
indicator.HistoricalData.AddBar(now.AddMinutes(i), basePrice, basePrice + 5, basePrice - 5, basePrice + 2);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
// PP is index 0
double pp = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(pp) || double.IsNaN(pp));
}
[Fact]
public void PivotfibIndicator_ProcessUpdate_NewBar_ComputesValue()
{
var indicator = new PivotfibIndicator();
indicator.Initialize();
var now = DateTime.UtcNow;
for (int i = 0; i < 5; i++)
{
indicator.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 110 + i, 90 + i, 105 + i);
var args = new UpdateArgs(UpdateReason.HistoricalBar);
indicator.ProcessUpdate(args);
}
// Simulate a new bar
indicator.HistoricalData.AddBar(now.AddMinutes(5), 110, 120, 100, 115);
var newArgs = new UpdateArgs(UpdateReason.NewBar);
indicator.ProcessUpdate(newArgs);
double pp = indicator.LinesSeries[0].GetValue(0);
Assert.True(double.IsFinite(pp) || double.IsNaN(pp));
}
[Fact]
public void PivotfibIndicator_SevenLineSeries_ArePresent()
{
var indicator = new PivotfibIndicator();
indicator.Initialize();
// PP=0, R1=1, R2=2, R3=3, S1=4, S2=5, S3=6
Assert.Equal(7, indicator.LinesSeries.Count);
Assert.Contains("PP", indicator.LinesSeries[0].Name, StringComparison.OrdinalIgnoreCase);
Assert.Contains("R1", indicator.LinesSeries[1].Name, StringComparison.OrdinalIgnoreCase);
Assert.Contains("S1", indicator.LinesSeries[4].Name, StringComparison.OrdinalIgnoreCase);
// Verify Fibonacci ratios in series names
Assert.Contains("38.2", indicator.LinesSeries[1].Name, StringComparison.Ordinal);
Assert.Contains("61.8", indicator.LinesSeries[2].Name, StringComparison.Ordinal);
}
[Fact]
public void PivotfibIndicator_Description_IsSet()
{
var indicator = new PivotfibIndicator();
Assert.NotNull(indicator.Description);
Assert.NotEmpty(indicator.Description);
Assert.Contains("Fibonacci", indicator.Description, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,72 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using TradingPlatform.BusinessLayer;
namespace QuanTAlib;
[SkipLocalsInit]
public sealed class PivotfibIndicator : Indicator, IWatchlistIndicator
{
[InputParameter("Show cold values", sortIndex: 21)]
public bool ShowColdValues { get; set; } = true;
private Pivotfib _indicator = null!;
private readonly LineSeries _ppSeries;
private readonly LineSeries _r1Series;
private readonly LineSeries _r2Series;
private readonly LineSeries _r3Series;
private readonly LineSeries _s1Series;
private readonly LineSeries _s2Series;
private readonly LineSeries _s3Series;
public static int MinHistoryDepths => 0;
int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths;
public override string ShortName => "PIVOTFIB";
public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/reversals/pivotfib/Pivotfib.cs";
public PivotfibIndicator()
{
OnBackGround = true;
SeparateWindow = false;
Name = "PIVOTFIB - Fibonacci Pivot Points";
Description = "Fibonacci pivot points: 7 support/resistance levels (PP, R1-R3, S1-S3) using Fibonacci ratios (0.382, 0.618, 1.000) applied to previous bar's range.";
_ppSeries = new LineSeries(name: "PP", color: Color.Yellow, width: 2, style: LineStyle.Solid);
_r1Series = new LineSeries(name: "R1 (38.2%)", color: Color.FromArgb(255, 200, 200), width: 1, style: LineStyle.Solid);
_r2Series = new LineSeries(name: "R2 (61.8%)", color: Color.FromArgb(255, 150, 150), width: 1, style: LineStyle.Solid);
_r3Series = new LineSeries(name: "R3 (100%)", color: Color.FromArgb(255, 100, 100), width: 1, style: LineStyle.Dash);
_s1Series = new LineSeries(name: "S1 (38.2%)", color: Color.FromArgb(200, 255, 200), width: 1, style: LineStyle.Solid);
_s2Series = new LineSeries(name: "S2 (61.8%)", color: Color.FromArgb(150, 255, 150), width: 1, style: LineStyle.Solid);
_s3Series = new LineSeries(name: "S3 (100%)", color: Color.FromArgb(100, 255, 100), width: 1, style: LineStyle.Dash);
AddLineSeries(_ppSeries);
AddLineSeries(_r1Series);
AddLineSeries(_r2Series);
AddLineSeries(_r3Series);
AddLineSeries(_s1Series);
AddLineSeries(_s2Series);
AddLineSeries(_s3Series);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnInit()
{
_indicator = new Pivotfib();
base.OnInit();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void OnUpdate(UpdateArgs args)
{
_ = _indicator.Update(this.GetInputBar(args), args.IsNewBar());
_ppSeries.SetValue(_indicator.PP, _indicator.IsHot, ShowColdValues);
_r1Series.SetValue(_indicator.R1, _indicator.IsHot, ShowColdValues);
_r2Series.SetValue(_indicator.R2, _indicator.IsHot, ShowColdValues);
_r3Series.SetValue(_indicator.R3, _indicator.IsHot, ShowColdValues);
_s1Series.SetValue(_indicator.S1, _indicator.IsHot, ShowColdValues);
_s2Series.SetValue(_indicator.S2, _indicator.IsHot, ShowColdValues);
_s3Series.SetValue(_indicator.S3, _indicator.IsHot, ShowColdValues);
}
}
+554
View File
@@ -0,0 +1,554 @@
// PIVOTFIB Tests - Fibonacci Pivot Points
namespace QuanTAlib.Tests;
// ── A) Constructor Tests ────────────────────────────────────────────
public sealed class PivotfibConstructorTests
{
[Fact]
public void DefaultConstructor_SetsExpectedDefaults()
{
var ind = new Pivotfib();
Assert.Equal("Pivotfib", ind.Name);
Assert.Equal(2, ind.WarmupPeriod);
Assert.False(ind.IsHot);
Assert.True(double.IsNaN(ind.PP));
}
[Fact]
public void SourceConstructor_PrimesFromSource()
{
var bars = new TBarSeries();
var dt = DateTime.UtcNow;
bars.Add(new TBar(dt, 110, 110, 90, 100, 1000));
bars.Add(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000));
var ind = new Pivotfib(bars);
Assert.True(ind.IsHot);
Assert.False(double.IsNaN(ind.PP));
}
}
// ── B) Basic Calculation Tests ──────────────────────────────────────
public sealed class PivotfibBasicTests
{
[Fact]
public void Update_ReturnsTValue()
{
var ind = new Pivotfib();
var bar = new TBar(DateTime.UtcNow, 110, 110, 90, 100, 1000);
TValue result = ind.Update(bar);
Assert.IsType<TValue>(result);
}
[Fact]
public void Last_IsAccessible()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 105, 105, 95, 100, 1000), isNew: true);
Assert.True(ind.IsHot);
Assert.True(double.IsFinite(ind.Last.Value));
}
[Fact]
public void KnownValues_FibonacciLevels()
{
// H=110, L=90, C=100 → PP=100, range=20
// R1=100+0.382*20=107.64, S1=100-0.382*20=92.36
// R2=100+0.618*20=112.36, S2=100-0.618*20=87.64
// R3=100+1.000*20=120, S3=100-1.000*20=80
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 105, 105, 95, 100, 1000), isNew: true);
Assert.Equal(100.0, ind.PP, 10);
Assert.Equal(107.64, ind.R1, 10);
Assert.Equal(92.36, ind.S1, 10);
Assert.Equal(112.36, ind.R2, 10);
Assert.Equal(87.64, ind.S2, 10);
Assert.Equal(120.0, ind.R3, 10);
Assert.Equal(80.0, ind.S3, 10);
}
[Fact]
public void LevelOrdering_S3_LessThan_S2_LessThan_S1_LessThan_PP_LessThan_R1_LessThan_R2_LessThan_R3()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 105, 105, 95, 100, 1000), isNew: true);
Assert.True(ind.S3 < ind.S2);
Assert.True(ind.S2 < ind.S1);
Assert.True(ind.S1 < ind.PP);
Assert.True(ind.PP < ind.R1);
Assert.True(ind.R1 < ind.R2);
Assert.True(ind.R2 < ind.R3);
}
[Fact]
public void FibonacciRatios_AreCorrect()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 105, 105, 95, 100, 1000), isNew: true);
double range = 110.0 - 90.0; // 20
double pp = ind.PP;
// Verify Fibonacci ratios
Assert.Equal(0.382, (ind.R1 - pp) / range, 10);
Assert.Equal(0.618, (ind.R2 - pp) / range, 10);
Assert.Equal(1.000, (ind.R3 - pp) / range, 10);
Assert.Equal(0.382, (pp - ind.S1) / range, 10);
Assert.Equal(0.618, (pp - ind.S2) / range, 10);
Assert.Equal(1.000, (pp - ind.S3) / range, 10);
}
[Fact]
public void Name_ReturnsExpectedString()
{
var ind = new Pivotfib();
Assert.Equal("Pivotfib", ind.Name);
}
}
// ── C) State + Bar Correction Tests ─────────────────────────────────
public sealed class PivotfibStateCorrectionTests
{
[Fact]
public void IsNew_True_AdvancesState()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
double pp1 = ind.PP;
ind.Update(new TBar(dt.AddMinutes(2), 120, 120, 100, 110, 1000), isNew: true);
double pp2 = ind.PP;
Assert.NotEqual(pp1, pp2);
}
[Fact]
public void IsNew_False_RewritesCurrentBar()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
double pp1 = ind.PP;
// Correction: rewrite the same bar
ind.Update(new TBar(dt.AddMinutes(1), 120, 120, 100, 110, 1000), isNew: false);
double pp2 = ind.PP;
// PP should be unchanged (still based on previous bar H=110,L=90,C=100)
Assert.Equal(pp1, pp2, 10);
}
[Fact]
public void IterativeCorrections_RestoreState()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
double ppBefore = ind.PP;
// Apply multiple corrections
ind.Update(new TBar(dt.AddMinutes(1), 200, 200, 50, 125, 1000), isNew: false);
ind.Update(new TBar(dt.AddMinutes(1), 300, 300, 10, 155, 1000), isNew: false);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: false);
Assert.Equal(ppBefore, ind.PP, 10);
}
[Fact]
public void Reset_ClearsAllState()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
Assert.True(ind.IsHot);
ind.Reset();
Assert.False(ind.IsHot);
Assert.True(double.IsNaN(ind.PP));
Assert.True(double.IsNaN(ind.R1));
Assert.True(double.IsNaN(ind.S1));
}
[Fact]
public void Reset_ThenReplay_MatchesOriginal()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
var bar1 = new TBar(dt, 110, 110, 90, 100, 1000);
var bar2 = new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000);
var bar3 = new TBar(dt.AddMinutes(2), 120, 120, 100, 110, 1000);
ind.Update(bar1, isNew: true);
ind.Update(bar2, isNew: true);
ind.Update(bar3, isNew: true);
double ppOriginal = ind.PP;
double r1Original = ind.R1;
double s1Original = ind.S1;
ind.Reset();
ind.Update(bar1, isNew: true);
ind.Update(bar2, isNew: true);
ind.Update(bar3, isNew: true);
Assert.Equal(ppOriginal, ind.PP, 10);
Assert.Equal(r1Original, ind.R1, 10);
Assert.Equal(s1Original, ind.S1, 10);
}
}
// ── D) Warmup / Convergence Tests ───────────────────────────────────
public sealed class PivotfibWarmupTests
{
[Fact]
public void IsHot_FlipsAfterWarmupPeriod()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
Assert.False(ind.IsHot);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
Assert.True(ind.IsHot);
}
[Fact]
public void WarmupPeriod_IsTwo()
{
var ind = new Pivotfib();
Assert.Equal(2, ind.WarmupPeriod);
}
}
// ── E) Robustness Tests ─────────────────────────────────────────────
public sealed class PivotfibRobustnessTests
{
[Fact]
public void NaN_UsesLastValidValue()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
// Feed NaN bar - should use last valid values and still produce valid PP
ind.Update(new TBar(dt.AddMinutes(2), double.NaN, double.NaN, double.NaN, double.NaN, 0), isNew: true);
Assert.False(double.IsNaN(ind.PP));
}
[Fact]
public void Infinity_UsesLastValidValue()
{
var ind = new Pivotfib();
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(2), double.PositiveInfinity, double.PositiveInfinity,
double.NegativeInfinity, double.PositiveInfinity, 0), isNew: true);
Assert.False(double.IsNaN(ind.PP));
Assert.True(double.IsFinite(ind.PP));
}
[Fact]
public void BatchNaN_Safe()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ind = new Pivotfib();
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
}
Assert.True(ind.IsHot);
Assert.False(double.IsNaN(ind.PP));
}
}
// ── F) Consistency Tests ────────────────────────────────────────────
public sealed class PivotfibConsistencyTests
{
private static TBarSeries CreateGbmBars(int count = 500)
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
}
[Fact]
public void Streaming_Matches_Batch()
{
var bars = CreateGbmBars();
// Streaming
var ind = new Pivotfib();
var streamResults = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
streamResults.Add(ind.PP);
}
// Batch
var batchResult = Pivotfib.Batch(bars);
Assert.Equal(bars.Count, batchResult.Count);
for (int i = 0; i < bars.Count; i++)
{
if (double.IsNaN(streamResults[i]) && double.IsNaN(batchResult[i].Value))
{
continue;
}
Assert.Equal(streamResults[i], batchResult[i].Value, 10);
}
}
[Fact]
public void Streaming_Matches_Span()
{
var bars = CreateGbmBars();
// Streaming
var ind = new Pivotfib();
var streamResults = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
streamResults.Add(ind.PP);
}
// Span
int len = bars.Count;
var ppOut = new double[len];
Pivotfib.Batch(bars.HighValues, bars.LowValues, bars.CloseValues, ppOut);
for (int i = 0; i < len; i++)
{
if (double.IsNaN(streamResults[i]) && double.IsNaN(ppOut[i]))
{
continue;
}
Assert.Equal(streamResults[i], ppOut[i], 10);
}
}
[Fact]
public void Streaming_Matches_BatchAll()
{
var bars = CreateGbmBars();
// Streaming - collect all 7 levels
var ind = new Pivotfib();
var sPP = new List<double>(bars.Count);
var sR1 = new List<double>(bars.Count);
var sS1 = new List<double>(bars.Count);
var sR2 = new List<double>(bars.Count);
var sS2 = new List<double>(bars.Count);
var sR3 = new List<double>(bars.Count);
var sS3 = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
sPP.Add(ind.PP);
sR1.Add(ind.R1);
sS1.Add(ind.S1);
sR2.Add(ind.R2);
sS2.Add(ind.S2);
sR3.Add(ind.R3);
sS3.Add(ind.S3);
}
// BatchAll
int len = bars.Count;
var ppOut = new double[len];
var r1Out = new double[len];
var s1Out = new double[len];
var r2Out = new double[len];
var s2Out = new double[len];
var r3Out = new double[len];
var s3Out = new double[len];
Pivotfib.BatchAll(
bars.HighValues, bars.LowValues, bars.CloseValues,
ppOut, r1Out, s1Out, r2Out, s2Out, r3Out, s3Out);
for (int i = 0; i < len; i++)
{
if (double.IsNaN(sPP[i])) { Assert.True(double.IsNaN(ppOut[i])); continue; }
Assert.Equal(sPP[i], ppOut[i], 10);
Assert.Equal(sR1[i], r1Out[i], 10);
Assert.Equal(sS1[i], s1Out[i], 10);
Assert.Equal(sR2[i], r2Out[i], 10);
Assert.Equal(sS2[i], s2Out[i], 10);
Assert.Equal(sR3[i], r3Out[i], 10);
Assert.Equal(sS3[i], s3Out[i], 10);
}
}
[Fact]
public void EventBased_MatchesStreaming()
{
var bars = CreateGbmBars();
// Streaming
var ind1 = new Pivotfib();
var streamResults = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind1.Update(bars[i], isNew: true);
streamResults.Add(ind1.PP);
}
// Event-based via Update(TBarSeries)
var ind2 = new Pivotfib();
var batchTSeries = ind2.Update(bars);
for (int i = 0; i < bars.Count; i++)
{
if (double.IsNaN(streamResults[i]) && double.IsNaN(batchTSeries[i].Value))
{
continue;
}
Assert.Equal(streamResults[i], batchTSeries[i].Value, 10);
}
}
}
// ── G) Span API Tests ───────────────────────────────────────────────
public sealed class PivotfibSpanTests
{
[Fact]
public void Batch_MismatchedInputLengths_Throws()
{
var high = new double[10];
var low = new double[9];
var close = new double[10];
var output = new double[10];
Assert.Throws<ArgumentException>(() => Pivotfib.Batch(high, low, close, output));
}
[Fact]
public void Batch_OutputTooShort_Throws()
{
var high = new double[10];
var low = new double[10];
var close = new double[10];
var output = new double[5];
Assert.Throws<ArgumentException>(() => Pivotfib.Batch(high, low, close, output));
}
[Fact]
public void BatchAll_MismatchedInputLengths_Throws()
{
var high = new double[10];
var low = new double[9];
var close = new double[10];
var pp = new double[10];
var r1 = new double[10];
var s1 = new double[10];
var r2 = new double[10];
var s2 = new double[10];
var r3 = new double[10];
var s3 = new double[10];
Assert.Throws<ArgumentException>(() => Pivotfib.BatchAll(high, low, close, pp, r1, s1, r2, s2, r3, s3));
}
[Fact]
public void BatchAll_OutputTooShort_Throws()
{
var high = new double[10];
var low = new double[10];
var close = new double[10];
var pp = new double[5];
var r1 = new double[10];
var s1 = new double[10];
var r2 = new double[10];
var s2 = new double[10];
var r3 = new double[10];
var s3 = new double[10];
Assert.Throws<ArgumentException>(() => Pivotfib.BatchAll(high, low, close, pp, r1, s1, r2, s2, r3, s3));
}
}
// ── H) Event / Chainability Tests ───────────────────────────────────
public sealed class PivotfibEventTests
{
[Fact]
public void Pub_FiresOnUpdate()
{
var ind = new Pivotfib();
int fireCount = 0;
ind.Pub += (object? _, in TValueEventArgs _e) => { fireCount++; };
var dt = DateTime.UtcNow;
ind.Update(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
ind.Update(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
Assert.Equal(2, fireCount);
}
[Fact]
public void EventChaining_Works()
{
var bars = new TBarSeries();
var ind = new Pivotfib(bars);
var receivedValues = new List<double>();
ind.Pub += (object? _, in TValueEventArgs e) => { receivedValues.Add(e.Value.Value); };
var dt = DateTime.UtcNow;
bars.Add(new TBar(dt, 110, 110, 90, 100, 1000), isNew: true);
bars.Add(new TBar(dt.AddMinutes(1), 115, 115, 95, 105, 1000), isNew: true);
Assert.True(receivedValues.Count >= 2);
}
}
// ── I) Prime Tests ──────────────────────────────────────────────────
public sealed class PivotfibPrimeTests
{
[Fact]
public void Prime_TBarSeries_SetsState()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var ind = new Pivotfib();
ind.Prime(bars);
Assert.True(ind.IsHot);
Assert.False(double.IsNaN(ind.PP));
}
[Fact]
public void Prime_ReadOnlySpan_SetsState()
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: 42);
var bars = gbm.Fetch(100, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
var values = new double[bars.Count];
for (int i = 0; i < bars.Count; i++)
{
values[i] = bars[i].Close;
}
var ind = new Pivotfib();
ind.Prime(values);
Assert.True(ind.IsHot);
Assert.False(double.IsNaN(ind.PP));
}
}
@@ -0,0 +1,248 @@
// PIVOTFIB Validation Tests - Fibonacci Pivot Points
// Self-consistency validation: math correctness, streaming==batch, streaming==span,
// streaming==batchAll, determinism, Calculate, level ordering.
// No external library implements Fibonacci Pivot Points with bar-to-bar granularity.
using System.Runtime.InteropServices;
namespace QuanTAlib.Tests;
public sealed class PivotfibValidationTests
{
private static TBarSeries CreateGbmBars(int count = 500, int seed = 42)
{
var gbm = new GBM(startPrice: 100.0, mu: 0.05, sigma: 0.20, seed: seed);
return gbm.Fetch(count, DateTime.UtcNow.Ticks, TimeSpan.FromMinutes(1));
}
// ── Math correctness ────────────────────────────────────────────
[Fact]
public void MathCorrectness_FibonacciFormula()
{
var bars = CreateGbmBars();
var ind = new Pivotfib();
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
if (i < 1) { continue; }
double pH = bars[i - 1].High;
double pL = bars[i - 1].Low;
double pC = bars[i - 1].Close;
double expectedPP = (pH + pL + pC) / 3.0;
double range = pH - pL;
Assert.Equal(expectedPP, ind.PP, 10);
Assert.Equal(expectedPP + 0.382 * range, ind.R1, 10);
Assert.Equal(expectedPP - 0.382 * range, ind.S1, 10);
Assert.Equal(expectedPP + 0.618 * range, ind.R2, 10);
Assert.Equal(expectedPP - 0.618 * range, ind.S2, 10);
Assert.Equal(expectedPP + range, ind.R3, 10);
Assert.Equal(expectedPP - range, ind.S3, 10);
}
}
// ── Streaming == Batch ──────────────────────────────────────────
[Fact]
public void Streaming_Matches_Batch_PP()
{
var bars = CreateGbmBars();
// Streaming
var ind = new Pivotfib();
var streamPP = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
streamPP.Add(ind.PP);
}
// Batch
var batchResult = Pivotfib.Batch(bars);
for (int i = 0; i < bars.Count; i++)
{
if (double.IsNaN(streamPP[i]))
{
Assert.True(double.IsNaN(batchResult[i].Value));
continue;
}
Assert.Equal(streamPP[i], batchResult[i].Value, 10);
}
}
// ── Streaming == Span ───────────────────────────────────────────
[Fact]
public void Streaming_Matches_Span_PP()
{
var bars = CreateGbmBars();
// Streaming
var ind = new Pivotfib();
var streamPP = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
streamPP.Add(ind.PP);
}
// Span
int len = bars.Count;
var ppOut = new double[len];
Pivotfib.Batch(bars.HighValues, bars.LowValues, bars.CloseValues, ppOut);
for (int i = 0; i < len; i++)
{
if (double.IsNaN(streamPP[i]))
{
Assert.True(double.IsNaN(ppOut[i]));
continue;
}
Assert.Equal(streamPP[i], ppOut[i], 10);
}
}
// ── Streaming == BatchAll (all 7 levels) ────────────────────────
[Fact]
public void Streaming_Matches_BatchAll_AllLevels()
{
var bars = CreateGbmBars();
// Streaming
var ind = new Pivotfib();
var sPP = new List<double>(bars.Count);
var sR1 = new List<double>(bars.Count);
var sS1 = new List<double>(bars.Count);
var sR2 = new List<double>(bars.Count);
var sS2 = new List<double>(bars.Count);
var sR3 = new List<double>(bars.Count);
var sS3 = new List<double>(bars.Count);
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
sPP.Add(ind.PP);
sR1.Add(ind.R1);
sS1.Add(ind.S1);
sR2.Add(ind.R2);
sS2.Add(ind.S2);
sR3.Add(ind.R3);
sS3.Add(ind.S3);
}
// BatchAll
int len = bars.Count;
var ppOut = new double[len];
var r1Out = new double[len];
var s1Out = new double[len];
var r2Out = new double[len];
var s2Out = new double[len];
var r3Out = new double[len];
var s3Out = new double[len];
Pivotfib.BatchAll(
bars.HighValues, bars.LowValues, bars.CloseValues,
ppOut, r1Out, s1Out, r2Out, s2Out, r3Out, s3Out);
for (int i = 0; i < len; i++)
{
if (double.IsNaN(sPP[i]))
{
Assert.True(double.IsNaN(ppOut[i]));
continue;
}
Assert.Equal(sPP[i], ppOut[i], 10);
Assert.Equal(sR1[i], r1Out[i], 10);
Assert.Equal(sS1[i], s1Out[i], 10);
Assert.Equal(sR2[i], r2Out[i], 10);
Assert.Equal(sS2[i], s2Out[i], 10);
Assert.Equal(sR3[i], r3Out[i], 10);
Assert.Equal(sS3[i], s3Out[i], 10);
}
}
// ── Determinism ─────────────────────────────────────────────────
[Fact]
public void Determinism_TwoRuns_IdenticalResults()
{
var bars = CreateGbmBars();
var ind1 = new Pivotfib();
var ind2 = new Pivotfib();
for (int i = 0; i < bars.Count; i++)
{
ind1.Update(bars[i], isNew: true);
ind2.Update(bars[i], isNew: true);
}
Assert.Equal(ind1.PP, ind2.PP, 15);
Assert.Equal(ind1.R1, ind2.R1, 15);
Assert.Equal(ind1.S1, ind2.S1, 15);
Assert.Equal(ind1.R2, ind2.R2, 15);
Assert.Equal(ind1.S2, ind2.S2, 15);
Assert.Equal(ind1.R3, ind2.R3, 15);
Assert.Equal(ind1.S3, ind2.S3, 15);
}
// ── Calculate factory ───────────────────────────────────────────
[Fact]
public void Calculate_ReturnsValidResults()
{
var bars = CreateGbmBars();
var (results, indicator) = Pivotfib.Calculate(bars);
Assert.NotNull(results);
Assert.NotNull(indicator);
Assert.Equal(bars.Count, results.Count);
Assert.True(indicator.IsHot);
}
// ── Level Ordering ──────────────────────────────────────────────
[Fact]
public void LevelOrdering_S3_LessThan_S2_LessThan_S1_LessThan_PP_LessThan_R1_LessThan_R2_LessThan_R3()
{
var bars = CreateGbmBars();
var ind = new Pivotfib();
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
if (!ind.IsHot) { continue; }
// For Fibonacci pivots with positive range, strict ordering holds
if (bars[i - 1].High > bars[i - 1].Low)
{
Assert.True(ind.S3 < ind.S2, $"S3 ({ind.S3}) should be < S2 ({ind.S2}) at bar {i}");
Assert.True(ind.S2 < ind.S1, $"S2 ({ind.S2}) should be < S1 ({ind.S1}) at bar {i}");
Assert.True(ind.S1 < ind.PP, $"S1 ({ind.S1}) should be < PP ({ind.PP}) at bar {i}");
Assert.True(ind.PP < ind.R1, $"PP ({ind.PP}) should be < R1 ({ind.R1}) at bar {i}");
Assert.True(ind.R1 < ind.R2, $"R1 ({ind.R1}) should be < R2 ({ind.R2}) at bar {i}");
Assert.True(ind.R2 < ind.R3, $"R2 ({ind.R2}) should be < R3 ({ind.R3}) at bar {i}");
}
}
}
// ── Symmetry ────────────────────────────────────────────────────
[Fact]
public void Symmetry_DistancesAboveAndBelowPP_AreEqual()
{
var bars = CreateGbmBars();
var ind = new Pivotfib();
for (int i = 0; i < bars.Count; i++)
{
ind.Update(bars[i], isNew: true);
if (!ind.IsHot) { continue; }
// Fibonacci pivots are symmetric: R_n - PP == PP - S_n
Assert.Equal(ind.R1 - ind.PP, ind.PP - ind.S1, 10);
Assert.Equal(ind.R2 - ind.PP, ind.PP - ind.S2, 10);
Assert.Equal(ind.R3 - ind.PP, ind.PP - ind.S3, 10);
}
}
}
+425
View File
@@ -0,0 +1,425 @@
// PIVOTFIB: Fibonacci Pivot Points
// Calculates 7 support/resistance levels using Fibonacci ratios applied to previous bar's HLC range.
// Fibonacci retracement levels (38.2%, 61.8%, 100%) centered on the pivot point.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
/// <summary>
/// PIVOTFIB: Fibonacci Pivot Points
/// </summary>
/// <remarks>
/// Computes 7 horizontal support/resistance levels from the previous bar's
/// high, low, and close using Fibonacci ratios. The central pivot point (PP)
/// is the arithmetic mean of HLC; resistance and support levels are derived
/// by adding/subtracting Fibonacci proportions of the prior bar's range.
///
/// Calculation (using previous bar's H, L, C):
/// <code>
/// PP = (H + L + C) / 3
/// range = H - L
/// R1 = PP + 0.382 * range S1 = PP - 0.382 * range
/// R2 = PP + 0.618 * range S2 = PP - 0.618 * range
/// R3 = PP + 1.000 * range S3 = PP - 1.000 * range
/// </code>
///
/// <b>Key characteristics:</b>
/// - O(1) computation: pure arithmetic from previous bar's HLC
/// - 7 outputs: PP, R1, R2, R3, S1, S2, S3
/// - WarmupPeriod = 2 (need previous bar's HLC)
/// - No configurable parameters
/// - Levels remain constant until a new bar arrives
/// </remarks>
/// <seealso href="Pivotfib.md">Detailed documentation</seealso>
[SkipLocalsInit]
public sealed class Pivotfib : ITValuePublisher
{
[StructLayout(LayoutKind.Auto)]
private record struct State(
double PrevHigh,
double PrevLow,
double PrevClose,
double LastValidHigh,
double LastValidLow,
double LastValidClose);
private State _s;
private State _ps;
private int _count;
private readonly TBarPublishedHandler _barHandler;
/// <summary>Display name for the indicator.</summary>
public string Name { get; }
/// <summary>Bars required for the indicator to warm up.</summary>
public int WarmupPeriod { get; }
/// <summary>Central Pivot Point: (prevH + prevL + prevC) / 3</summary>
public double PP { get; private set; }
/// <summary>Resistance 1: PP + 0.382 * range</summary>
public double R1 { get; private set; }
/// <summary>Resistance 2: PP + 0.618 * range</summary>
public double R2 { get; private set; }
/// <summary>Resistance 3: PP + 1.000 * range</summary>
public double R3 { get; private set; }
/// <summary>Support 1: PP - 0.382 * range</summary>
public double S1 { get; private set; }
/// <summary>Support 2: PP - 0.618 * range</summary>
public double S2 { get; private set; }
/// <summary>Support 3: PP - 1.000 * range</summary>
public double S3 { get; private set; }
/// <summary>Primary output value (PP as TValue).</summary>
public TValue Last { get; private set; }
/// <summary>True when enough bars have been processed for valid output.</summary>
public bool IsHot => _count >= 2;
public event TValuePublishedHandler? Pub;
/// <summary>
/// Creates a Fibonacci Pivot Points indicator.
/// </summary>
public Pivotfib()
{
_count = 0;
_s = new State(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN);
_ps = _s;
PP = double.NaN;
R1 = double.NaN;
R2 = double.NaN;
R3 = double.NaN;
S1 = double.NaN;
S2 = double.NaN;
S3 = double.NaN;
Name = "Pivotfib";
WarmupPeriod = 2;
_barHandler = HandleBar;
}
/// <summary>
/// Creates a Fibonacci Pivot Points indicator chained to a TBarSeries source.
/// </summary>
public Pivotfib(TBarSeries source)
: this()
{
Prime(source);
source.Pub += _barHandler;
}
private void HandleBar(object? sender, in TBarEventArgs e) => Update(e.Value, e.IsNew);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void PubEvent(TValue value, bool isNew = true) =>
Pub?.Invoke(this, new TValueEventArgs { Value = value, IsNew = isNew });
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TBar input, bool isNew = true)
{
if (isNew)
{
_ps = _s;
_count++;
}
else
{
_s = _ps;
}
var s = _s;
// Validate inputs - substitute last-valid on NaN/Infinity
double high = input.High;
double low = input.Low;
double close = input.Close;
if (double.IsFinite(high)) { s.LastValidHigh = high; }
else { high = s.LastValidHigh; }
if (double.IsFinite(low)) { s.LastValidLow = low; }
else { low = s.LastValidLow; }
if (double.IsFinite(close)) { s.LastValidClose = close; }
else { close = s.LastValidClose; }
// If still no valid data, return NaN
if (double.IsNaN(high) || double.IsNaN(low) || double.IsNaN(close))
{
_s = s;
SetAllNaN();
Last = new TValue(input.Time, double.NaN);
PubEvent(Last, isNew);
return Last;
}
// First bar: store HLC but cannot compute pivots yet (no previous bar)
if (_count < 2)
{
s.PrevHigh = high;
s.PrevLow = low;
s.PrevClose = close;
_s = s;
SetAllNaN();
Last = new TValue(input.Time, double.NaN);
PubEvent(Last, isNew);
return Last;
}
// Compute pivot levels from PREVIOUS bar's HLC
double pH = s.PrevHigh;
double pL = s.PrevLow;
double pC = s.PrevClose;
double pp = (pH + pL + pC) / 3.0;
double range = pH - pL;
PP = pp;
R1 = Math.FusedMultiplyAdd(0.382, range, pp); // pp + 0.382 * range
S1 = Math.FusedMultiplyAdd(-0.382, range, pp); // pp - 0.382 * range
R2 = Math.FusedMultiplyAdd(0.618, range, pp); // pp + 0.618 * range
S2 = Math.FusedMultiplyAdd(-0.618, range, pp); // pp - 0.618 * range
R3 = pp + range; // pp + 1.000 * range
S3 = pp - range; // pp - 1.000 * range
// Store current bar's HLC as "previous" for next bar
s.PrevHigh = high;
s.PrevLow = low;
s.PrevClose = close;
_s = s;
Last = new TValue(input.Time, PP);
PubEvent(Last, isNew);
return Last;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TValue Update(TValue input, bool isNew = true) =>
Update(new TBar(input.Time, input.Value, input.Value, input.Value, input.Value, 0), isNew);
public TSeries Update(TBarSeries source)
{
if (source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.HighValues, source.LowValues, source.CloseValues,
CollectionsMarshal.AsSpan(v));
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
// Prime internal state for continued streaming
Prime(source);
var lastTime = new DateTime(source.Times[^1], DateTimeKind.Utc);
Last = new TValue(lastTime, CollectionsMarshal.AsSpan(v)[^1]);
return new TSeries(t, v);
}
public void Prime(TBarSeries source)
{
Reset();
if (source.Count == 0)
{
return;
}
for (int i = 0; i < source.Count; i++)
{
Update(source[i], isNew: true);
}
}
public void Prime(ReadOnlySpan<double> source, TimeSpan? step = null)
{
Reset();
if (source.Length == 0)
{
return;
}
long t = DateTime.UtcNow.Ticks;
long stepTicks = (step ?? TimeSpan.FromMinutes(1)).Ticks;
for (int i = 0; i < source.Length; i++)
{
double val = source[i];
Update(new TBar(t, val, val, val, val, 0), isNew: true);
t += stepTicks;
}
}
public void Reset()
{
_count = 0;
_s = new State(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN);
_ps = _s;
SetAllNaN();
Last = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetAllNaN()
{
PP = double.NaN;
R1 = double.NaN;
R2 = double.NaN;
R3 = double.NaN;
S1 = double.NaN;
S2 = double.NaN;
S3 = double.NaN;
}
/// <summary>
/// Batch computation of Fibonacci Pivot Points over span data.
/// Writes PP values to <paramref name="ppOutput"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(
ReadOnlySpan<double> high,
ReadOnlySpan<double> low,
ReadOnlySpan<double> close,
Span<double> ppOutput)
{
if (high.Length != low.Length || high.Length != close.Length)
{
throw new ArgumentException("Input spans must have the same length.", nameof(high));
}
if (ppOutput.Length < high.Length)
{
throw new ArgumentException("Output span must be at least as long as input.", nameof(ppOutput));
}
int len = high.Length;
if (len == 0)
{
return;
}
// First bar: no previous data
ppOutput[0] = double.NaN;
// Remaining bars: compute from previous bar's HLC
for (int i = 1; i < len; i++)
{
double pH = high[i - 1];
double pL = low[i - 1];
double pC = close[i - 1];
ppOutput[i] = (pH + pL + pC) / 3.0;
}
}
public static TSeries Batch(TBarSeries source)
{
if (source == null || source.Count == 0)
{
return new TSeries([], []);
}
int len = source.Count;
var t = new List<long>(len);
var v = new List<double>(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
Batch(source.HighValues, source.LowValues, source.CloseValues,
CollectionsMarshal.AsSpan(v));
source.Times.CopyTo(CollectionsMarshal.AsSpan(t));
return new TSeries(t, v);
}
/// <summary>
/// Batch computation of all 7 Fibonacci Pivot Point levels over span data.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BatchAll(
ReadOnlySpan<double> high,
ReadOnlySpan<double> low,
ReadOnlySpan<double> close,
Span<double> ppOut,
Span<double> r1Out,
Span<double> s1Out,
Span<double> r2Out,
Span<double> s2Out,
Span<double> r3Out,
Span<double> s3Out)
{
if (high.Length != low.Length || high.Length != close.Length)
{
throw new ArgumentException("Input spans must have the same length.", nameof(high));
}
int len = high.Length;
if (ppOut.Length < len) { throw new ArgumentException("Output span too short.", nameof(ppOut)); }
if (r1Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(r1Out)); }
if (s1Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(s1Out)); }
if (r2Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(r2Out)); }
if (s2Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(s2Out)); }
if (r3Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(r3Out)); }
if (s3Out.Length < len) { throw new ArgumentException("Output span too short.", nameof(s3Out)); }
if (len == 0)
{
return;
}
// First bar: no previous data
ppOut[0] = double.NaN;
r1Out[0] = double.NaN;
s1Out[0] = double.NaN;
r2Out[0] = double.NaN;
s2Out[0] = double.NaN;
r3Out[0] = double.NaN;
s3Out[0] = double.NaN;
for (int i = 1; i < len; i++)
{
double pH = high[i - 1];
double pL = low[i - 1];
double pC = close[i - 1];
double pp = (pH + pL + pC) / 3.0;
double range = pH - pL;
ppOut[i] = pp;
r1Out[i] = Math.FusedMultiplyAdd(0.382, range, pp);
s1Out[i] = Math.FusedMultiplyAdd(-0.382, range, pp);
r2Out[i] = Math.FusedMultiplyAdd(0.618, range, pp);
s2Out[i] = Math.FusedMultiplyAdd(-0.618, range, pp);
r3Out[i] = pp + range;
s3Out[i] = pp - range;
}
}
public static (TSeries Results, Pivotfib Indicator) Calculate(TBarSeries source)
{
var indicator = new Pivotfib();
var results = indicator.Update(source);
return (results, indicator);
}
}
+72
View File
@@ -0,0 +1,72 @@
# PIVOTFIB: Fibonacci Pivot Points
## Overview
Fibonacci Pivot Points apply Fibonacci retracement ratios (38.2%, 61.8%, 100%) to the standard pivot point formula. The central pivot (PP) uses the classic HLC/3 calculation, while support and resistance levels are derived by adding or subtracting Fibonacci proportions of the previous bar's trading range.
## Origin and Sources
- **Concept**: Adaptation of Leonardo Fibonacci's ratios (derived from the Fibonacci sequence) to traditional pivot point analysis
- **Foundation**: Standard pivot points combined with Fibonacci retracement levels (0.382, 0.618, 1.000)
## Formula
Using previous bar's High (H), Low (L), Close (C):
```
PP = (H + L + C) / 3
range = H - L
R1 = PP + 0.382 × range S1 = PP - 0.382 × range
R2 = PP + 0.618 × range S2 = PP - 0.618 × range
R3 = PP + 1.000 × range S3 = PP - 1.000 × range
```
### Known Values Example
For H = 110, L = 90, C = 100:
- PP = 100.0, range = 20
- R1 = 107.64, S1 = 92.36
- R2 = 112.36, S2 = 87.64
- R3 = 120.00, S3 = 80.00
## Key Properties
- **Symmetry**: R_n - PP = PP - S_n for all levels
- **Level ordering**: S3 < S2 < S1 < PP < R1 < R2 < R3 (when range > 0)
- **Fibonacci ratios**: Distances from PP are proportional to 0.382, 0.618, and 1.000 of the range
- **Golden ratio relationship**: 0.618 ≈ φ - 1, where φ = (1 + √5) / 2; 0.382 = 1 - 0.618
## Usage
```csharp
// Streaming
var fib = new Pivotfib();
var result = fib.Update(bar);
double pp = fib.PP;
double r1 = fib.R1; // 38.2% resistance
double r2 = fib.R2; // 61.8% resistance
double r3 = fib.R3; // 100% resistance
double s1 = fib.S1; // 38.2% support
double s2 = fib.S2; // 61.8% support
double s3 = fib.S3; // 100% support
// Batch
var results = Pivotfib.Batch(bars);
// All 7 levels at once
Pivotfib.BatchAll(high, low, close, ppOut, r1Out, s1Out, r2Out, s2Out, r3Out, s3Out);
```
## Comparison with Other Pivot Variants
| Variant | R/S Formula | Levels | Ratios Used |
|---------|------------|--------|-------------|
| **PIVOT** (Classic) | Arithmetic from PP | 7 | 1×, 2× range |
| **PIVOTFIB** | Fibonacci × range | 7 | 0.382, 0.618, 1.000 |
| **PIVOTCAM** (Camarilla) | Close ± ratio × range | 9 | 1.1/12 series |
| **PIVOTEXT** (Extended) | Arithmetic extended | 11 | 1×–4× range |
| **PIVOTDEM** (DeMark) | Conditional X/4 | 3 | Direction-based |
## Implementation Details
- **WarmupPeriod**: 2 bars (need previous bar's HLC)
- **Parameters**: None
- **Outputs**: 7 (PP, R1, R2, R3, S1, S2, S3)
- **Input**: TBar (OHLCV)
- **Complexity**: O(1) per bar
- **Uses FMA**: `Math.FusedMultiplyAdd` for R1/S1/R2/S2 computations