using System; using System.Collections.Generic; using System.Linq; using FinlyticCore.Dtos.TechnicalAnalysis; using FinlyticTechnicalAnalysis.Entities; using Skender.Stock.Indicators; namespace FinlyticTechnicalAnalysis.Services; public interface ITechnicalAnalysisCalculator { /// /// Calculates the technical analysis using Skender.StockIndicators for math and custom algorithms for pattern detection. /// (List Indicators, List Patterns, List Signals) CalculateAnalysis(List candles, string currency = "EUR"); } public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator { public (List Indicators, List Patterns, List Signals) CalculateAnalysis(List candles, string currency = "EUR") { var indicators = new List(); var patterns = new List(); var signals = new List(); if (candles == null || candles.Count == 0) return (indicators, patterns, signals); var curSym = GetCurrencySymbol(currency); var sortedCandles = candles.OrderBy(c => c.Timestamp).ToList(); // 1. Convert domain candles to Skender Quotes var quotes = sortedCandles.Select(c => new Quote { Date = c.Timestamp, Open = c.Open, High = c.High, Low = c.Low, Close = c.Close, Volume = c.Volume }).ToList(); // 2. Compute Indicators via Skender.StockIndicators var ema20List = quotes.GetEma(20).ToList(); var sma50List = quotes.GetSma(50).ToList(); var sma200List = quotes.GetSma(200).ToList(); var rsi14List = quotes.GetRsi(14).ToList(); var macdList = quotes.GetMacd(12, 26, 9).ToList(); var atr14List = quotes.GetAtr(14).ToList(); var vwapList = quotes.GetVwap().ToList(); var supertrendList = quotes.GetSuperTrend(10, 3.0).ToList(); // Build IndicatorValuesDto list per candle for (int i = 0; i < sortedCandles.Count; i++) { var candle = sortedCandles[i]; var closeVal = candle.Close; var atr = atr14List[i].Atr.HasValue ? (decimal)atr14List[i].Atr!.Value : 0m; var stopLoss = atr > 0m ? closeVal - (1.5m * atr) : (decimal?)null; // Map Supertrend direction string string? superDir = null; if (supertrendList[i].LowerBand.HasValue) superDir = "Bullish"; else if (supertrendList[i].UpperBand.HasValue) superDir = "Bearish"; indicators.Add(new IndicatorValuesDto( Timestamp: candle.Timestamp, Ema20: ema20List[i].Ema.HasValue ? (decimal)ema20List[i].Ema!.Value : null, Sma50: sma50List[i].Sma.HasValue ? (decimal)sma50List[i].Sma!.Value : null, Sma200: sma200List[i].Sma.HasValue ? (decimal)sma200List[i].Sma!.Value : null, Rsi14: rsi14List[i].Rsi.HasValue ? (decimal)rsi14List[i].Rsi!.Value : null, MacdLine: macdList[i].Macd.HasValue ? (decimal)macdList[i].Macd!.Value : null, MacdSignal: macdList[i].Signal.HasValue ? (decimal)macdList[i].Signal!.Value : null, MacdHistogram: macdList[i].Histogram.HasValue ? (decimal)macdList[i].Histogram!.Value : null, Atr14: atr > 0m ? atr : null, Vwap: vwapList[i].Vwap.HasValue ? (decimal)vwapList[i].Vwap!.Value : null, SupertrendUpper: supertrendList[i].UpperBand.HasValue ? (decimal)supertrendList[i].UpperBand!.Value : null, SupertrendLower: supertrendList[i].LowerBand.HasValue ? (decimal)supertrendList[i].LowerBand!.Value : null, SupertrendDirection: superDir, RecommendedStopLoss: stopLoss )); } // 3. Detect Strategy Signals using computed indicator lists var sma50Values = sma50List.Select(x => x.Sma).ToList(); var sma200Values = sma200List.Select(x => x.Sma).ToList(); var rsiValues = rsi14List.Select(x => x.Rsi).ToList(); DetectStrategySignals(sortedCandles, sma50Values, sma200Values, rsiValues, signals); // 4. Detect Geometric Chart Patterns DetectTrianglePatterns(sortedCandles, patterns, curSym); return (indicators, patterns, signals); } private static string GetCurrencySymbol(string currency) { if (string.IsNullOrWhiteSpace(currency)) return "€"; return currency.ToUpperInvariant() switch { "USD" => "$", "GBP" => "£", "CHF" => "CHF ", "JPY" => "¥", _ => "€" }; } private static void DetectStrategySignals(List candles, List sma50, List sma200, List rsi14, List signals) { for (int i = 1; i < candles.Count; i++) { var candle = candles[i]; // Golden Cross / Death Cross if (sma50[i - 1].HasValue && sma200[i - 1].HasValue && sma50[i].HasValue && sma200[i].HasValue) { if (sma50[i - 1]!.Value <= sma200[i - 1]!.Value && sma50[i]!.Value > sma200[i]!.Value) { signals.Add(new StrategySignalDto( Type: "GoldenCross", Timestamp: candle.Timestamp, Direction: "BUY", Price: candle.Close, Description: "Golden Cross: SMA 50 hat den SMA 200 von unten nach oben gekreuzt (Bullisches Signal)." )); } else if (sma50[i - 1]!.Value >= sma200[i - 1]!.Value && sma50[i]!.Value < sma200[i]!.Value) { signals.Add(new StrategySignalDto( Type: "DeathCross", Timestamp: candle.Timestamp, Direction: "SELL", Price: candle.Close, Description: "Death Cross: SMA 50 hat den SMA 200 von oben nach unten gekreuzt (Bearisches Signal)." )); } } // RSI Oversold / Overbought Rebounds if (rsi14[i].HasValue && rsi14[i - 1].HasValue) { if (rsi14[i - 1]!.Value < 30 && rsi14[i]!.Value >= 30) { signals.Add(new StrategySignalDto( Type: "RsiOversoldRebound", Timestamp: candle.Timestamp, Direction: "BUY", Price: candle.Close, Description: "RSI (14) steigt aus überverkauftem Bereich (<30) wieder an." )); } else if (rsi14[i - 1]!.Value > 70 && rsi14[i]!.Value <= 70) { signals.Add(new StrategySignalDto( Type: "RsiOverboughtCorrection", Timestamp: candle.Timestamp, Direction: "SELL", Price: candle.Close, Description: "RSI (14) fällt aus überkauftem Bereich (>70) zurück." )); } } } } private static void DetectTrianglePatterns(List sortedCandles, List patterns, string curSym) { if (sortedCandles.Count < 20) return; int[] windowSizes = { 20, 30, 45, 60, 90, 120 }; var candidatePatterns = new List(); foreach (var window in windowSizes) { if (sortedCandles.Count < window) continue; var slice = sortedCandles.TakeLast(window).ToList(); DetectDoubleBottomInSlice(slice, candidatePatterns, curSym); DetectDoubleTopInSlice(slice, candidatePatterns, curSym); DetectHeadAndShouldersInSlice(slice, candidatePatterns, curSym); DetectTrianglesInSlice(slice, candidatePatterns, curSym); } if (candidatePatterns.Count == 0) return; var currentClose = sortedCandles.Last().Close; bool activeSellBreakdown = candidatePatterns.Any(p => p.BreakoutSignal?.Direction == "SELL" && currentClose < p.BreakoutSignal.TriggerPrice); bool activeBuyBreakout = candidatePatterns.Any(p => p.BreakoutSignal?.Direction == "BUY" && currentClose > p.BreakoutSignal.TriggerPrice); var filteredPatterns = candidatePatterns.Where(p => { var isBuy = p.BreakoutSignal?.Direction == "BUY"; var trigger = p.BreakoutSignal?.TriggerPrice ?? 0m; if (activeSellBreakdown && isBuy && currentClose < trigger) return false; if (activeBuyBreakout && !isBuy && currentClose > trigger) return false; return true; }).ToList(); var distinctPatterns = filteredPatterns .GroupBy(p => p.Type) .Select(g => g.OrderByDescending(p => p.ConfidencePercent ?? 0m).First()) .OrderByDescending(p => p.ConfidencePercent ?? 0m) .ToList(); patterns.Clear(); patterns.AddRange(distinctPatterns); } private static List FindPivotLows(List candles, int lookback = 3) { var result = new List(); for (int i = lookback; i < candles.Count - lookback; i++) { var low = candles[i].Low; bool isPivot = true; for (int j = i - lookback; j <= i + lookback; j++) { if (j == i) continue; if (candles[j].Low <= low) { isPivot = false; break; } } if (isPivot) result.Add(i); } return result; } private static List FindPivotHighs(List candles, int lookback = 3) { var result = new List(); for (int i = lookback; i < candles.Count - lookback; i++) { var high = candles[i].High; bool isPivot = true; for (int j = i - lookback; j <= i + lookback; j++) { if (j == i) continue; if (candles[j].High >= high) { isPivot = false; break; } } if (isPivot) result.Add(i); } return result; } private static void DetectDoubleBottomInSlice(List slice, List patterns, string curSym) { if (slice.Count < 15) return; var currentClose = slice.Last().Close; var maxRecentHigh = slice.Max(c => c.High); int lookback = slice.Count >= 45 ? 3 : 2; var pivotLows = FindPivotLows(slice, lookback); if (pivotLows.Count < 2) return; for (int a = 0; a < pivotLows.Count - 1; a++) { for (int b = a + 1; b < pivotLows.Count; b++) { int idx1 = pivotLows[a]; int idx2 = pivotLows[b]; if (idx2 - idx1 < 5) continue; decimal low1 = slice[idx1].Low; decimal low2 = slice[idx2].Low; if (Math.Abs(low1 - low2) / Math.Max(low1, low2) > 0.05m) continue; decimal neckline = 0m; for (int k = idx1; k <= idx2; k++) if (slice[k].High > neckline) neckline = slice[k].High; decimal avgLow = (low1 + low2) / 2m; if (neckline < avgLow * 1.02m) continue; var targetPrice = neckline + (neckline - avgLow); if (maxRecentHigh >= targetPrice) continue; if (currentClose < avgLow * 0.97m) continue; bool breakoutConfirmed = maxRecentHigh >= neckline * 1.01m; if (breakoutConfirmed && currentClose < neckline) continue; if (!breakoutConfirmed && currentClose < neckline * 0.90m) continue; DateTime breakoutTime = slice.Last().Timestamp; for (int k = idx2 + 1; k < slice.Count; k++) { if (slice[k].High >= neckline || slice[k].Close >= neckline) { breakoutTime = slice[k].Timestamp; break; } } var diffRatio = Math.Abs(low1 - low2) / Math.Max(low1, low2); var neckDistRatio = (neckline - avgLow) / avgLow; var conf = Math.Round(Math.Max(70m, 98m - (diffRatio * 600m) + (neckDistRatio * 200m)), 1); conf = Math.Min(conf, 99m); var pct = currentClose > 0m ? ((targetPrice - currentClose) / currentClose) * 100m : 0m; string status = breakoutConfirmed ? $"Ausbruch über {neckline:F2} {curSym} erfolgt (Kurs bei {currentClose:F2} {curSym}). Signal aktiv." : $"Warten auf Ausbruch über Nackenlinie {neckline:F2} {curSym} (Trigger)."; DateTime futureTime = slice.Last().Timestamp.AddDays(14); double daysBetweenTiefs = (slice[idx2].Timestamp - slice[idx1].Timestamp).TotalDays; if (daysBetweenTiefs <= 0) daysBetweenTiefs = 1; double lowerSlope = (double)(low2 - low1) / daysBetweenTiefs; double daysToFuture = (futureTime - slice[idx1].Timestamp).TotalDays; decimal projectedLowerPrice = low1 + (decimal)(lowerSlope * daysToFuture); patterns.Add(new ChartPatternDto( Type: "DoubleBottom", Description: $"Doppel-Tief (W-Muster): Bullische Bodenformation. Zwei Tiefs bei ~{avgLow:F2} {curSym} getestet. {status}", UpperLine: new List { new(slice[idx1].Timestamp, neckline), new(futureTime, neckline) }, LowerLine: new List { new(slice[idx1].Timestamp, low1), new(slice[idx2].Timestamp, low2), new(futureTime, projectedLowerPrice) }, ApexTime: null, BreakoutSignal: new BreakoutSignalDto( Time: breakoutTime, Direction: "BUY", TriggerPrice: neckline, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: conf)); return; } } } private static void DetectDoubleTopInSlice(List slice, List patterns, string curSym) { if (slice.Count < 15) return; var currentClose = slice.Last().Close; var minRecentLow = slice.Min(c => c.Low); int lookback = slice.Count >= 45 ? 3 : 2; var pivotHighs = FindPivotHighs(slice, lookback); if (pivotHighs.Count < 2) return; for (int a = 0; a < pivotHighs.Count - 1; a++) { for (int b = a + 1; b < pivotHighs.Count; b++) { int idx1 = pivotHighs[a]; int idx2 = pivotHighs[b]; if (idx2 - idx1 < 5) continue; decimal high1 = slice[idx1].High; decimal high2 = slice[idx2].High; if (Math.Abs(high1 - high2) / Math.Max(high1, high2) > 0.05m) continue; decimal neckline = decimal.MaxValue; for (int k = idx1; k <= idx2; k++) if (slice[k].Low < neckline) neckline = slice[k].Low; decimal avgHigh = (high1 + high2) / 2m; if (neckline > avgHigh * 0.98m) continue; var targetPrice = neckline - (avgHigh - neckline); if (minRecentLow <= targetPrice) continue; if (currentClose > avgHigh * 1.03m) continue; bool breakdownConfirmed = minRecentLow <= neckline * 0.99m; if (breakdownConfirmed && currentClose > neckline) continue; if (!breakdownConfirmed && currentClose > neckline * 1.10m) continue; DateTime breakdownTime = slice.Last().Timestamp; for (int k = idx2 + 1; k < slice.Count; k++) { if (slice[k].Low <= neckline || slice[k].Close <= neckline) { breakdownTime = slice[k].Timestamp; break; } } var diffRatio = Math.Abs(high1 - high2) / Math.Max(high1, high2); var neckDistRatio = (avgHigh - neckline) / avgHigh; var conf = Math.Round(Math.Max(70m, 97m - (diffRatio * 600m) + (neckDistRatio * 200m)), 1); conf = Math.Min(conf, 99m); var pct = currentClose > 0m ? ((currentClose - targetPrice) / currentClose) * 100m : 0m; string status = breakdownConfirmed ? $"Breakdown unter {neckline:F2} {curSym} erfolgt (Kurs bei {currentClose:F2} {curSym}). Signal aktiv." : $"Warten auf Breakdown unter Nackenlinie {neckline:F2} {curSym} (Trigger)."; DateTime futureTime = slice.Last().Timestamp.AddDays(14); double daysBetweenHighs = (slice[idx2].Timestamp - slice[idx1].Timestamp).TotalDays; if (daysBetweenHighs <= 0) daysBetweenHighs = 1; double upperSlope = (double)(high2 - high1) / daysBetweenHighs; double daysToFuture = (futureTime - slice[idx1].Timestamp).TotalDays; decimal projectedUpperPrice = high1 + (decimal)(upperSlope * daysToFuture); patterns.Add(new ChartPatternDto( Type: "DoubleTop", Description: $"Doppel-Top (M-Muster): Bearische Umkehrformation. Widerstand bei ~{avgHigh:F2} {curSym} zweimal abgeprallt. {status}", UpperLine: new List { new(slice[idx1].Timestamp, high1), new(slice[idx2].Timestamp, high2), new(futureTime, projectedUpperPrice) }, LowerLine: new List { new(slice[idx1].Timestamp, neckline), new(futureTime, neckline) }, ApexTime: null, BreakoutSignal: new BreakoutSignalDto( Time: breakdownTime, Direction: "SELL", TriggerPrice: neckline, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: conf)); return; } } } private static void DetectHeadAndShouldersInSlice(List slice, List patterns, string curSym) { if (slice.Count < 20) return; var currentClose = slice.Last().Close; var minRecentLow = slice.Min(c => c.Low); int lookback = slice.Count >= 60 ? 4 : 3; var pivotHighs = FindPivotHighs(slice, lookback); if (pivotHighs.Count < 3) return; for (int a = 0; a < pivotHighs.Count - 2; a++) { int lsIdx = pivotHighs[a]; int headIdx = pivotHighs[a + 1]; int rsIdx = pivotHighs[a + 2]; decimal ls = slice[lsIdx].High; decimal head = slice[headIdx].High; decimal rs = slice[rsIdx].High; if (head <= ls * 1.01m || head <= rs * 1.01m) continue; if (Math.Abs(ls - rs) / Math.Max(ls, rs) > 0.06m) continue; decimal neckline = decimal.MaxValue; for (int k = lsIdx; k <= rsIdx; k++) if (slice[k].Low < neckline) neckline = slice[k].Low; var targetPrice = neckline - (head - neckline); if (minRecentLow <= targetPrice) continue; if (currentClose > head * 1.03m) continue; bool breakdownConfirmed = minRecentLow <= neckline * 0.99m; if (breakdownConfirmed && currentClose > neckline) continue; if (!breakdownConfirmed && currentClose > neckline * 1.10m) continue; DateTime breakdownTime = slice.Last().Timestamp; for (int k = rsIdx + 1; k < slice.Count; k++) { if (slice[k].Low <= neckline || slice[k].Close <= neckline) { breakdownTime = slice[k].Timestamp; break; } } var diffRatio = Math.Abs(ls - rs) / Math.Max(ls, rs); var conf = Math.Round(Math.Max(72m, 96m - (diffRatio * 500m)), 1); conf = Math.Min(conf, 99m); var pct = currentClose > 0m ? ((currentClose - targetPrice) / currentClose) * 100m : 0m; string status = breakdownConfirmed ? $"Breakdown unter {neckline:F2} {curSym} erfolgt (Kurs bei {currentClose:F2} {curSym}). Signal aktiv." : $"Warten auf Breakdown unter Nackenlinie {neckline:F2} {curSym} (Trigger)."; DateTime futureTime = slice.Last().Timestamp.AddDays(14); double daysBetweenShoulders = (slice[rsIdx].Timestamp - slice[lsIdx].Timestamp).TotalDays; if (daysBetweenShoulders <= 0) daysBetweenShoulders = 1; double upperSlope = (double)(rs - ls) / daysBetweenShoulders; double daysToFuture = (futureTime - slice[lsIdx].Timestamp).TotalDays; decimal projectedUpperPrice = ls + (decimal)(upperSlope * daysToFuture); patterns.Add(new ChartPatternDto( Type: "HeadAndShoulders", Description: $"Kopf-Schulter-Formation: Bearische Trendumkehr. Kopf bei {head:F2} {curSym}, Nackenlinie bei {neckline:F2} {curSym} (Trigger). {status}", UpperLine: new List { new(slice[lsIdx].Timestamp, ls), new(slice[rsIdx].Timestamp, rs), new(futureTime, projectedUpperPrice) }, LowerLine: new List { new(slice[lsIdx].Timestamp, neckline), new(futureTime, neckline) }, ApexTime: null, BreakoutSignal: new BreakoutSignalDto( Time: breakdownTime, Direction: "SELL", TriggerPrice: neckline, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: conf)); return; } } private static void DetectTrianglesInSlice(List slice, List patterns, string curSym) { if (slice.Count < 10) return; var startTime = slice[0].Timestamp; var endTime = slice[^1].Timestamp; var lastPrice = slice[^1].Close; var maxRecentHigh = slice.Max(c => c.High); var minRecentLow = slice.Min(c => c.Low); int third = slice.Count / 3; var first = slice.Take(third).ToList(); var last = slice.TakeLast(third).ToList(); decimal high1 = first.Max(c => c.High); decimal high2 = last.Max(c => c.High); decimal low1 = first.Min(c => c.Low); decimal low2 = last.Min(c => c.Low); decimal triangleBaseHeight = Math.Max(0.5m, high1 - low1); double totalDays = (endTime - startTime).TotalDays; if (totalDays <= 0) totalDays = 10; DateTime apexTime = endTime.AddDays(10); double mUpper = (double)(high2 - high1) / totalDays; double mLower = (double)(low2 - low1) / totalDays; if (Math.Abs(mUpper - mLower) > 0.00001) { double daysToApex = (double)(low1 - high1) / (mUpper - mLower); if (daysToApex > 0 && daysToApex < 120) { apexTime = startTime.AddDays(daysToApex); } } if (high2 >= high1 * 0.97m && high2 <= high1 * 1.03m && low2 > low1 * 1.01m) { var resistance = (high1 + high2) / 2m; var targetPrice = resistance + triangleBaseHeight; bool breakoutConfirmed = maxRecentHigh >= resistance * 1.01m; bool isValid = maxRecentHigh < targetPrice && lastPrice >= low1 * 0.97m; if (breakoutConfirmed && lastPrice < resistance) isValid = false; if (isValid && !patterns.Any(p => p.Type == "AscendingTriangle")) { var pct = lastPrice > 0m ? ((targetPrice - lastPrice) / lastPrice) * 100m : 0m; var conf = Math.Round(Math.Max(70m, 93m - (Math.Abs(high1 - high2) / high1) * 600m), 1); patterns.Add(new ChartPatternDto( Type: "AscendingTriangle", Description: $"Steigendes Dreieck: Flacher Widerstand bei {resistance:F2} {curSym} (Trigger) mit steigenden Tiefs — bullisches Konsolidierungsmuster.", UpperLine: new List { new(startTime, resistance), new(apexTime, resistance) }, LowerLine: new List { new(startTime, low1), new(apexTime, resistance) }, ApexTime: apexTime, BreakoutSignal: new BreakoutSignalDto(Time: endTime, Direction: "BUY", TriggerPrice: resistance, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: conf)); } } if (low2 >= low1 * 0.97m && low2 <= low1 * 1.03m && high2 < high1 * 0.99m) { var support = (low1 + low2) / 2m; var targetPrice = Math.Max(0.01m, support - triangleBaseHeight); bool breakdownConfirmed = minRecentLow <= support * 0.99m; bool isValid = minRecentLow > targetPrice && lastPrice <= high1 * 1.03m; if (breakdownConfirmed && lastPrice > support) isValid = false; if (isValid && !patterns.Any(p => p.Type == "DescendingTriangle")) { var pct = lastPrice > 0m ? ((lastPrice - targetPrice) / lastPrice) * 100m : 0m; var conf = Math.Round(Math.Max(70m, 93m - (Math.Abs(low1 - low2) / low1) * 600m), 1); patterns.Add(new ChartPatternDto( Type: "DescendingTriangle", Description: $"Fallendes Dreieck: Flache Unterstützung bei {support:F2} {curSym} (Trigger) mit fallenden Hochs — bearisches Konsolidierungsmuster.", UpperLine: new List { new(startTime, high1), new(apexTime, support) }, LowerLine: new List { new(startTime, support), new(apexTime, support) }, ApexTime: apexTime, BreakoutSignal: new BreakoutSignalDto(Time: endTime, Direction: "SELL", TriggerPrice: support, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: conf)); } } if (high2 < high1 * 0.99m && low2 > low1 * 1.01m) { if (!patterns.Any(p => p.Type == "SymmetricalTriangle")) { var direction = lastPrice >= (high1 + low1) / 2m ? "BUY" : "SELL"; var targetPrice = direction == "BUY" ? lastPrice + triangleBaseHeight : Math.Max(0.01m, lastPrice - triangleBaseHeight); var pct = lastPrice > 0m ? (direction == "BUY" ? ((targetPrice - lastPrice) / lastPrice) : ((lastPrice - targetPrice) / lastPrice)) * 100m : 0m; decimal apexPrice = (high2 + low2) / 2m; patterns.Add(new ChartPatternDto( Type: "SymmetricalTriangle", Description: $"Symmetrisches Dreieck: Konvergierende Hochs und Tiefs — dynamischer Ausbruch in Trendrichtung erwartet.", UpperLine: new List { new(startTime, high1), new(apexTime, apexPrice) }, LowerLine: new List { new(startTime, low1), new(apexTime, apexPrice) }, ApexTime: apexTime, BreakoutSignal: new BreakoutSignalDto(Time: endTime, Direction: direction, TriggerPrice: lastPrice, TargetPrice: targetPrice, PotentialPercent: pct), ConfidencePercent: 85m)); } } } }