Stc opti (#15)

* Optimize STC

* Optimize STC

* Add SuperTrendCrossEma
This commit is contained in:
Oda
2025-03-01 02:59:19 +07:00
committed by GitHub
parent c715da8a17
commit e16f0a2e5d
13 changed files with 485 additions and 51 deletions

View File

@@ -7,8 +7,6 @@ namespace Managing.Domain.Scenarios;
public static class ScenarioHelpers
{
public static IEnumerable<IStrategy> GetStrategiesFromScenario(Scenario scenario)
{
var strategies = new List<IStrategy>();
@@ -45,6 +43,10 @@ public static class ScenarioHelpers
strategy.SmoothPeriods.Value),
StrategyType.Stc => new STCStrategy(strategy.Name, strategy.CyclePeriods.Value,
strategy.FastPeriods.Value, strategy.SlowPeriods.Value),
StrategyType.LaggingStc => new LaggingSTC(strategy.Name, strategy.CyclePeriods.Value,
strategy.FastPeriods.Value, strategy.SlowPeriods.Value),
StrategyType.SuperTrendCrossEma => new SuperTrendCrossEma(strategy.Name,
strategy.Period.Value, strategy.Multiplier.Value),
_ => throw new NotImplementedException(),
};
@@ -101,6 +103,7 @@ public static class ScenarioHelpers
case StrategyType.ThreeWhiteSoldiers:
break;
case StrategyType.SuperTrend:
case StrategyType.SuperTrendCrossEma:
case StrategyType.ChandelierExit:
if (!period.HasValue || !multiplier.HasValue)
{
@@ -132,6 +135,7 @@ public static class ScenarioHelpers
break;
case StrategyType.Stc:
case StrategyType.LaggingStc:
if (!fastPeriods.HasValue || !slowPeriods.HasValue || !cyclePeriods.HasValue)
{
throw new Exception(
@@ -168,6 +172,8 @@ public static class ScenarioHelpers
StrategyType.StochRsiTrend => SignalType.Trend,
StrategyType.Stc => SignalType.Signal,
StrategyType.StDev => SignalType.Context,
StrategyType.LaggingStc => SignalType.Signal,
StrategyType.SuperTrendCrossEma => SignalType.Signal,
_ => throw new NotImplementedException(),
};
}

View File

@@ -21,13 +21,27 @@ public static class TradingBox
if (signals == null || signals.Count == 0) continue;
var candleLoopback = limitedCandles.TakeLast(loopbackPeriod ?? 1).ToList();
// Ensure limitedCandles is ordered chronologically
var orderedCandles = limitedCandles.OrderBy(c => c.Date).ToList();
foreach (var signal in signals.Where(s => s.Date >= candleLoopback.FirstOrDefault()?.Date))
var loopback = loopbackPeriod ?? 1;
var candleLoopback = orderedCandles.TakeLast(loopback).ToList();
if (!candleLoopback.Any())
{
if (previousSignal.SingleOrDefault(s => s.Identifier == signal.Identifier) == null)
// Handle empty case (e.g., log warning, skip processing)
continue;
}
var loopbackStartDate = candleLoopback.First().Date;
foreach (var signal in signals.Where(s => s.Date >= loopbackStartDate))
{
var hasExistingSignal = previousSignal.Any(s => s.Identifier == signal.Identifier);
if (!hasExistingSignal)
{
if (previousSignal.Count == 0 || previousSignal.Last().Date < signal.Date)
bool shouldAdd = previousSignal.Count == 0 || previousSignal.Last().Date < signal.Date;
if (shouldAdd)
{
signalOnCandles.Add(signal);
}

View File

@@ -0,0 +1,144 @@
using Managing.Core;
using Managing.Domain.Candles;
using Managing.Domain.Shared.Rules;
using Managing.Domain.Strategies.Base;
using Skender.Stock.Indicators;
using static Managing.Common.Enums;
namespace Managing.Domain.Strategies;
///<summary>
/// Lagging STC Strategy: Combines Schaff Trend Cycle with volatility-based confirmation.
/// Key Features:
/// 1. Short signals on STC breakdown from overbught (75+ → ≤75) with recent compressed volatility (min >78)
/// 2. Long signals on STC rebound from oversold (25- → ≥25) with recent compressed volatility (max <11)
/// 3. Avoids look-ahead bias through proper rolling window implementation
/// </summary>
public class LaggingSTC : Strategy
{
public List<Signal> Signals { get; set; }
public LaggingSTC(string name, int cyclePeriods, int fastPeriods, int slowPeriods) : base(name,
StrategyType.LaggingStc)
{
Signals = new List<Signal>();
FastPeriods = fastPeriods;
SlowPeriods = slowPeriods;
CyclePeriods = cyclePeriods;
}
public override List<Signal> Run()
{
if (Candles.Count <= 2 * (SlowPeriods + CyclePeriods))
{
return null;
}
try
{
var stc = Candles.GetStc(FastPeriods.Value, FastPeriods.Value, SlowPeriods.Value).ToList();
var stcCandles = MapStcToCandle(stc, Candles.TakeLast(CyclePeriods.Value * 3));
if (stcCandles.Count == 0)
return null;
for (int i = 1; i < stcCandles.Count; i++)
{
var currentCandle = stcCandles[i];
var previousCandle = stcCandles[i - 1];
/* VOLATILITY CONFIRMATION WINDOW
* - 22-period rolling window (≈1 trading month)
* - Ends at previous candle to avoid inclusion of current break
* - Dynamic sizing for early dataset cases */
// Calculate the lookback window ending at previousCandle (excludes currentCandle)
int windowSize = 32;
int windowStart = Math.Max(0, i - windowSize); // Ensure no negative indices
var lookbackWindow = stcCandles
.Skip(windowStart)
.Take(i - windowStart) // Take up to previousCandle (i-1)
.ToList();
double? minStc = lookbackWindow.Min(c => c.Stc);
double? maxStc = lookbackWindow.Max(c => c.Stc);
// Short Signal: Break below 75 with prior min >78
if (previousCandle.Stc > 75 && currentCandle.Stc <= 75)
{
if (minStc > 78)
{
AddSignal(currentCandle, TradeDirection.Short, Confidence.Medium);
}
}
// Long Signal: Break above 25 with prior max <11
if (previousCandle.Stc < 25 && currentCandle.Stc >= 25)
{
if (maxStc < 11)
{
AddSignal(currentCandle, TradeDirection.Long, Confidence.Medium);
}
}
}
return Signals.Where(s => s.Confidence != Confidence.None).OrderBy(s => s.Date).ToList();
}
catch (RuleException)
{
return null;
}
}
public override StrategiesResultBase GetStrategyValues()
{
var stc = Candles.GetStc(FastPeriods.Value, FastPeriods.Value, SlowPeriods.Value).ToList();
return new StrategiesResultBase
{
Stc = stc
};
}
private List<CandleSct> MapStcToCandle(List<StcResult> stc, IEnumerable<Candle> candles)
{
var sctList = new List<CandleSct>();
foreach (var candle in candles)
{
var currentSct = stc.Find(candle.Date);
if (currentSct != null)
{
sctList.Add(new CandleSct()
{
Close = candle.Close,
Open = candle.Open,
Date = candle.Date,
Ticker = candle.Ticker,
Exchange = candle.Exchange,
Stc = currentSct.Stc
});
}
}
return sctList;
}
private void AddSignal(CandleSct candleSignal, TradeDirection direction, Confidence confidence)
{
var signal = new Signal(
MiscExtensions.ParseEnum<Ticker>(candleSignal.Ticker),
direction,
confidence,
candleSignal,
candleSignal.Date,
candleSignal.Exchange,
Type, SignalType);
if (!Signals.Any(s => s.Identifier == signal.Identifier))
{
Signals.AddItem(signal);
}
}
private class CandleSct : Candle
{
public double? Stc { get; internal set; }
}
}

View File

@@ -0,0 +1,192 @@
using Managing.Core;
using Managing.Domain.Candles;
using Managing.Domain.Shared.Rules;
using Managing.Domain.Strategies.Base;
using Skender.Stock.Indicators;
using static Managing.Common.Enums;
namespace Managing.Domain.Strategies;
public class SuperTrendCrossEma : Strategy
{
public List<Signal> Signals { get; set; }
public SuperTrendCrossEma(string name, int period, double multiplier) : base(name, StrategyType.SuperTrendCrossEma)
{
Signals = new List<Signal>();
Period = period;
Multiplier = multiplier;
MinimumHistory = 100 + Period.Value;
}
public override List<Signal> Run()
{
// Validate sufficient historical data for all indicators
const int emaPeriod = 50;
const int adxPeriod = 14; // Standard ADX period
const int adxThreshold = 25; // Minimum ADX level to confirm a trend
int minimumRequiredHistory = Math.Max(Math.Max(emaPeriod, adxPeriod), Period.Value * 2); // Ensure enough data
if (Candles.Count < minimumRequiredHistory)
{
return null;
}
try
{
// 1. Calculate indicators
var superTrend = Candles.GetSuperTrend(Period.Value, Multiplier.Value)
.Where(s => s.SuperTrend.HasValue)
.ToList();
var ema50 = Candles.GetEma(emaPeriod)
.Where(e => e.Ema.HasValue)
.ToList();
var adxResults = Candles.GetAdx(adxPeriod)
.Where(a => a.Adx.HasValue && a.Pdi.HasValue && a.Mdi.HasValue) // Ensure all values exist
.ToList();
// 2. Create merged dataset with price + indicators
var superTrendCandles = MapSuperTrendToCandle(superTrend, Candles.TakeLast(minimumRequiredHistory));
if (superTrendCandles.Count == 0)
return null;
// 3. Add EMA50 and ADX values to the CandleSuperTrend objects
foreach (var candle in superTrendCandles)
{
var emaValue = ema50.Find(e => e.Date == candle.Date)?.Ema;
var adxValue = adxResults.Find(a => a.Date == candle.Date);
if (emaValue.HasValue)
candle.Ema50 = emaValue.Value;
if (adxValue != null)
{
candle.Adx = (decimal)adxValue.Adx.Value;
candle.Pdi = (decimal)adxValue.Pdi.Value;
candle.Mdi = (decimal)adxValue.Mdi.Value;
}
}
// 4. Signal detection logic with ADX filter
for (int i = 1; i < superTrendCandles.Count; i++)
{
var current = superTrendCandles[i];
var previous = superTrendCandles[i - 1];
// Convert SuperTrend to double for comparison
double currentSuperTrend = (double)current.SuperTrend;
double previousSuperTrend = (double)previous.SuperTrend;
// Ensure ADX data exists
if (current.Adx < adxThreshold) // Only trade when ADX confirms trend strength
continue;
/* LONG SIGNAL CONDITIONS:
* 1. SuperTrend crosses above EMA50
* 2. Price > SuperTrend and > EMA50
* 3. Previous state shows SuperTrend < EMA50
* 4. ADX > threshold and +DI > -DI (bullish momentum)
*/
bool longCross = currentSuperTrend > current.Ema50 &&
previousSuperTrend < previous.Ema50;
bool longPricePosition = current.Close > (decimal)currentSuperTrend &&
current.Close > (decimal)current.Ema50;
bool adxBullish = current.Pdi > current.Mdi; // Bullish momentum confirmation
if (longCross && longPricePosition && adxBullish)
{
AddSignal(current, TradeDirection.Long, Confidence.Medium);
}
/* SHORT SIGNAL CONDITIONS:
* 1. SuperTrend crosses below EMA50
* 2. Price < SuperTrend and < EMA50
* 3. Previous state shows SuperTrend > EMA50
* 4. ADX > threshold and -DI > +DI (bearish momentum)
*/
bool shortCross = currentSuperTrend < current.Ema50 &&
previousSuperTrend > previous.Ema50;
bool shortPricePosition = current.Close < (decimal)currentSuperTrend &&
current.Close < (decimal)current.Ema50;
bool adxBearish = current.Mdi > current.Pdi; // Bearish momentum confirmation
if (shortCross && shortPricePosition && adxBearish)
{
AddSignal(current, TradeDirection.Short, Confidence.Medium);
}
}
return Signals.Where(s => s.Confidence != Confidence.None)
.OrderBy(s => s.Date)
.ToList();
}
catch (RuleException)
{
return null;
}
}
private List<CandleSuperTrend> MapSuperTrendToCandle(List<SuperTrendResult> superTrend, IEnumerable<Candle> candles)
{
var superTrends = new List<CandleSuperTrend>();
foreach (var candle in candles)
{
var currentSuperTrend = superTrend.Find(candle.Date);
if (currentSuperTrend != null)
{
superTrends.Add(new CandleSuperTrend()
{
Close = candle.Close,
Open = candle.Open,
Date = candle.Date,
Ticker = candle.Ticker,
Exchange = candle.Exchange,
SuperTrend = currentSuperTrend.SuperTrend.Value,
LowerBand = currentSuperTrend.LowerBand,
UpperBand = currentSuperTrend.UpperBand,
});
}
}
return superTrends;
}
public override StrategiesResultBase GetStrategyValues()
{
return new StrategiesResultBase()
{
SuperTrend = Candles.GetSuperTrend(Period.Value, Multiplier.Value).Where(s => s.SuperTrend.HasValue)
.ToList()
};
}
private void AddSignal(CandleSuperTrend candleSignal, TradeDirection direction, Confidence confidence)
{
var signal = new Signal(MiscExtensions.ParseEnum<Ticker>(candleSignal.Ticker), direction, confidence,
candleSignal, candleSignal.Date,
candleSignal.Exchange, Type, SignalType);
if (!Signals.Any(s => s.Identifier == signal.Identifier))
{
Signals.AddItem(signal);
}
}
private class CandleSuperTrend : Candle
{
public decimal SuperTrend { get; internal set; }
public decimal? LowerBand { get; internal set; }
public decimal? UpperBand { get; internal set; }
public double Ema50 { get; set; }
public decimal Adx { get; set; } // ADX value
public decimal Pdi { get; set; } // Positive Directional Indicator (+DI)
public decimal Mdi { get; set; } // Negative Directional Indicator (-DI)
}
}