671 lines
29 KiB
C#
671 lines
29 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// Calculates the technical analysis using Skender.StockIndicators for math and custom algorithms for pattern detection.
|
|
/// </summary>
|
|
(List<IndicatorValuesDto> Indicators, List<ChartPatternDto> Patterns, List<StrategySignalDto> Signals) CalculateAnalysis(List<MarketCandleEntity> candles, string currency = "EUR");
|
|
}
|
|
|
|
public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
|
|
{
|
|
public (List<IndicatorValuesDto> Indicators, List<ChartPatternDto> Patterns, List<StrategySignalDto> Signals) CalculateAnalysis(List<MarketCandleEntity> candles, string currency = "EUR")
|
|
{
|
|
var indicators = new List<IndicatorValuesDto>();
|
|
var patterns = new List<ChartPatternDto>();
|
|
var signals = new List<StrategySignalDto>();
|
|
|
|
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
|
|
DetectChartPatterns(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<MarketCandleEntity> candles, List<double?> sma50, List<double?> sma200, List<double?> rsi14, List<StrategySignalDto> signals)
|
|
{
|
|
for (int i = 1; i < candles.Count; i++)
|
|
{
|
|
var candle = candles[i];
|
|
|
|
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)."
|
|
));
|
|
}
|
|
}
|
|
|
|
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 DetectChartPatterns(List<MarketCandleEntity> sortedCandles, List<ChartPatternDto> patterns, string curSym)
|
|
{
|
|
if (sortedCandles.Count < 20) return;
|
|
|
|
int[] windowSizes = { 20, 30, 45, 60, 90, 120 };
|
|
var candidatePatterns = new List<ChartPatternDto>();
|
|
|
|
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();
|
|
|
|
// Gruppierung nach Typ & Auswahl des Musters mit der höchsten Confidence
|
|
var distinctPatterns = filteredPatterns
|
|
.GroupBy(p => p.Type)
|
|
.Select(g => g.OrderByDescending(p => p.ConfidencePercent ?? 0m).First())
|
|
.OrderByDescending(p => p.ConfidencePercent ?? 0m)
|
|
.ToList();
|
|
|
|
// Wenn ein starkes Reversal-Muster (z.B. DoubleTop mit 90%+ Confidence) existiert,
|
|
// entfeuern wir konkurrierende generische Dreiecks-Formationen im selben Zeitfenster.
|
|
if (distinctPatterns.Any(p => p.Type == "DoubleTop" && (p.ConfidencePercent ?? 0) > 90m))
|
|
{
|
|
distinctPatterns.RemoveAll(p => p.Type == "SymmetricalTriangle");
|
|
}
|
|
|
|
patterns.Clear();
|
|
patterns.AddRange(distinctPatterns);
|
|
}
|
|
|
|
private static List<int> FindPivotLows(List<MarketCandleEntity> candles, int lookback = 3)
|
|
{
|
|
var result = new List<int>();
|
|
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<int> FindPivotHighs(List<MarketCandleEntity> candles, int lookback = 3)
|
|
{
|
|
var result = new List<int>();
|
|
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<MarketCandleEntity> slice, List<ChartPatternDto> 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);
|
|
|
|
patterns.Add(new ChartPatternDto(
|
|
Type: "DoubleBottom",
|
|
Description: $"Doppel-Tief (W-Muster): Bullische Bodenformation. Zwei Tiefs bei ~{avgLow:F2} {curSym} getestet. {status}",
|
|
UpperLine: new List<PatternPointDto>
|
|
{
|
|
new(slice[idx1].Timestamp, neckline),
|
|
new(futureTime, neckline)
|
|
},
|
|
LowerLine: new List<PatternPointDto>
|
|
{
|
|
new(slice[idx1].Timestamp, low1),
|
|
new(slice[idx2].Timestamp, low2)
|
|
},
|
|
ApexTime: null,
|
|
BreakoutSignal: new BreakoutSignalDto(
|
|
Time: breakoutTime,
|
|
Direction: "BUY",
|
|
TriggerPrice: neckline,
|
|
TargetPrice: targetPrice,
|
|
PotentialPercent: pct),
|
|
ConfidencePercent: conf));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void DetectDoubleTopInSlice(List<MarketCandleEntity> slice, List<ChartPatternDto> 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);
|
|
|
|
patterns.Add(new ChartPatternDto(
|
|
Type: "DoubleTop",
|
|
Description: $"Doppel-Top (M-Muster): Bearische Umkehrformation. Widerstand bei ~{avgHigh:F2} {curSym} zweimal abgeprallt. {status}",
|
|
UpperLine: new List<PatternPointDto>
|
|
{
|
|
new(slice[idx1].Timestamp, high1),
|
|
new(slice[idx2].Timestamp, high2)
|
|
},
|
|
LowerLine: new List<PatternPointDto>
|
|
{
|
|
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<MarketCandleEntity> slice, List<ChartPatternDto> 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);
|
|
|
|
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<PatternPointDto>
|
|
{
|
|
new(slice[lsIdx].Timestamp, ls),
|
|
new(slice[headIdx].Timestamp, head),
|
|
new(slice[rsIdx].Timestamp, rs)
|
|
},
|
|
LowerLine: new List<PatternPointDto>
|
|
{
|
|
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<MarketCandleEntity> slice, List<ChartPatternDto> patterns, string curSym)
|
|
{
|
|
if (slice.Count < 15) return;
|
|
|
|
int lookback = 2;
|
|
var pHighs = FindPivotHighs(slice, lookback);
|
|
var pLows = FindPivotLows(slice, lookback);
|
|
|
|
if (pHighs.Count < 2 || pLows.Count < 2) return;
|
|
|
|
// Nutze die letzten beiden Pivot-Highs und Pivot-Lows für exakte Geradengleichungen
|
|
int hIdx1 = pHighs[^2];
|
|
int hIdx2 = pHighs[^1];
|
|
int lIdx1 = pLows[^2];
|
|
int lIdx2 = pLows[^1];
|
|
|
|
// Verhindere zu nahe beieinander liegende Pivots
|
|
if (hIdx2 - hIdx1 < 3 || lIdx2 - lIdx1 < 3) return;
|
|
|
|
DateTime tH1 = slice[hIdx1].Timestamp;
|
|
DateTime tH2 = slice[hIdx2].Timestamp;
|
|
DateTime tL1 = slice[lIdx1].Timestamp;
|
|
DateTime tL2 = slice[lIdx2].Timestamp;
|
|
|
|
decimal yH1 = slice[hIdx1].High;
|
|
decimal yH2 = slice[hIdx2].High;
|
|
decimal yL1 = slice[lIdx1].Low;
|
|
decimal yL2 = slice[lIdx2].Low;
|
|
|
|
double daysH = (tH2 - tH1).TotalDays;
|
|
double daysL = (tL2 - tL1).TotalDays;
|
|
|
|
if (daysH <= 0 || daysL <= 0) return;
|
|
|
|
// Steigungen in €/Tag
|
|
double mUpper = (double)(yH2 - yH1) / daysH;
|
|
double mLower = (double)(yL2 - yL1) / daysL;
|
|
|
|
var lastCandle = slice.Last();
|
|
var lastClose = lastCandle.Close;
|
|
|
|
// --- 1. Steigendes Dreieck (Ascending Triangle) ---
|
|
// Obere Linie ist nahezu flach (Widerstand), Untere Linie steigt
|
|
if (Math.Abs(mUpper) < 0.05 && mLower > 0.01)
|
|
{
|
|
if (!patterns.Any(p => p.Type == "AscendingTriangle"))
|
|
{
|
|
decimal resistance = (yH1 + yH2) / 2m;
|
|
decimal baseHeight = resistance - yL1;
|
|
decimal targetPrice = resistance + baseHeight;
|
|
|
|
// Schnittpunkt (Apex) berechnen: y = mLower * x + yL1
|
|
double daysToApex = (double)(resistance - yL1) / mLower;
|
|
DateTime apexTime = tL1.AddDays(daysToApex);
|
|
|
|
if (apexTime > lastCandle.Timestamp)
|
|
{
|
|
var pct = lastClose > 0m ? ((targetPrice - lastClose) / lastClose) * 100m : 0m;
|
|
var conf = Math.Round(Math.Max(70m, 93m - (Math.Abs(yH1 - yH2) / yH1) * 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<PatternPointDto> { new(tH1, resistance), new(apexTime, resistance) },
|
|
LowerLine: new List<PatternPointDto> { new(tL1, yL1), new(tL2, yL2), new(apexTime, resistance) },
|
|
ApexTime: apexTime,
|
|
BreakoutSignal: new BreakoutSignalDto(Time: lastCandle.Timestamp, Direction: "BUY", TriggerPrice: resistance, TargetPrice: targetPrice, PotentialPercent: pct),
|
|
ConfidencePercent: conf));
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- 2. Fallendes Dreieck (Descending Triangle) ---
|
|
// Untere Linie ist nahezu flach (Unterstützung), Obere Linie fällt
|
|
if (Math.Abs(mLower) < 0.05 && mUpper < -0.01)
|
|
{
|
|
if (!patterns.Any(p => p.Type == "DescendingTriangle"))
|
|
{
|
|
decimal support = (yL1 + yL2) / 2m;
|
|
decimal baseHeight = yH1 - support;
|
|
decimal targetPrice = Math.Max(0.01m, support - baseHeight);
|
|
|
|
// Schnittpunkt (Apex) berechnen: y = mUpper * x + yH1
|
|
double daysToApex = (double)(support - yH1) / mUpper;
|
|
DateTime apexTime = tH1.AddDays(daysToApex);
|
|
|
|
if (apexTime > lastCandle.Timestamp)
|
|
{
|
|
var pct = lastClose > 0m ? ((lastClose - targetPrice) / lastClose) * 100m : 0m;
|
|
var conf = Math.Round(Math.Max(70m, 93m - (Math.Abs(yL1 - yL2) / yL1) * 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<PatternPointDto> { new(tH1, yH1), new(tH2, yH2), new(apexTime, support) },
|
|
LowerLine: new List<PatternPointDto> { new(tL1, support), new(apexTime, support) },
|
|
ApexTime: apexTime,
|
|
BreakoutSignal: new BreakoutSignalDto(Time: lastCandle.Timestamp, Direction: "SELL", TriggerPrice: support, TargetPrice: targetPrice, PotentialPercent: pct),
|
|
ConfidencePercent: conf));
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- 3. Symmetrisches Dreieck (Symmetrical Triangle) ---
|
|
// Obere Linie fällt (mUpper < 0) UND Untere Linie steigt (mLower > 0) -> Konvergieren!
|
|
if (mUpper < -0.005 && mLower > 0.01)
|
|
{
|
|
if (!patterns.Any(p => p.Type == "SymmetricalTriangle"))
|
|
{
|
|
// Präzise Berechnung des Schnittpunkts zweier Geraden in der Ebene (t, y)
|
|
// y = mUpper * (t - tH1) + yH1
|
|
// y = mLower * (t - tL1) + yL1
|
|
double deltaDaysT1 = (tH1 - tL1).TotalDays;
|
|
double denominator = mUpper - mLower;
|
|
|
|
if (Math.Abs(denominator) > 0.0001)
|
|
{
|
|
double daysFromT1ToApex = ((double)(yL1 - yH1) + (mLower * deltaDaysT1)) / denominator;
|
|
DateTime apexTime = tH1.AddDays(daysFromT1ToApex);
|
|
|
|
// Apex muss in der Zukunft liegen!
|
|
if (apexTime > lastCandle.Timestamp)
|
|
{
|
|
decimal apexPrice = yH1 + (decimal)(mUpper * daysFromT1ToApex);
|
|
decimal baseHeight = Math.Abs(yH1 - yL1);
|
|
|
|
var direction = lastClose >= (yH1 + yL1) / 2m ? "BUY" : "SELL";
|
|
var targetPrice = direction == "BUY"
|
|
? lastClose + baseHeight
|
|
: Math.Max(0.01m, lastClose - baseHeight);
|
|
|
|
var pct = lastClose > 0m
|
|
? (direction == "BUY" ? ((targetPrice - lastClose) / lastClose) : ((lastClose - targetPrice) / lastClose)) * 100m
|
|
: 0m;
|
|
|
|
patterns.Add(new ChartPatternDto(
|
|
Type: "SymmetricalTriangle",
|
|
Description: $"Symmetrisches Dreieck: Konvergierende Hochs und Tiefs — dynamischer Ausbruch in Trendrichtung erwartet.",
|
|
UpperLine: new List<PatternPointDto> { new(tH1, yH1), new(tH2, yH2), new(apexTime, apexPrice) },
|
|
LowerLine: new List<PatternPointDto> { new(tL1, yL1), new(tL2, yL2), new(apexTime, apexPrice) },
|
|
ApexTime: apexTime,
|
|
BreakoutSignal: new BreakoutSignalDto(Time: lastCandle.Timestamp, Direction: direction, TriggerPrice: lastClose, TargetPrice: targetPrice, PotentialPercent: pct),
|
|
ConfidencePercent: 85m));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |