diff --git a/.github/workflows/Publish.yml b/.github/workflows/Publish.yml
index 4e9d31b0..18e0d78b 100644
--- a/.github/workflows/Publish.yml
+++ b/.github/workflows/Publish.yml
@@ -409,7 +409,70 @@ jobs:
if-no-files-found: warn
# ==============================================================================
- # 5) DeepSource Coverage Upload
+ # 5) GitHub Code Scanning Upload (SARIF → Security tab)
+ # ==============================================================================
+ GitHub_Security_Upload:
+ needs: [ReSharper_Analysis, Snyk_Scan, Semgrep_Scan, Sonar_Analysis]
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ actions: read
+ security-events: write
+ if: always()
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ ref: ${{ env.CHECKOUT_REF }}
+
+ - name: Download all SARIF artifacts
+ uses: actions/download-artifact@v4
+ with:
+ pattern: sarif-*
+ path: sarif
+ merge-multiple: true
+
+ - name: List SARIF files
+ run: |
+ echo "Downloaded SARIF files:"
+ find sarif -name "*.sarif" -o -name "*.sarif.json" 2>/dev/null | head -50 || true
+ ls -la sarif/ || true
+
+ - name: Upload ReSharper SARIF to GitHub Security
+ if: always()
+ uses: github/codeql-action/upload-sarif@v3
+ with:
+ sarif_file: sarif/resharper.sarif
+ category: resharper
+ continue-on-error: true
+
+ - name: Upload Snyk SARIF to GitHub Security
+ if: always()
+ uses: github/codeql-action/upload-sarif@v3
+ with:
+ sarif_file: sarif/snyk.sarif
+ category: snyk
+ continue-on-error: true
+
+ - name: Upload Semgrep SARIF to GitHub Security
+ if: always()
+ uses: github/codeql-action/upload-sarif@v3
+ with:
+ sarif_file: sarif/semgrep.sarif
+ category: semgrep
+ continue-on-error: true
+
+ - name: Upload Roslyn SARIF to GitHub Security
+ if: always()
+ uses: github/codeql-action/upload-sarif@v3
+ with:
+ sarif_file: sarif/roslyn.sarif
+ category: roslyn
+ continue-on-error: true
+
+ # ==============================================================================
+ # 6) DeepSource Coverage Upload
# ==============================================================================
DeepSource_Upload:
needs: [Sonar_Analysis]
@@ -441,7 +504,7 @@ jobs:
fi
curl https://deepsource.io/cli | sh
-
+
if [ -f "coverage-merged/Cobertura.xml" ]; then
./bin/deepsource report --analyzer test-coverage --key csharp --value-file coverage-merged/Cobertura.xml
else
@@ -449,7 +512,7 @@ jobs:
fi
# ==============================================================================
- # 6) Codacy Upload (SARIF + Coverage)
+ # 7) Codacy Upload (SARIF + Coverage)
# ==============================================================================
Codacy_Upload:
needs: [ReSharper_Analysis, Snyk_Scan, Semgrep_Scan, Sonar_Analysis]
@@ -499,13 +562,13 @@ jobs:
if: steps.check_token.outputs.skip != 'true'
run: |
set -euo pipefail
-
+
# Install Codacy CLI using official bootstrap script
echo "Installing Codacy CLI v2..."
sudo curl -Ls https://raw.githubusercontent.com/codacy/codacy-cli-v2/main/codacy-cli.sh -o /usr/local/bin/codacy-cli
sudo chmod +x /usr/local/bin/codacy-cli
-
+
# Script will fetch binary if needed
codacy-cli version
diff --git a/docs/indicators.md b/docs/indicators.md
index 4f50b2fc..02ef5904 100644
--- a/docs/indicators.md
+++ b/docs/indicators.md
@@ -172,6 +172,7 @@ Price envelope and boundary indicators for breakout and mean-reversion strategie
| [**PCHANNEL**](../lib/channels/pchannel/pchannel.md) | Price Channel | Highest high / lowest low; identical to Donchian |
| [**REGCHANNEL**](../lib/channels/regchannel/regchannel.md) | Linear Regression Channel | Linear regression line with standard deviation bands |
| [**SDCHANNEL**](../lib/channels/sdchannel/sdchannel.md) | Standard Deviation Channel | Moving average with standard deviation bands |
+| [**STARCHANNEL**](../lib/channels/starchannel/starchannel.md) | Stoller Average Range Channel | SMA with ATR bands; similar to Keltner but uses SMA |
### Statistics
diff --git a/docs/validation.md b/docs/validation.md
index dd887cf4..cff40aa1 100644
--- a/docs/validation.md
+++ b/docs/validation.md
@@ -251,7 +251,7 @@ No external reference exists. Implementation verified through unit tests, edge c
| **Stochastic Momentum Index** | Smi | - | - | ✔️ | ❔ |
| **Stochastic Oscillator** | Stoch | ✔️ | ✔️ | ✔️ | ❔ |
| **Stochastic RSI** | Stochrsi | ✔️ | ✔️ | ✔️ | ❔ |
-| **Stoller Average Range Channel** | Starchannel | - | - | - | ❔ |
+| **Stoller Average Range Channel** | [Starchannel](../lib/channels/starchannel/starchannel.md) | - | - | - | ❔ |
| **Super Trend Bands** | Stbands | - | - | - | - |
| **SuperTrend** | [Super](../lib/trends/super/super.md) | - | - | ✔️ | ❔ |
| **Swing High/Low Detection** | Swings | - | - | - | - |
diff --git a/lib/channels/_index.md b/lib/channels/_index.md
index 87eca2ab..30c1cb68 100644
--- a/lib/channels/_index.md
+++ b/lib/channels/_index.md
@@ -24,7 +24,7 @@ Channels define dynamic support and resistance. Upper band shows where price ten
| [PCHANNEL](lib/channels/pchannel/pchannel.md) | Price Channel | Highest high and lowest low. Identical to Donchian Channels. |
| [REGCHANNEL](lib/channels/regchannel/regchannel.md) | Linear Regression Channel | Linear regression line with standard deviation bands. |
| [SDCHANNEL](lib/channels/sdchannel/sdchannel.md) | Standard Deviation Channel | Moving average with standard deviation bands. |
-| STARCHANNEL | Stoller Average Range Channel | ATR-based channel around moving average. Similar to Keltner. |
+| [STARCHANNEL](lib/channels/starchannel/starchannel.md) | Stoller Average Range Channel | SMA with ATR bands. Similar to Keltner but uses SMA instead of EMA. |
| STBANDS | Super Trend Bands | ATR-based trend-following bands. Flips direction on breakout. |
| UBANDS | Ultimate Bands | Composite volatility bands using multiple measures. |
| UCHANNEL | Ultimate Channel | Adaptive channel using multiple volatility inputs. |
diff --git a/lib/channels/starchannel/Starchannel.Quantower.Tests.cs b/lib/channels/starchannel/Starchannel.Quantower.Tests.cs
new file mode 100644
index 00000000..a8b41d66
--- /dev/null
+++ b/lib/channels/starchannel/Starchannel.Quantower.Tests.cs
@@ -0,0 +1,234 @@
+using TradingPlatform.BusinessLayer;
+using Xunit;
+
+namespace QuanTAlib.Tests;
+
+public class StarchannelIndicatorTests
+{
+ [Fact]
+ public void Constructor_SetsDefaults()
+ {
+ var ind = new StarchannelIndicator();
+
+ Assert.Equal(20, ind.Period);
+ Assert.Equal(2.0, ind.Multiplier);
+ Assert.True(ind.ShowColdValues);
+ Assert.Equal("Starchannel - Stoller Average Range Channel", ind.Name);
+ Assert.False(ind.SeparateWindow);
+ Assert.True(ind.OnBackGround);
+ }
+
+ [Fact]
+ public void MinHistoryDepths_EqualsPeriod()
+ {
+ var ind = new StarchannelIndicator { Period = 15 };
+ Assert.Equal(15, ind.MinHistoryDepths);
+ }
+
+ [Fact]
+ public void ShortName_ReflectsParameters()
+ {
+ var ind = new StarchannelIndicator { Period = 12, Multiplier = 1.5 };
+ Assert.Contains("12", ind.ShortName, StringComparison.Ordinal);
+ Assert.Contains("1.5", ind.ShortName, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Initialize_AddsThreeLineSeries()
+ {
+ var ind = new StarchannelIndicator { Period = 14, Multiplier = 2.0 };
+ ind.Initialize();
+
+ Assert.Equal(3, ind.LinesSeries.Count);
+ Assert.Equal("Middle", ind.LinesSeries[0].Name);
+ Assert.Equal("Upper", ind.LinesSeries[1].Name);
+ Assert.Equal("Lower", ind.LinesSeries[2].Name);
+ }
+
+ [Fact]
+ public void ProcessUpdate_Historical_ComputesValues()
+ {
+ var ind = new StarchannelIndicator { Period = 3, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ ind.HistoricalData.AddBar(now, 100, 110, 90, 102);
+
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
+
+ Assert.Equal(1, ind.LinesSeries[0].Count);
+ Assert.True(double.IsFinite(ind.LinesSeries[0].GetValue(0)));
+ Assert.True(double.IsFinite(ind.LinesSeries[1].GetValue(0)));
+ Assert.True(double.IsFinite(ind.LinesSeries[2].GetValue(0)));
+ }
+
+ [Fact]
+ public void ProcessUpdate_NewBar_Appends()
+ {
+ var ind = new StarchannelIndicator { Period = 3, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ ind.HistoricalData.AddBar(now, 100, 110, 90, 102);
+ ind.HistoricalData.AddBar(now.AddMinutes(1), 102, 112, 92, 104);
+
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
+
+ Assert.Equal(2, ind.LinesSeries[0].Count);
+ }
+
+ [Fact]
+ public void ProcessUpdate_NewTick_DoesNotThrow()
+ {
+ var ind = new StarchannelIndicator { Period = 5, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ ind.HistoricalData.AddBar(now, 100, 105, 95, 102);
+
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.NewTick));
+
+ Assert.Equal(2, ind.LinesSeries[0].Count);
+ }
+
+ [Fact]
+ public void MultipleUpdates_ProducesFiniteSeries()
+ {
+ var ind = new StarchannelIndicator { Period = 5, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ for (int i = 0; i < 20; i++)
+ {
+ ind.HistoricalData.AddBar(now.AddMinutes(i), 100 + i, 105 + i, 95 + i, 102 + i);
+ ind.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ }
+
+ Assert.Equal(20, ind.LinesSeries[0].Count);
+ Assert.Equal(20, ind.LinesSeries[1].Count);
+ Assert.Equal(20, ind.LinesSeries[2].Count);
+
+ for (int i = 0; i < 20; i++)
+ {
+ Assert.True(double.IsFinite(ind.LinesSeries[0].GetValue(i)));
+ Assert.True(double.IsFinite(ind.LinesSeries[1].GetValue(i)));
+ Assert.True(double.IsFinite(ind.LinesSeries[2].GetValue(i)));
+ }
+ }
+
+ [Fact]
+ public void Bands_Order_Correct()
+ {
+ var ind = new StarchannelIndicator { Period = 5, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ // Create bars with some volatility
+ for (int i = 0; i < 10; i++)
+ {
+ ind.HistoricalData.AddBar(now.AddMinutes(i), 100, 110, 90, 100, 1000);
+ ind.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ }
+
+ double middle = ind.LinesSeries[0].GetValue(0);
+ double upper = ind.LinesSeries[1].GetValue(0);
+ double lower = ind.LinesSeries[2].GetValue(0);
+
+ // After warmup with volatility, upper > middle > lower
+ Assert.True(upper >= middle, $"Upper ({upper}) should be >= Middle ({middle})");
+ Assert.True(lower <= middle, $"Lower ({lower}) should be <= Middle ({middle})");
+ }
+
+ [Fact]
+ public void Bands_Expand_WithVolatility()
+ {
+ var ind = new StarchannelIndicator { Period = 5, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+
+ // First few bars: low volatility
+ for (int i = 0; i < 5; i++)
+ {
+ ind.HistoricalData.AddBar(now.AddMinutes(i), 100, 101, 99, 100);
+ ind.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ }
+
+ double lowVolWidth = ind.LinesSeries[1].GetValue(0) - ind.LinesSeries[2].GetValue(0);
+
+ // Next bars: high volatility
+ for (int i = 5; i < 15; i++)
+ {
+ ind.HistoricalData.AddBar(now.AddMinutes(i), 100, 120, 80, 100);
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.NewBar));
+ }
+
+ double highVolWidth = ind.LinesSeries[1].GetValue(0) - ind.LinesSeries[2].GetValue(0);
+
+ Assert.True(highVolWidth > lowVolWidth, "Higher volatility should produce wider bands");
+ }
+
+ [Fact]
+ public void FirstBar_AllBandsEqualClose()
+ {
+ var ind = new StarchannelIndicator { Period = 10, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ ind.HistoricalData.AddBar(now, 100, 110, 90, 105);
+ ind.ProcessUpdate(new UpdateArgs(UpdateReason.HistoricalBar));
+
+ double middle = ind.LinesSeries[0].GetValue(0);
+ double upper = ind.LinesSeries[1].GetValue(0);
+ double lower = ind.LinesSeries[2].GetValue(0);
+
+ // First bar: all equal close (no ATR yet)
+ Assert.Equal(105.0, middle, 1e-10);
+ Assert.Equal(105.0, upper, 1e-10);
+ Assert.Equal(105.0, lower, 1e-10);
+ }
+
+ [Fact]
+ public void Multiplier_AffectsBandWidth()
+ {
+ var ind1 = new StarchannelIndicator { Period = 10, Multiplier = 1.0 };
+ var ind2 = new StarchannelIndicator { Period = 10, Multiplier = 2.0 };
+ ind1.Initialize();
+ ind2.Initialize();
+
+ var now = DateTime.UtcNow;
+ for (int i = 0; i < 20; i++)
+ {
+ ind1.HistoricalData.AddBar(now.AddMinutes(i), 100, 110, 90, 100);
+ ind2.HistoricalData.AddBar(now.AddMinutes(i), 100, 110, 90, 100);
+ ind1.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ ind2.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ }
+
+ double width1 = ind1.LinesSeries[1].GetValue(0) - ind1.LinesSeries[2].GetValue(0);
+ double width2 = ind2.LinesSeries[1].GetValue(0) - ind2.LinesSeries[2].GetValue(0);
+
+ Assert.Equal(width2, width1 * 2, 1e-9);
+ }
+
+ [Fact]
+ public void SMA_ConvergesToConstantPrice()
+ {
+ var ind = new StarchannelIndicator { Period = 5, Multiplier = 2.0 };
+ ind.Initialize();
+
+ var now = DateTime.UtcNow;
+ // Feed constant close price
+ for (int i = 0; i < 10; i++)
+ {
+ ind.HistoricalData.AddBar(now.AddMinutes(i), 100, 105, 95, 100);
+ ind.ProcessUpdate(new UpdateArgs(i == 0 ? UpdateReason.HistoricalBar : UpdateReason.NewBar));
+ }
+
+ // After warmup, SMA should be exactly 100 (constant close)
+ double middle = ind.LinesSeries[0].GetValue(0);
+ Assert.Equal(100.0, middle, 1e-10);
+ }
+}
diff --git a/lib/channels/starchannel/Starchannel.Quantower.cs b/lib/channels/starchannel/Starchannel.Quantower.cs
new file mode 100644
index 00000000..d5a06ef9
--- /dev/null
+++ b/lib/channels/starchannel/Starchannel.Quantower.cs
@@ -0,0 +1,73 @@
+using System.Drawing;
+using TradingPlatform.BusinessLayer;
+using static QuanTAlib.IndicatorExtensions;
+
+namespace QuanTAlib;
+
+///
+/// Starchannel: Stoller Average Range Channel - Quantower Indicator Adapter
+/// A volatility-based envelope using SMA as the middle line and ATR for band width.
+/// Middle = SMA(close, period)
+/// Upper = Middle + (multiplier × ATR)
+/// Lower = Middle - (multiplier × ATR)
+/// ATR uses RMA (Wilder's smoothing) with warmup compensation.
+///
+public sealed class StarchannelIndicator : Indicator, IWatchlistIndicator
+{
+ [InputParameter("Period", sortIndex: 10, minimum: 1, maximum: 500, increment: 1, decimalPlaces: 0)]
+ public int Period { get; set; } = 20;
+
+ [InputParameter("Multiplier", sortIndex: 20, minimum: 0.1, maximum: 10.0, increment: 0.1, decimalPlaces: 1)]
+ public double Multiplier { get; set; } = 2.0;
+
+ [InputParameter("Show Cold Values", sortIndex: 100)]
+ public bool ShowColdValues { get; set; } = true;
+
+ private Starchannel? _indicator;
+
+ public int MinHistoryDepths => Period;
+ public override string ShortName => $"Starchannel({Period},{Multiplier})";
+
+ public StarchannelIndicator()
+ {
+ Name = "Starchannel - Stoller Average Range Channel";
+ Description = "SMA-based channel with ATR-derived band width";
+ SeparateWindow = false;
+ OnBackGround = true;
+ }
+
+ protected override void OnInit()
+ {
+ _indicator = new Starchannel(Period, Multiplier);
+
+ AddLineSeries(new LineSeries("Middle", Color.DodgerBlue, 2, LineStyle.Solid));
+ AddLineSeries(new LineSeries("Upper", Color.FromArgb(255, 180, 180), 1, LineStyle.Dash));
+ AddLineSeries(new LineSeries("Lower", Color.FromArgb(180, 180, 255), 1, LineStyle.Dash));
+ }
+
+ protected override void OnUpdate(UpdateArgs args)
+ {
+ if (_indicator is null)
+ return;
+
+ var item = HistoricalData[0, SeekOriginHistory.End];
+ bool isNew = args.IsNewBar();
+
+ TBar input = new(
+ time: item.TimeLeft,
+ open: item[PriceType.Open],
+ high: item[PriceType.High],
+ low: item[PriceType.Low],
+ close: item[PriceType.Close],
+ volume: item[PriceType.Volume]
+ );
+
+ _indicator.Update(input, isNew);
+
+ bool isHot = _indicator.IsHot;
+
+ LinesSeries[0].SetValue(_indicator.Last.Value, isHot, ShowColdValues);
+ LinesSeries[1].SetValue(_indicator.Upper.Value, isHot, ShowColdValues);
+ LinesSeries[2].SetValue(_indicator.Lower.Value, isHot, ShowColdValues);
+ }
+}
diff --git a/lib/channels/starchannel/Starchannel.Tests.cs b/lib/channels/starchannel/Starchannel.Tests.cs
new file mode 100644
index 00000000..a4ec4cd2
--- /dev/null
+++ b/lib/channels/starchannel/Starchannel.Tests.cs
@@ -0,0 +1,487 @@
+using System;
+using QuanTAlib;
+using Xunit;
+
+namespace QuanTAlib.Tests;
+
+public class StarchannelTests
+{
+ [Fact]
+ public void Starchannel_Constructor_ValidatesInput()
+ {
+ Assert.Throws(() => new Starchannel(0));
+ Assert.Throws(() => new Starchannel(-5));
+ Assert.Throws(() => new Starchannel(10, 0.0));
+ Assert.Throws(() => new Starchannel(10, -1.0));
+
+ var s = new Starchannel(10, 2.0);
+ Assert.Equal(10, s.WarmupPeriod); // period (SMA warmup)
+ Assert.Contains("Starchannel", s.Name, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void Starchannel_InitialState_Defaults()
+ {
+ var s = new Starchannel(5);
+
+ Assert.Equal(0, s.Last.Value);
+ Assert.Equal(0, s.Upper.Value);
+ Assert.Equal(0, s.Lower.Value);
+ Assert.False(s.IsHot);
+ }
+
+ [Fact]
+ public void Starchannel_FirstBar_AllBandsEqualClose()
+ {
+ var s = new Starchannel(10, 2.0);
+
+ var result = s.Update(new TBar(DateTime.UtcNow, 100, 105, 95, 102, 1000));
+
+ // First bar: SMA = close, ATR = 0, so all bands = close
+ Assert.Equal(102.0, result.Value, 1e-10);
+ Assert.Equal(102.0, s.Upper.Value, 1e-10);
+ Assert.Equal(102.0, s.Lower.Value, 1e-10);
+ }
+
+ [Fact]
+ public void Starchannel_SecondBar_BandsExpand()
+ {
+ var s = new Starchannel(10, 2.0);
+
+ s.Update(new TBar(DateTime.UtcNow, 100, 105, 95, 100, 1000));
+
+ // Second bar with volatility
+ _ = s.Update(new TBar(DateTime.UtcNow, 102, 110, 92, 102, 1000));
+
+ // SMA shifts toward 101, ATR > 0, bands expand
+ Assert.True(s.Upper.Value > s.Last.Value, "Upper should be above middle");
+ Assert.True(s.Lower.Value < s.Last.Value, "Lower should be below middle");
+ }
+
+ [Fact]
+ public void Starchannel_BandWidth_ProportionalToATR()
+ {
+ var s1 = new Starchannel(10, 1.0);
+ var s2 = new Starchannel(10, 2.0);
+ var s3 = new Starchannel(10, 3.0);
+
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.2, seed: 42);
+
+ for (int i = 0; i < 50; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ s1.Update(bar);
+ s2.Update(bar);
+ s3.Update(bar);
+ }
+
+ double width1 = s1.Upper.Value - s1.Lower.Value;
+ double width2 = s2.Upper.Value - s2.Lower.Value;
+ double width3 = s3.Upper.Value - s3.Lower.Value;
+
+ // Width should scale linearly with multiplier
+ Assert.Equal(width2, width1 * 2, 1e-9);
+ Assert.Equal(width3, width1 * 3, 1e-9);
+ }
+
+ [Fact]
+ public void Starchannel_BandOrder_Correct()
+ {
+ var s = new Starchannel(10, 2.0);
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.15, seed: 42);
+
+ for (int i = 0; i < 50; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ s.Update(bar);
+
+ // After first bar, upper > middle > lower
+ if (i > 0)
+ {
+ Assert.True(s.Upper.Value > s.Last.Value, $"Upper > Middle at bar {i}");
+ Assert.True(s.Lower.Value < s.Last.Value, $"Lower < Middle at bar {i}");
+ }
+ }
+ }
+
+ [Fact]
+ public void Starchannel_MiddleIsSMA()
+ {
+ var s = new Starchannel(10, 2.0);
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.1, seed: 42);
+
+ for (int i = 0; i < 50; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ var result = s.Update(bar);
+
+ // Middle is SMA (returned value)
+ Assert.Equal(result.Value, s.Last.Value, 1e-10);
+ }
+ }
+
+ [Fact]
+ public void Starchannel_BandSymmetry()
+ {
+ var s = new Starchannel(10, 2.0);
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.1, seed: 42);
+
+ for (int i = 0; i < 50; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ s.Update(bar);
+
+ // Bands should be symmetric around middle
+ double upperDist = s.Upper.Value - s.Last.Value;
+ double lowerDist = s.Last.Value - s.Lower.Value;
+ Assert.Equal(upperDist, lowerDist, 1e-10);
+ }
+ }
+
+ [Fact]
+ public void Starchannel_IsHot_TurnsTrueAfterWarmup()
+ {
+ var s = new Starchannel(5);
+ // WarmupPeriod = 5 (SMA period)
+
+ for (int i = 0; i < 4; i++)
+ {
+ s.Update(new TBar(DateTime.UtcNow, 100 + i, 101 + i, 99 + i, 100 + i, 1000));
+ Assert.False(s.IsHot);
+ }
+
+ s.Update(new TBar(DateTime.UtcNow, 200, 201, 199, 200, 1000));
+ Assert.True(s.IsHot);
+ }
+
+ [Fact]
+ public void Starchannel_IsNewFalse_RebuildsState()
+ {
+ var s = new Starchannel(10, 2.0);
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.1, seed: 7);
+
+ TBar remembered = default;
+ for (int i = 0; i < 30; i++)
+ {
+ remembered = gbm.Next(isNew: true);
+ s.Update(remembered, isNew: true);
+ }
+
+ double mid = s.Last.Value;
+ double up = s.Upper.Value;
+ double lo = s.Lower.Value;
+
+ // Apply corrections
+ for (int i = 0; i < 5; i++)
+ {
+ var corrected = gbm.Next(isNew: false);
+ s.Update(corrected, isNew: false);
+ }
+
+ // Restore with remembered bar
+ s.Update(remembered, isNew: false);
+
+ Assert.Equal(mid, s.Last.Value, 1e-10);
+ Assert.Equal(up, s.Upper.Value, 1e-10);
+ Assert.Equal(lo, s.Lower.Value, 1e-10);
+ }
+
+ [Fact]
+ public void Starchannel_NaN_UsesLastValid()
+ {
+ var s = new Starchannel(10, 2.0);
+
+ s.Update(new TBar(DateTime.UtcNow, 100, 110, 90, 105, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 101, 111, 91, 106, 1000));
+
+ var result = s.Update(new TBar(DateTime.UtcNow, 102, double.NaN, 92, 107, 1000));
+ Assert.True(double.IsFinite(result.Value));
+ Assert.True(double.IsFinite(s.Upper.Value));
+ Assert.True(double.IsFinite(s.Lower.Value));
+
+ var result2 = s.Update(new TBar(DateTime.UtcNow, 103, 113, double.PositiveInfinity, 108, 1000));
+ Assert.True(double.IsFinite(result2.Value));
+ }
+
+ [Fact]
+ public void Starchannel_Reset_Clears()
+ {
+ var s = new Starchannel(10, 2.0);
+ s.Update(new TBar(DateTime.UtcNow, 100, 110, 90, 100, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 101, 111, 91, 101, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 102, 112, 92, 102, 1000));
+
+ s.Reset();
+
+ Assert.Equal(0, s.Last.Value);
+ Assert.Equal(0, s.Upper.Value);
+ Assert.Equal(0, s.Lower.Value);
+ Assert.False(s.IsHot);
+
+ s.Update(new TBar(DateTime.UtcNow, 50, 60, 40, 55, 1000));
+ Assert.NotEqual(0, s.Last.Value);
+ }
+
+ [Fact]
+ public void Starchannel_BatchVsStreaming_Match()
+ {
+ var sStream = new Starchannel(20, 1.5);
+ var gbm = new GBM(startPrice: 100, mu: 0.02, sigma: 0.15, seed: 42);
+ var series = new TBarSeries();
+
+ for (int i = 0; i < 200; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ series.Add(bar);
+ sStream.Update(bar, isNew: true);
+ }
+
+ double expectedMid = sStream.Last.Value;
+ double expectedUp = sStream.Upper.Value;
+ double expectedLo = sStream.Lower.Value;
+
+ var (midBatch, upBatch, loBatch) = Starchannel.Batch(series, 20, 1.5);
+
+ Assert.Equal(expectedMid, midBatch.Last.Value, 1e-10);
+ Assert.Equal(expectedUp, upBatch.Last.Value, 1e-10);
+ Assert.Equal(expectedLo, loBatch.Last.Value, 1e-10);
+ }
+
+ [Fact]
+ public void Starchannel_SpanBatch_Validates()
+ {
+ double[] high = [110, 115, 120];
+ double[] low = [90, 95, 100];
+ double[] close = [100, 105, 110];
+ double[] middle = new double[3];
+ double[] upper = new double[3];
+ double[] lower = new double[3];
+
+ double[] highShort = [110, 115];
+ double[] smallOut = new double[1];
+
+ Assert.Throws(() => Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(), middle.AsSpan(), upper.AsSpan(), lower.AsSpan(), 0));
+ Assert.Throws(() => Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(), middle.AsSpan(), upper.AsSpan(), lower.AsSpan(), -1));
+ Assert.Throws(() => Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(), middle.AsSpan(), upper.AsSpan(), lower.AsSpan(), 10, 0.0));
+ Assert.Throws(() => Starchannel.Batch(highShort.AsSpan(), low.AsSpan(), close.AsSpan(), middle.AsSpan(), upper.AsSpan(), lower.AsSpan(), 2));
+ Assert.Throws(() => Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(), smallOut.AsSpan(), upper.AsSpan(), lower.AsSpan(), 2));
+ }
+
+ [Fact]
+ public void Starchannel_SpanBatch_ComputesCorrectly()
+ {
+ double[] high = [105, 110, 115, 112, 118];
+ double[] low = [95, 100, 105, 102, 108];
+ double[] close = [100, 105, 110, 107, 115];
+ double[] middle = new double[5];
+ double[] upper = new double[5];
+ double[] lower = new double[5];
+
+ Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(), middle.AsSpan(), upper.AsSpan(), lower.AsSpan(), 3);
+
+ // First bar: all equal close
+ Assert.Equal(100.0, middle[0], 1e-10);
+ Assert.Equal(100.0, upper[0], 1e-10);
+ Assert.Equal(100.0, lower[0], 1e-10);
+
+ // Subsequent bars: upper > middle > lower
+ for (int i = 1; i < 5; i++)
+ {
+ Assert.True(upper[i] > middle[i], $"Upper > Middle at {i}");
+ Assert.True(lower[i] < middle[i], $"Lower < Middle at {i}");
+ }
+ }
+
+ [Fact]
+ public void Starchannel_Calculate_ReturnsIndicatorAndResults()
+ {
+ var series = new TBarSeries();
+ series.Add(DateTime.UtcNow, 100, 110, 90, 100, 1000);
+ series.Add(DateTime.UtcNow, 105, 115, 95, 105, 1000);
+ series.Add(DateTime.UtcNow, 102, 112, 92, 102, 1000);
+
+ var ((mid, up, lo), ind) = Starchannel.Calculate(series, 2);
+
+ Assert.True(double.IsFinite(mid.Last.Value));
+ Assert.True(double.IsFinite(up.Last.Value));
+ Assert.True(double.IsFinite(lo.Last.Value));
+
+ // Continue streaming
+ ind.Update(new TBar(DateTime.UtcNow, 108, 118, 98, 108, 1000));
+ Assert.True(double.IsFinite(ind.Last.Value));
+ Assert.True(double.IsFinite(ind.Upper.Value));
+ Assert.True(double.IsFinite(ind.Lower.Value));
+ }
+
+ [Fact]
+ public void Starchannel_Event_Publishes()
+ {
+ var src = new TBarSeries();
+ var s = new Starchannel(src, 2);
+ bool fired = false;
+ s.Pub += (object? sender, in TValueEventArgs args) => fired = true;
+
+ src.Add(new TBar(DateTime.UtcNow, 100, 110, 90, 100, 1000));
+ Assert.True(fired);
+ }
+
+ [Fact]
+ public void Starchannel_HighVolatility_WiderBands()
+ {
+ var sLow = new Starchannel(20, 2.0);
+ var sHigh = new Starchannel(20, 2.0);
+
+ // Low volatility data
+ for (int i = 0; i < 50; i++)
+ {
+ sLow.Update(new TBar(DateTime.UtcNow, 100, 101, 99, 100, 1000));
+ }
+
+ // High volatility data
+ for (int i = 0; i < 50; i++)
+ {
+ sHigh.Update(new TBar(DateTime.UtcNow, 100, 120, 80, 100, 1000));
+ }
+
+ double lowWidth = sLow.Upper.Value - sLow.Lower.Value;
+ double highWidth = sHigh.Upper.Value - sHigh.Lower.Value;
+
+ Assert.True(highWidth > lowWidth, "Higher volatility should produce wider bands");
+ }
+
+ [Fact]
+ public void Starchannel_ShorterPeriod_FasterResponse()
+ {
+ var sShort = new Starchannel(5, 2.0);
+ var sLong = new Starchannel(20, 2.0);
+
+ // Initial stable period
+ for (int i = 0; i < 30; i++)
+ {
+ var bar = new TBar(DateTime.UtcNow, 100, 102, 98, 100, 1000);
+ sShort.Update(bar);
+ sLong.Update(bar);
+ }
+
+ double shortInitial = sShort.Last.Value;
+ double longInitial = sLong.Last.Value;
+
+ // Sudden price jump
+ for (int i = 0; i < 5; i++)
+ {
+ var bar = new TBar(DateTime.UtcNow, 150, 152, 148, 150, 1000);
+ sShort.Update(bar);
+ sLong.Update(bar);
+ }
+
+ double shortMove = sShort.Last.Value - shortInitial;
+ double longMove = sLong.Last.Value - longInitial;
+
+ // Shorter period should respond faster
+ Assert.True(shortMove > longMove, "Shorter period SMA should respond faster to price changes");
+ }
+
+ [Fact]
+ public void Starchannel_TrueRange_IncludesGaps()
+ {
+ var s = new Starchannel(3, 2.0);
+
+ // Bar 1: normal range
+ s.Update(new TBar(DateTime.UtcNow, 100, 105, 95, 100, 1000));
+
+ // Bar 2: gap up (close was 100, now low is 110)
+ // True range should include the gap: high - prevClose or high - low
+ s.Update(new TBar(DateTime.UtcNow, 115, 120, 110, 115, 1000));
+
+ // ATR should reflect the gap
+ double width = s.Upper.Value - s.Lower.Value;
+ Assert.True(width > 0, "Band width should be positive after gap");
+
+ // Bar 3: another check
+ s.Update(new TBar(DateTime.UtcNow, 118, 122, 114, 118, 1000));
+ Assert.True(double.IsFinite(s.Upper.Value));
+ Assert.True(double.IsFinite(s.Lower.Value));
+ }
+
+ [Fact]
+ public void Starchannel_WarmupCompensation_ReducesStartupBias()
+ {
+ // Warmup compensation should make early values more accurate
+ var s = new Starchannel(20, 2.0);
+
+ // Create bars with consistent volatility
+ for (int i = 0; i < 100; i++)
+ {
+ s.Update(new TBar(DateTime.UtcNow, 100, 110, 90, 100, 1000));
+ }
+
+ // Middle should converge to close (100) as SMA stabilizes
+ Assert.InRange(s.Last.Value, 99.5, 100.5);
+
+ // Band width should stabilize (ATR converges to true range = 20)
+ // Width = Upper - Lower = (SMA + mult*ATR) - (SMA - mult*ATR) = 2 * mult * ATR
+ double expectedWidth = 2.0 * 2.0 * 20.0; // 2 * multiplier * ATR = 80
+ double actualWidth = s.Upper.Value - s.Lower.Value;
+ Assert.InRange(actualWidth, expectedWidth * 0.9, expectedWidth * 1.1);
+ }
+
+ [Fact]
+ public void Starchannel_LongSeriesStability()
+ {
+ var s = new Starchannel(20, 2.0);
+ var gbm = new GBM(startPrice: 100, mu: 0.001, sigma: 0.02, seed: 123);
+
+ for (int i = 0; i < 10000; i++)
+ {
+ var bar = gbm.Next(isNew: true);
+ s.Update(bar);
+
+ Assert.True(double.IsFinite(s.Last.Value), $"Middle finite at {i}");
+ Assert.True(double.IsFinite(s.Upper.Value), $"Upper finite at {i}");
+ Assert.True(double.IsFinite(s.Lower.Value), $"Lower finite at {i}");
+
+ if (i > 0)
+ {
+ Assert.True(s.Upper.Value > s.Last.Value, $"Upper > Middle at {i}");
+ Assert.True(s.Lower.Value < s.Last.Value, $"Lower < Middle at {i}");
+ }
+ }
+ }
+
+ [Fact]
+ public void Starchannel_SMA_ConvergesToMean()
+ {
+ // SMA should converge to the mean price unlike EMA which weights recent more
+ var s = new Starchannel(10, 2.0);
+
+ // Feed constant price
+ for (int i = 0; i < 20; i++)
+ {
+ s.Update(new TBar(DateTime.UtcNow, 100, 105, 95, 100, 1000));
+ }
+
+ // SMA should be exactly 100 after enough bars
+ Assert.Equal(100.0, s.Last.Value, 1e-10);
+ }
+
+ [Fact]
+ public void Starchannel_SMA_EquallyWeightsWindow()
+ {
+ // SMA equally weights all bars in window, unlike EMA
+ var s = new Starchannel(5, 2.0);
+
+ // Feed prices 100, 110, 120, 130, 140 (mean = 120)
+ s.Update(new TBar(DateTime.UtcNow, 100, 105, 95, 100, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 110, 115, 105, 110, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 120, 125, 115, 120, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 130, 135, 125, 130, 1000));
+ s.Update(new TBar(DateTime.UtcNow, 140, 145, 135, 140, 1000));
+
+ // SMA(5) = (100+110+120+130+140)/5 = 120
+ Assert.Equal(120.0, s.Last.Value, 1e-10);
+
+ // Add one more: window shifts to 110,120,130,140,150 -> mean = 130
+ s.Update(new TBar(DateTime.UtcNow, 150, 155, 145, 150, 1000));
+ Assert.Equal(130.0, s.Last.Value, 1e-10);
+ }
+}
diff --git a/lib/channels/starchannel/Starchannel.Validation.Tests.cs b/lib/channels/starchannel/Starchannel.Validation.Tests.cs
new file mode 100644
index 00000000..2e1a9d41
--- /dev/null
+++ b/lib/channels/starchannel/Starchannel.Validation.Tests.cs
@@ -0,0 +1,570 @@
+using Xunit.Abstractions;
+
+namespace QuanTAlib.Tests;
+
+public sealed class StarchannelValidationTests : IDisposable
+{
+ private readonly ValidationTestData _testData;
+ private readonly ITestOutputHelper _output;
+ private bool _disposed;
+
+ public StarchannelValidationTests(ITestOutputHelper output)
+ {
+ _output = output;
+ _testData = new ValidationTestData();
+ }
+
+ public void Dispose() => Dispose(true);
+
+ private void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+
+ if (disposing)
+ {
+ _testData?.Dispose();
+ }
+ }
+
+ [Fact]
+ public void Validate_ManualCalculation_FirstBars()
+ {
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ // Create simple test data
+ // Bar 0: close=100, high=105, low=95 (range=10)
+ series.Add(new TBar(t0, 100, 105, 95, 100, 100));
+ // Bar 1: close=102, high=108, low=98 (range=10, prevClose=100, TR=max(10,8,2)=10)
+ series.Add(new TBar(t0.AddMinutes(1), 102, 108, 98, 102, 100));
+ // Bar 2: close=105, high=112, low=100 (range=12, prevClose=102, TR=max(12,10,2)=12)
+ series.Add(new TBar(t0.AddMinutes(2), 105, 112, 100, 105, 100));
+
+ var ind = new Starchannel(10, 2.0);
+ var (mid, up, lo) = ind.Update(series);
+
+ // First bar: all equal close
+ Assert.Equal(100.0, mid[0].Value, 1e-10);
+ Assert.Equal(100.0, up[0].Value, 1e-10);
+ Assert.Equal(100.0, lo[0].Value, 1e-10);
+
+ // Subsequent bars: upper > middle > lower (bands expand)
+ for (int i = 1; i < mid.Count; i++)
+ {
+ Assert.True(up[i].Value > mid[i].Value, $"Upper > Middle at {i}");
+ Assert.True(lo[i].Value < mid[i].Value, $"Lower < Middle at {i}");
+ }
+
+ // Bands should be symmetric
+ for (int i = 0; i < mid.Count; i++)
+ {
+ double upperDist = up[i].Value - mid[i].Value;
+ double lowerDist = mid[i].Value - lo[i].Value;
+ Assert.Equal(upperDist, lowerDist, 1e-10);
+ }
+
+ _output.WriteLine("Starchannel manual calculation validated");
+ }
+
+ [Fact]
+ public void Validate_AllModes_Consistency()
+ {
+ int[] periods = { 5, 10, 20, 50 };
+ double[] multipliers = { 1.0, 2.0, 2.5 };
+
+ foreach (int period in periods)
+ {
+ foreach (double multiplier in multipliers)
+ {
+ // Batch (instance)
+ var inst = new Starchannel(period, multiplier);
+ var (bMid, bUp, bLo) = inst.Update(_testData.Bars);
+
+ // Static batch
+ var (sMid, sUp, sLo) = Starchannel.Batch(_testData.Bars, period, multiplier);
+
+ ValidationHelper.VerifySeriesEqual(bMid, sMid);
+ ValidationHelper.VerifySeriesEqual(bUp, sUp);
+ ValidationHelper.VerifySeriesEqual(bLo, sLo);
+
+ // Streaming
+ var streaming = new Starchannel(period, multiplier);
+ var sMidStream = new TSeries();
+ var sUpStream = new TSeries();
+ var sLoStream = new TSeries();
+ foreach (var bar in _testData.Bars)
+ {
+ streaming.Update(bar);
+ sMidStream.Add(streaming.Last);
+ sUpStream.Add(streaming.Upper);
+ sLoStream.Add(streaming.Lower);
+ }
+
+ ValidationHelper.VerifySeriesEqual(sMid, sMidStream);
+ ValidationHelper.VerifySeriesEqual(sUp, sUpStream);
+ ValidationHelper.VerifySeriesEqual(sLo, sLoStream);
+
+ // Span
+ double[] high = _testData.HighPrices.ToArray();
+ double[] low = _testData.LowPrices.ToArray();
+ double[] close = _testData.ClosePrices.ToArray();
+ double[] spanMid = new double[high.Length];
+ double[] spanUp = new double[high.Length];
+ double[] spanLo = new double[high.Length];
+ Starchannel.Batch(high.AsSpan(), low.AsSpan(), close.AsSpan(),
+ spanMid.AsSpan(), spanUp.AsSpan(), spanLo.AsSpan(), period, multiplier);
+
+ for (int i = 0; i < high.Length; i++)
+ {
+ Assert.Equal(sMid[i].Value, spanMid[i], 9);
+ Assert.Equal(sUp[i].Value, spanUp[i], 9);
+ Assert.Equal(sLo[i].Value, spanLo[i], 9);
+ }
+ }
+ }
+
+ _output.WriteLine("Starchannel mode consistency validated (batch/stream/span)");
+ }
+
+ [Fact]
+ public void Validate_EventingMode_MatchesBatch()
+ {
+ const int period = 20;
+ const double multiplier = 2.0;
+
+ var pub = new TBarSeries();
+ var evtInd = new Starchannel(pub, period, multiplier);
+ var evtMid = new TSeries();
+ var evtUp = new TSeries();
+ var evtLo = new TSeries();
+
+ foreach (var bar in _testData.Bars)
+ {
+ pub.Add(bar);
+ evtMid.Add(evtInd.Last);
+ evtUp.Add(evtInd.Upper);
+ evtLo.Add(evtInd.Lower);
+ }
+
+ var (bMid, bUp, bLo) = Starchannel.Batch(_testData.Bars, period, multiplier);
+
+ ValidationHelper.VerifySeriesEqual(bMid, evtMid);
+ ValidationHelper.VerifySeriesEqual(bUp, evtUp);
+ ValidationHelper.VerifySeriesEqual(bLo, evtLo);
+
+ _output.WriteLine("Starchannel eventing mode validated");
+ }
+
+ [Fact]
+ public void Validate_Calculate_ReturnsHotIndicator()
+ {
+ const int period = 15;
+ const double multiplier = 2.5;
+
+ var ((mid, up, lo), ind) = Starchannel.Calculate(_testData.Bars, period, multiplier);
+
+ Assert.True(ind.IsHot);
+ Assert.Equal(period, ind.WarmupPeriod);
+ Assert.Equal(mid.Last.Value, ind.Last.Value, 1e-10);
+ Assert.Equal(up.Last.Value, ind.Upper.Value, 1e-10);
+ Assert.Equal(lo.Last.Value, ind.Lower.Value, 1e-10);
+
+ // Continue streaming
+ var next = new TBar(DateTime.UtcNow, 100, 110, 90, 100, 1000);
+ ind.Update(next);
+ Assert.True(ind.IsHot);
+
+ _output.WriteLine("Starchannel Calculate validated");
+ }
+
+ [Fact]
+ public void Validate_Prime_MatchesBatch()
+ {
+ const int period = 25;
+ const double multiplier = 1.5;
+
+ var (bMid, bUp, bLo) = Starchannel.Batch(_testData.Bars, period, multiplier);
+
+ var primed = new Starchannel(period, multiplier);
+ var subset = new TBarSeries();
+ for (int i = 0; i < 200; i++)
+ {
+ subset.Add(_testData.Bars[i]);
+ }
+
+ primed.Prime(subset);
+
+ for (int i = 200; i < _testData.Bars.Count; i++)
+ {
+ primed.Update(_testData.Bars[i]);
+ }
+
+ Assert.Equal(bMid.Last.Value, primed.Last.Value, 1e-9);
+ Assert.Equal(bUp.Last.Value, primed.Upper.Value, 1e-9);
+ Assert.Equal(bLo.Last.Value, primed.Lower.Value, 1e-9);
+
+ _output.WriteLine("Starchannel Prime validated against batch");
+ }
+
+ [Fact]
+ public void Validate_LargeDataset_FiniteOutputs()
+ {
+ var (mid, up, lo) = Starchannel.Batch(_testData.Bars, 50, 2.0);
+
+ ValidationHelper.VerifyAllFinite(mid, startIndex: 0);
+ ValidationHelper.VerifyAllFinite(up, startIndex: 0);
+ ValidationHelper.VerifyAllFinite(lo, startIndex: 0);
+
+ // After first bar, upper > lower
+ for (int i = 1; i < mid.Count; i++)
+ {
+ Assert.True(up[i].Value > lo[i].Value, $"Upper > Lower at {i}");
+ }
+
+ _output.WriteLine("Starchannel large dataset validated");
+ }
+
+ [Fact]
+ public void Validate_BandSymmetry_AllBars()
+ {
+ var ind = new Starchannel(20, 2.0);
+ var (mid, up, lo) = ind.Update(_testData.Bars);
+
+ for (int i = 0; i < mid.Count; i++)
+ {
+ double upperWidth = up[i].Value - mid[i].Value;
+ double lowerWidth = mid[i].Value - lo[i].Value;
+ Assert.Equal(upperWidth, lowerWidth, 1e-10);
+ }
+
+ _output.WriteLine("Starchannel band symmetry validated for all bars");
+ }
+
+ [Fact]
+ public void Validate_MultiplierScaling()
+ {
+ double[] multipliers = { 1.0, 2.0, 3.0, 4.0 };
+ double[] widths = new double[multipliers.Length];
+
+ for (int i = 0; i < multipliers.Length; i++)
+ {
+ var ind = new Starchannel(20, multipliers[i]);
+ foreach (var bar in _testData.Bars)
+ {
+ ind.Update(bar);
+ }
+ widths[i] = ind.Upper.Value - ind.Lower.Value;
+ }
+
+ // Widths should scale linearly with multiplier
+ double baseWidth = widths[0];
+ for (int i = 1; i < multipliers.Length; i++)
+ {
+ double expected = baseWidth * multipliers[i];
+ Assert.Equal(expected, widths[i], 1e-9);
+ }
+
+ _output.WriteLine("Starchannel multiplier scaling validated");
+ }
+
+ [Fact]
+ public void Validate_PeriodEffect_Smoothing()
+ {
+ int[] periods = { 5, 10, 20, 50 };
+ double[] middles = new double[periods.Length];
+
+ for (int i = 0; i < periods.Length; i++)
+ {
+ var ind = new Starchannel(periods[i], 2.0);
+ foreach (var bar in _testData.Bars)
+ {
+ ind.Update(bar);
+ }
+ middles[i] = ind.Last.Value;
+ }
+
+ // All should produce finite values
+ foreach (var m in middles)
+ {
+ Assert.True(double.IsFinite(m));
+ }
+
+ _output.WriteLine("Starchannel period effect validated");
+ }
+
+ [Fact]
+ public void Validate_ATRComponent_TrueRange()
+ {
+ // Create data with gaps to verify True Range includes gaps
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ // Bar 0: normal
+ series.Add(new TBar(t0, 100, 105, 95, 100, 100));
+ // Bar 1: gap up (prev close=100, new low=110, gap=10)
+ series.Add(new TBar(t0.AddMinutes(1), 115, 120, 110, 115, 100));
+ // Bar 2: gap down (prev close=115, new high=100)
+ series.Add(new TBar(t0.AddMinutes(2), 95, 100, 90, 95, 100));
+
+ var ind = new Starchannel(3, 2.0);
+ var (mid, up, lo) = ind.Update(series);
+
+ // Bands should expand due to gaps
+ for (int i = 1; i < mid.Count; i++)
+ {
+ double width = up[i].Value - lo[i].Value;
+ Assert.True(width > 0, $"Band width > 0 at bar {i}");
+ }
+
+ _output.WriteLine("Starchannel ATR true range validated with gaps");
+ }
+
+ [Fact]
+ public void Validate_WarmupCompensation_EarlyConvergence()
+ {
+ // Constant price data - SMA should converge quickly
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ for (int i = 0; i < 100; i++)
+ {
+ series.Add(new TBar(t0.AddMinutes(i), 100, 105, 95, 100, 100));
+ }
+
+ var ind = new Starchannel(20, 2.0);
+ var (mid, _, _) = ind.Update(series);
+
+ // After warmup, middle should be very close to constant price (SMA = 100 exactly)
+ for (int i = 20; i < 100; i++)
+ {
+ Assert.Equal(100.0, mid[i].Value, 1e-10);
+ }
+
+ _output.WriteLine("Starchannel warmup compensation validated");
+ }
+
+ [Fact]
+ public void Validate_StateRestoration_Iterative()
+ {
+ var ind = new Starchannel(15, 2.5);
+ var gbm = new GBM(startPrice: 100, mu: 0.01, sigma: 0.1, seed: 42);
+
+ // Build up state
+ for (int i = 0; i < 50; i++)
+ {
+ ind.Update(gbm.Next(isNew: true), isNew: true);
+ }
+
+ // Multiple corrections
+ var remembered = gbm.Next(isNew: true);
+ ind.Update(remembered, isNew: true);
+
+ for (int i = 0; i < 10; i++)
+ {
+ var corrected = gbm.Next(isNew: false);
+ ind.Update(corrected, isNew: false);
+ }
+
+ // Restore
+ ind.Update(remembered, isNew: false);
+
+ // State should be back to remembered point (after remembered bar)
+ Assert.True(double.IsFinite(ind.Last.Value));
+ Assert.True(double.IsFinite(ind.Upper.Value));
+ Assert.True(double.IsFinite(ind.Lower.Value));
+
+ _output.WriteLine("Starchannel state restoration validated");
+ }
+
+ [Fact]
+ public void Validate_SMA_VersusPineScript()
+ {
+ // PineScript: ta.sma(close, period)
+ // Verify SMA calculation matches expected behavior
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ // Create predictable data: 100, 102, 104, 106, 108
+ for (int i = 0; i < 5; i++)
+ {
+ double close = 100 + i * 2;
+ series.Add(new TBar(t0.AddMinutes(i), close, close + 5, close - 5, close, 100));
+ }
+
+ var ind = new Starchannel(5, 2.0);
+ var (mid, _, _) = ind.Update(series);
+
+ // SMA(5) at bar 4 = (100+102+104+106+108)/5 = 104
+ Assert.Equal(104.0, mid[4].Value, 1e-10);
+
+ _output.WriteLine("Starchannel SMA calculation validated against expected");
+ }
+
+ [Fact]
+ public void Validate_BandWidthConsistency()
+ {
+ // Verify that band width is consistent across different calculation modes
+ int[] periods = { 10, 20, 30 };
+
+ foreach (int period in periods)
+ {
+ var (mid, up, lo) = Starchannel.Batch(_testData.Bars, period, 2.0);
+
+ // Band width should be exactly 2x ATR (multiplier * ATR)
+ for (int i = 1; i < mid.Count; i++)
+ {
+ double width = up[i].Value - lo[i].Value;
+ double upperDist = up[i].Value - mid[i].Value;
+ double lowerDist = mid[i].Value - lo[i].Value;
+
+ // Width = 2 * ATR * multiplier, so upperDist = lowerDist = ATR * multiplier
+ Assert.Equal(upperDist, lowerDist, 1e-10);
+ Assert.Equal(width, upperDist + lowerDist, 1e-10);
+ }
+ }
+
+ _output.WriteLine("Starchannel band width consistency validated");
+ }
+
+ [Fact]
+ public void Validate_ATRCalculation_Correctness()
+ {
+ // Verify ATR calculation using known values
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ // Create bars with known true range values
+ // Bar 0: TR = high - low = 10 (no previous close)
+ series.Add(new TBar(t0, 100, 105, 95, 100, 100));
+ // Bar 1: TR = max(110-90, |110-100|, |90-100|) = max(20, 10, 10) = 20
+ series.Add(new TBar(t0.AddMinutes(1), 100, 110, 90, 100, 100));
+ // Bar 2: TR = max(105-95, |105-100|, |95-100|) = max(10, 5, 5) = 10
+ series.Add(new TBar(t0.AddMinutes(2), 100, 105, 95, 100, 100));
+
+ var ind = new Starchannel(3, 1.0); // multiplier=1 so width = 2*ATR
+ var (mid, up, lo) = ind.Update(series);
+
+ // All outputs should be finite
+ for (int i = 0; i < mid.Count; i++)
+ {
+ Assert.True(double.IsFinite(mid[i].Value));
+ Assert.True(double.IsFinite(up[i].Value));
+ Assert.True(double.IsFinite(lo[i].Value));
+ }
+
+ // Band width should be positive after first bar
+ for (int i = 1; i < mid.Count; i++)
+ {
+ double width = up[i].Value - lo[i].Value;
+ Assert.True(width > 0, $"Band width > 0 at bar {i}");
+ }
+
+ _output.WriteLine("Starchannel ATR calculation validated");
+ }
+
+ [Fact]
+ public void Validate_SMA_SlidingWindow()
+ {
+ // Verify SMA uses sliding window correctly
+ var series = new TBarSeries();
+ var t0 = DateTime.UtcNow;
+
+ // Create 10 bars with close = bar index + 1 (1,2,3,4,5,6,7,8,9,10)
+ for (int i = 0; i < 10; i++)
+ {
+ double close = i + 1;
+ series.Add(new TBar(t0.AddMinutes(i), close, close + 1, close - 1, close, 100));
+ }
+
+ var ind = new Starchannel(5, 2.0);
+ var (mid, _, _) = ind.Update(series);
+
+ // Bar 4: SMA(5) = (1+2+3+4+5)/5 = 3
+ Assert.Equal(3.0, mid[4].Value, 1e-10);
+
+ // Bar 5: SMA(5) = (2+3+4+5+6)/5 = 4
+ Assert.Equal(4.0, mid[5].Value, 1e-10);
+
+ // Bar 9: SMA(5) = (6+7+8+9+10)/5 = 8
+ Assert.Equal(8.0, mid[9].Value, 1e-10);
+
+ _output.WriteLine("Starchannel SMA sliding window validated");
+ }
+
+ [Fact]
+ public void Validate_KchannelComparison_Structure()
+ {
+ // Compare structural properties with Kchannel (EMA vs SMA middle)
+ // Both use ATR for bands, so band calculation should be similar
+
+ const int period = 20;
+ const double multiplier = 2.0;
+
+ var star = new Starchannel(period, multiplier);
+ var kelt = new Kchannel(period, multiplier);
+
+ foreach (var bar in _testData.Bars)
+ {
+ star.Update(bar);
+ kelt.Update(bar);
+ }
+
+ // Both should have finite outputs
+ Assert.True(double.IsFinite(star.Last.Value));
+ Assert.True(double.IsFinite(star.Upper.Value));
+ Assert.True(double.IsFinite(star.Lower.Value));
+
+ Assert.True(double.IsFinite(kelt.Last.Value));
+ Assert.True(double.IsFinite(kelt.Upper.Value));
+ Assert.True(double.IsFinite(kelt.Lower.Value));
+
+ // Both should have upper > middle > lower
+ Assert.True(star.Upper.Value > star.Last.Value);
+ Assert.True(star.Lower.Value < star.Last.Value);
+
+ Assert.True(kelt.Upper.Value > kelt.Last.Value);
+ Assert.True(kelt.Lower.Value < kelt.Last.Value);
+
+ // Both should have symmetric bands
+ double starUpperDist = star.Upper.Value - star.Last.Value;
+ double starLowerDist = star.Last.Value - star.Lower.Value;
+ Assert.Equal(starUpperDist, starLowerDist, 1e-10);
+
+ double keltUpperDist = kelt.Upper.Value - kelt.Last.Value;
+ double keltLowerDist = kelt.Last.Value - kelt.Lower.Value;
+ Assert.Equal(keltUpperDist, keltLowerDist, 1e-10);
+
+ _output.WriteLine("Starchannel vs Kchannel structure validated");
+ }
+
+ [Fact]
+ public void Validate_Starchannel_DifferentFromKchannel()
+ {
+ // Starchannel (SMA) should differ from Kchannel (EMA) in the middle line
+ const int period = 20;
+ const double multiplier = 2.0;
+
+ var star = new Starchannel(period, multiplier);
+ var kelt = new Kchannel(period, multiplier);
+
+ foreach (var bar in _testData.Bars)
+ {
+ star.Update(bar);
+ kelt.Update(bar);
+ }
+
+ // Middle lines should be different (SMA vs EMA with different weighting)
+ // They may be close but not identical
+ double diff = Math.Abs(star.Last.Value - kelt.Last.Value);
+
+ // Just verify they're both finite and reasonable
+ Assert.True(double.IsFinite(diff));
+
+ _output.WriteLine($"Starchannel vs Kchannel middle difference: {diff:F6}");
+ }
+}
diff --git a/lib/channels/starchannel/Starchannel.cs b/lib/channels/starchannel/Starchannel.cs
new file mode 100644
index 00000000..3d5e8a0f
--- /dev/null
+++ b/lib/channels/starchannel/Starchannel.cs
@@ -0,0 +1,360 @@
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace QuanTAlib;
+
+///
+/// STARCHANNEL: Stoller Average Range Channel
+/// A volatility-based envelope using SMA as the middle line and ATR for band width.
+/// Middle = SMA(source, period)
+/// Upper = Middle + (multiplier × ATR)
+/// Lower = Middle - (multiplier × ATR)
+/// ATR uses RMA (Wilder's smoothing) with warmup compensation.
+///
+[SkipLocalsInit]
+public sealed class Starchannel : ITValuePublisher
+{
+ private readonly int _period;
+ private readonly double _multiplier;
+ private readonly double _atrAlpha;
+ private readonly RingBuffer _smaBuffer;
+
+ [StructLayout(LayoutKind.Auto)]
+ private record struct State(
+ double RawRma,
+ double E,
+ double PrevClose,
+ double LastValidClose,
+ double LastValidHigh,
+ double LastValidLow,
+ int Bars,
+ bool IsHot);
+
+ private State _state;
+ private State _p_state;
+
+ private readonly TBarPublishedHandler _barHandler;
+
+ private const double Epsilon = 1e-10;
+
+ public string Name { get; }
+ public int WarmupPeriod { get; }
+ public TValue Last { get; private set; }
+ public TValue Upper { get; private set; }
+ public TValue Lower { get; private set; }
+ public bool IsHot => _state.IsHot;
+
+ public event TValuePublishedHandler? Pub;
+
+ public Starchannel(int period = 20, double multiplier = 2.0)
+ {
+ if (period < 1)
+ throw new ArgumentOutOfRangeException(nameof(period), "Period must be >= 1.");
+ if (multiplier <= 0.0)
+ throw new ArgumentOutOfRangeException(nameof(multiplier), "Multiplier must be > 0.");
+
+ _period = period;
+ _multiplier = multiplier;
+ _atrAlpha = 1.0 / period;
+ _smaBuffer = new RingBuffer(period);
+
+ WarmupPeriod = period;
+
+ Name = $"Starchannel({period},{multiplier})";
+ _barHandler = HandleBar;
+
+ Reset();
+ }
+
+ public Starchannel(TBarSeries source, int period = 20, double multiplier = 2.0) : this(period, multiplier)
+ {
+ 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 void Reset()
+ {
+ _smaBuffer.Clear();
+ _state = new State(0, 1.0, double.NaN, double.NaN, double.NaN, double.NaN, 0, false);
+ _p_state = _state;
+ Last = default;
+ Upper = default;
+ Lower = default;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private (double close, double high, double low) GetValid(double close, double high, double low)
+ {
+ if (double.IsFinite(close))
+ _state = _state with { LastValidClose = close };
+ else
+ close = _state.LastValidClose;
+
+ if (double.IsFinite(high))
+ _state = _state with { LastValidHigh = high };
+ else
+ high = _state.LastValidHigh;
+
+ if (double.IsFinite(low))
+ _state = _state with { LastValidLow = low };
+ else
+ low = _state.LastValidLow;
+
+ return (close, high, low);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public TValue Update(TBar input, bool isNew = true)
+ {
+ if (isNew)
+ {
+ _p_state = _state;
+ _smaBuffer.Snapshot();
+ }
+ else
+ {
+ _state = _p_state;
+ _smaBuffer.Restore();
+ }
+
+ var (close, high, low) = GetValid(input.Close, input.High, input.Low);
+
+ // Handle first bar
+ if (_state.Bars == 0)
+ {
+ _smaBuffer.Add(close);
+ _state = _state with
+ {
+ RawRma = 0.0,
+ E = 1.0,
+ PrevClose = close,
+ Bars = 1
+ };
+
+ double sma = close;
+ Last = new TValue(input.Time, sma);
+ Upper = new TValue(input.Time, sma);
+ Lower = new TValue(input.Time, sma);
+ PubEvent(Last, isNew);
+ return Last;
+ }
+
+ if (isNew)
+ _state = _state with { Bars = _state.Bars + 1 };
+
+ // SMA: use RingBuffer's running sum
+ _smaBuffer.Add(close);
+ double smaValue = _smaBuffer.Average;
+
+ // True Range
+ double prevClose = _state.PrevClose;
+ double tr1 = high - low;
+ double tr2 = Math.Abs(high - prevClose);
+ double tr3 = Math.Abs(low - prevClose);
+ double trueRange = Math.Max(tr1, Math.Max(tr2, tr3));
+
+ // ATR using RMA with warmup compensation
+ double newRawRma = (_state.RawRma * (_period - 1) + trueRange) / _period;
+ double newE = (1.0 - _atrAlpha) * _state.E;
+ double atrValue = newE > Epsilon ? newRawRma / (1.0 - newE) : newRawRma;
+
+ // Update state
+ _state = _state with
+ {
+ RawRma = newRawRma,
+ E = newE,
+ PrevClose = close
+ };
+
+ // Calculate bands
+ double width = _multiplier * atrValue;
+ double upper = smaValue + width;
+ double lower = smaValue - width;
+
+ if (!_state.IsHot && _state.Bars >= WarmupPeriod)
+ _state = _state with { IsHot = true };
+
+ Last = new TValue(input.Time, smaValue);
+ Upper = new TValue(input.Time, upper);
+ Lower = new TValue(input.Time, lower);
+
+ PubEvent(Last, isNew);
+ return Last;
+ }
+
+ public (TSeries Middle, TSeries Upper, TSeries Lower) Update(TBarSeries source)
+ {
+ if (source.Count == 0)
+ return (new TSeries([], []), new TSeries([], []), new TSeries([], []));
+
+ int len = source.Count;
+ var tMiddle = new List(len);
+ var vMiddle = new List(len);
+ var tUpper = new List(len);
+ var vUpper = new List(len);
+ var tLower = new List(len);
+ var vLower = new List(len);
+
+ CollectionsMarshal.SetCount(tMiddle, len);
+ CollectionsMarshal.SetCount(vMiddle, len);
+ CollectionsMarshal.SetCount(tUpper, len);
+ CollectionsMarshal.SetCount(vUpper, len);
+ CollectionsMarshal.SetCount(tLower, len);
+ CollectionsMarshal.SetCount(vLower, len);
+
+ var tSpan = CollectionsMarshal.AsSpan(tMiddle);
+ var vMiddleSpan = CollectionsMarshal.AsSpan(vMiddle);
+ var vUpperSpan = CollectionsMarshal.AsSpan(vUpper);
+ var vLowerSpan = CollectionsMarshal.AsSpan(vLower);
+
+ Batch(source.HighValues, source.LowValues, source.CloseValues,
+ vMiddleSpan, vUpperSpan, vLowerSpan, _period, _multiplier);
+
+ source.Times.CopyTo(tSpan);
+ tSpan.CopyTo(CollectionsMarshal.AsSpan(tUpper));
+ tSpan.CopyTo(CollectionsMarshal.AsSpan(tLower));
+
+ // Prime internal state for continued streaming
+ Prime(source);
+
+ var lastTime = new DateTime(source.Times[^1], DateTimeKind.Utc);
+ Last = new TValue(lastTime, vMiddleSpan[^1]);
+ Upper = new TValue(lastTime, vUpperSpan[^1]);
+ Lower = new TValue(lastTime, vLowerSpan[^1]);
+
+ return (new TSeries(tMiddle, vMiddle), new TSeries(tUpper, vUpper), new TSeries(tLower, vLower));
+ }
+
+ public void Prime(TBarSeries source)
+ {
+ Reset();
+
+ if (source.Count == 0)
+ return;
+
+ for (int i = 0; i < source.Count; i++)
+ {
+ Update(source[i], isNew: true);
+ }
+ }
+
+ ///
+ /// Batch calculation using spans (zero allocation).
+ ///
+ public static void Batch(
+ ReadOnlySpan high,
+ ReadOnlySpan low,
+ ReadOnlySpan close,
+ Span middle,
+ Span upper,
+ Span lower,
+ int period,
+ double multiplier = 2.0)
+ {
+ if (period < 1)
+ throw new ArgumentOutOfRangeException(nameof(period), "Period must be >= 1.");
+ if (multiplier <= 0.0)
+ throw new ArgumentOutOfRangeException(nameof(multiplier), "Multiplier must be > 0.");
+ if (high.Length != low.Length || high.Length != close.Length)
+ throw new ArgumentException("High, Low, and Close spans must have the same length", nameof(high));
+ if (middle.Length < high.Length || upper.Length < high.Length || lower.Length < high.Length)
+ throw new ArgumentException("Output spans must be at least as long as inputs", nameof(middle));
+
+ int len = high.Length;
+ if (len == 0) return;
+
+ double atrAlpha = 1.0 / period;
+
+ // SMA running sum
+ double smaSum = close[0];
+ double rawRma = 0.0;
+ double e = 1.0;
+ double prevClose = close[0];
+
+ // First bar
+ middle[0] = close[0];
+ upper[0] = close[0];
+ lower[0] = close[0];
+
+ for (int i = 1; i < len; i++)
+ {
+ double c = close[i];
+ double h = high[i];
+ double l = low[i];
+
+ // SMA: add current, subtract oldest if beyond window
+ if (i < period)
+ {
+ smaSum += c;
+ }
+ else
+ {
+ smaSum += c - close[i - period];
+ }
+ int count = Math.Min(i + 1, period);
+ double sma = smaSum / count;
+
+ // True Range
+ double tr1 = h - l;
+ double tr2 = Math.Abs(h - prevClose);
+ double tr3 = Math.Abs(l - prevClose);
+ double tr = Math.Max(tr1, Math.Max(tr2, tr3));
+
+ // ATR (RMA with warmup compensation)
+ rawRma = (rawRma * (period - 1) + tr) / period;
+ e = (1.0 - atrAlpha) * e;
+ double atr = e > Epsilon ? rawRma / (1.0 - e) : rawRma;
+
+ prevClose = c;
+
+ double width = multiplier * atr;
+ middle[i] = sma;
+ upper[i] = sma + width;
+ lower[i] = sma - width;
+ }
+ }
+
+ public static (TSeries Middle, TSeries Upper, TSeries Lower) Batch(TBarSeries source, int period = 20, double multiplier = 2.0)
+ {
+ int len = source.Count;
+ var tMiddle = new List(len);
+ var vMiddle = new List(len);
+ var tUpper = new List(len);
+ var vUpper = new List(len);
+ var tLower = new List(len);
+ var vLower = new List(len);
+
+ CollectionsMarshal.SetCount(tMiddle, len);
+ CollectionsMarshal.SetCount(vMiddle, len);
+ CollectionsMarshal.SetCount(tUpper, len);
+ CollectionsMarshal.SetCount(vUpper, len);
+ CollectionsMarshal.SetCount(tLower, len);
+ CollectionsMarshal.SetCount(vLower, len);
+
+ Batch(source.HighValues, source.LowValues, source.CloseValues,
+ CollectionsMarshal.AsSpan(vMiddle),
+ CollectionsMarshal.AsSpan(vUpper),
+ CollectionsMarshal.AsSpan(vLower),
+ period, multiplier);
+
+ source.Times.CopyTo(CollectionsMarshal.AsSpan(tMiddle));
+ CollectionsMarshal.AsSpan(tMiddle).CopyTo(CollectionsMarshal.AsSpan(tUpper));
+ CollectionsMarshal.AsSpan(tMiddle).CopyTo(CollectionsMarshal.AsSpan(tLower));
+
+ return (new TSeries(tMiddle, vMiddle), new TSeries(tUpper, vUpper), new TSeries(tLower, vLower));
+ }
+
+ public static ((TSeries Middle, TSeries Upper, TSeries Lower) Results, Starchannel Indicator) Calculate(TBarSeries source, int period = 20, double multiplier = 2.0)
+ {
+ var indicator = new Starchannel(source, period, multiplier);
+ var results = indicator.Update(source);
+ return (results, indicator);
+ }
+}