refactor: save current workspace state including FinlyticAnalyzer fixes, FinlyticApp trade route alignment, and DTO audit documentation

This commit is contained in:
2026-08-12 18:30:42 +02:00
parent a9553e9fbf
commit 3d8af3940b
163 changed files with 3421 additions and 1751 deletions
@@ -90,7 +90,7 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
DetectStrategySignals(sortedCandles, sma50Values, sma200Values, rsiValues, signals);
// 4. Detect Geometric Chart Patterns
DetectTrianglePatterns(sortedCandles, patterns, curSym);
DetectChartPatterns(sortedCandles, patterns, curSym);
return (indicators, patterns, signals);
}
@@ -114,7 +114,6 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
{
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)
@@ -139,7 +138,6 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
}
}
// RSI Oversold / Overbought Rebounds
if (rsi14[i].HasValue && rsi14[i - 1].HasValue)
{
if (rsi14[i - 1]!.Value < 30 && rsi14[i]!.Value >= 30)
@@ -166,7 +164,7 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
}
}
private static void DetectTrianglePatterns(List<MarketCandleEntity> sortedCandles, List<ChartPatternDto> patterns, string curSym)
private static void DetectChartPatterns(List<MarketCandleEntity> sortedCandles, List<ChartPatternDto> patterns, string curSym)
{
if (sortedCandles.Count < 20) return;
@@ -210,12 +208,20 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
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);
}
@@ -316,12 +322,6 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
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}",
@@ -333,8 +333,7 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
LowerLine: new List<PatternPointDto>
{
new(slice[idx1].Timestamp, low1),
new(slice[idx2].Timestamp, low2),
new(futureTime, projectedLowerPrice)
new(slice[idx2].Timestamp, low2)
},
ApexTime: null,
BreakoutSignal: new BreakoutSignalDto(
@@ -411,20 +410,13 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
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<PatternPointDto>
{
new(slice[idx1].Timestamp, high1),
new(slice[idx2].Timestamp, high2),
new(futureTime, projectedUpperPrice)
new(slice[idx2].Timestamp, high2)
},
LowerLine: new List<PatternPointDto>
{
@@ -502,20 +494,14 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
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<PatternPointDto>
{
new(slice[lsIdx].Timestamp, ls),
new(slice[rsIdx].Timestamp, rs),
new(futureTime, projectedUpperPrice)
new(slice[headIdx].Timestamp, head),
new(slice[rsIdx].Timestamp, rs)
},
LowerLine: new List<PatternPointDto>
{
@@ -536,114 +522,149 @@ public class TechnicalAnalysisCalculator : ITechnicalAnalysisCalculator
private static void DetectTrianglesInSlice(List<MarketCandleEntity> slice, List<ChartPatternDto> patterns, string curSym)
{
if (slice.Count < 10) return;
if (slice.Count < 15) 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 lookback = 2;
var pHighs = FindPivotHighs(slice, lookback);
var pLows = FindPivotLows(slice, lookback);
int third = slice.Count / 3;
var first = slice.Take(third).ToList();
var last = slice.TakeLast(third).ToList();
if (pHighs.Count < 2 || pLows.Count < 2) return;
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);
// 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];
decimal triangleBaseHeight = Math.Max(0.5m, high1 - low1);
// Verhindere zu nahe beieinander liegende Pivots
if (hIdx2 - hIdx1 < 3 || lIdx2 - lIdx1 < 3) return;
double totalDays = (endTime - startTime).TotalDays;
if (totalDays <= 0) totalDays = 10;
DateTime tH1 = slice[hIdx1].Timestamp;
DateTime tH2 = slice[hIdx2].Timestamp;
DateTime tL1 = slice[lIdx1].Timestamp;
DateTime tL2 = slice[lIdx2].Timestamp;
DateTime apexTime = endTime.AddDays(10);
double mUpper = (double)(high2 - high1) / totalDays;
double mLower = (double)(low2 - low1) / totalDays;
decimal yH1 = slice[hIdx1].High;
decimal yH2 = slice[hIdx2].High;
decimal yL1 = slice[lIdx1].Low;
decimal yL2 = slice[lIdx2].Low;
if (Math.Abs(mUpper - mLower) > 0.00001)
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)
{
double daysToApex = (double)(low1 - high1) / (mUpper - mLower);
if (daysToApex > 0 && daysToApex < 120)
if (!patterns.Any(p => p.Type == "AscendingTriangle"))
{
apexTime = startTime.AddDays(daysToApex);
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));
}
}
}
if (high2 >= high1 * 0.97m && high2 <= high1 * 1.03m && low2 > low1 * 1.01m)
// --- 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)
{
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"))
if (!patterns.Any(p => p.Type == "DescendingTriangle"))
{
var pct = lastPrice > 0m ? ((targetPrice - lastPrice) / lastPrice) * 100m : 0m;
var conf = Math.Round(Math.Max(70m, 93m - (Math.Abs(high1 - high2) / high1) * 600m), 1);
decimal support = (yL1 + yL2) / 2m;
decimal baseHeight = yH1 - support;
decimal targetPrice = Math.Max(0.01m, support - baseHeight);
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(startTime, resistance), new(apexTime, resistance) },
LowerLine: new List<PatternPointDto> { new(startTime, low1), new(apexTime, resistance) },
ApexTime: apexTime,
BreakoutSignal: new BreakoutSignalDto(Time: endTime, Direction: "BUY", TriggerPrice: resistance, TargetPrice: targetPrice, PotentialPercent: pct),
ConfidencePercent: conf));
// 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));
}
}
}
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<PatternPointDto> { new(startTime, high1), new(apexTime, support) },
LowerLine: new List<PatternPointDto> { 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)
// --- 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"))
{
var direction = lastPrice >= (high1 + low1) / 2m ? "BUY" : "SELL";
var targetPrice = direction == "BUY"
? lastPrice + triangleBaseHeight
: Math.Max(0.01m, lastPrice - triangleBaseHeight);
// 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;
var pct = lastPrice > 0m
? (direction == "BUY" ? ((targetPrice - lastPrice) / lastPrice) : ((lastPrice - targetPrice) / lastPrice)) * 100m
: 0m;
if (Math.Abs(denominator) > 0.0001)
{
double daysFromT1ToApex = ((double)(yL1 - yH1) + (mLower * deltaDaysT1)) / denominator;
DateTime apexTime = tH1.AddDays(daysFromT1ToApex);
decimal apexPrice = (high2 + low2) / 2m;
// Apex muss in der Zukunft liegen!
if (apexTime > lastCandle.Timestamp)
{
decimal apexPrice = yH1 + (decimal)(mUpper * daysFromT1ToApex);
decimal baseHeight = Math.Abs(yH1 - yL1);
patterns.Add(new ChartPatternDto(
Type: "SymmetricalTriangle",
Description: $"Symmetrisches Dreieck: Konvergierende Hochs und Tiefs — dynamischer Ausbruch in Trendrichtung erwartet.",
UpperLine: new List<PatternPointDto> { new(startTime, high1), new(apexTime, apexPrice) },
LowerLine: new List<PatternPointDto> { new(startTime, low1), new(apexTime, apexPrice) },
ApexTime: apexTime,
BreakoutSignal: new BreakoutSignalDto(Time: endTime, Direction: direction, TriggerPrice: lastPrice, TargetPrice: targetPrice, PotentialPercent: pct),
ConfidencePercent: 85m));
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));
}
}
}
}
}
@@ -17,7 +17,9 @@ namespace FinlyticTechnicalAnalysis.Services;
public interface ITechnicalAnalysisDbService
{
Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, CancellationToken cancellationToken = default);
Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, string? ticker = null,
CancellationToken cancellationToken = default);
Task<LivePriceDto?> GetLivePriceAsync(string isin, CancellationToken cancellationToken = default);
}
@@ -29,10 +31,7 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
private readonly ITechnicalAnalysisCalculator _calculator;
private readonly ILogger<TechnicalAnalysisDbService> _logger;
// Cache Layer 1: In-Memory Candles Cache (TTL: 15 Minuten)
private static readonly ConcurrentDictionary<string, (List<MarketCandleEntity> Candles, string Symbol, string Currency, DateTime FetchedAt)> _candleCache = new();
// Per-ISIN Semaphores zur Vermeidung von Cache-Stampedes
private static readonly ConcurrentDictionary<string, SemaphoreSlim> _perIsinLocks = new();
private static readonly TimeSpan CandleCacheTtl = TimeSpan.FromMinutes(15);
private static readonly TimeSpan DbCacheTtl = TimeSpan.FromHours(1);
@@ -51,26 +50,30 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
_logger = logger;
}
public async Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, CancellationToken cancellationToken = default)
public async Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, string? ticker = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(isin)) return null;
var cleanIsin = isin.Trim().ToUpperInvariant();
// 1. Layer-1: Fast-Path aus In-Memory Cache (wenn kein forceRefresh)
if (!forceRefresh && _candleCache.TryGetValue(cleanIsin, out var ramEntry) && DateTime.UtcNow - ramEntry.FetchedAt < CandleCacheTtl)
if (!forceRefresh && _candleCache.TryGetValue(cleanIsin, out var ramEntry) &&
DateTime.UtcNow - ramEntry.FetchedAt < CandleCacheTtl &&
(string.IsNullOrWhiteSpace(ticker) || string.Equals(ramEntry.Symbol, ticker, StringComparison.OrdinalIgnoreCase)))
{
_logger.LogDebug("[{Channel}] RAM-Cache Hit for ISIN {Isin}. Merging live price...", "TechnicalAnalysisChannel", cleanIsin);
return await BuildAnalysisWithLivePriceAsync(cleanIsin, ramEntry.Candles, ramEntry.Symbol, ramEntry.Currency, cancellationToken);
}
// Semaphor für ISIN holen (verhindert doppelte parallele Abfragen der gleichen ISIN)
var semaphore = _perIsinLocks.GetOrAdd(cleanIsin, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(cancellationToken);
try
{
// Re-Check nach Lock-Erhalt
if (!forceRefresh && _candleCache.TryGetValue(cleanIsin, out ramEntry) && DateTime.UtcNow - ramEntry.FetchedAt < CandleCacheTtl)
if (!forceRefresh && _candleCache.TryGetValue(cleanIsin, out ramEntry) &&
DateTime.UtcNow - ramEntry.FetchedAt < CandleCacheTtl &&
(string.IsNullOrWhiteSpace(ticker) || string.Equals(ramEntry.Symbol, ticker, StringComparison.OrdinalIgnoreCase)))
{
return await BuildAnalysisWithLivePriceAsync(cleanIsin, ramEntry.Candles, ramEntry.Symbol, ramEntry.Currency, cancellationToken);
}
@@ -78,7 +81,7 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
// 2. Layer-2: Prüfen ob frische Daten in der Datenbank liegen
if (!forceRefresh)
{
var dbDto = await GetFromDbCacheAsync(cleanIsin, cancellationToken);
var dbDto = await GetFromDbCacheAsync(cleanIsin, ticker, cancellationToken);
if (dbDto != null)
{
_logger.LogDebug("[{Channel}] DB-Cache Hit for ISIN {Isin}.", "TechnicalAnalysisChannel", cleanIsin);
@@ -86,13 +89,11 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
}
}
// 3. Cache Miss / ForceRefresh: Vollständige Neuberechnung
return await FullRefreshAsync(cleanIsin, cancellationToken);
return await FullRefreshAsync(cleanIsin, ticker, cancellationToken);
}
finally
{
semaphore.Release();
// Speicher aufräumen, falls Lock nicht mehr genutzt wird
if (semaphore.CurrentCount == 1)
{
_perIsinLocks.TryRemove(cleanIsin, out _);
@@ -105,38 +106,41 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
if (string.IsNullOrWhiteSpace(isin)) return null;
var cleanIsin = isin.Trim().ToUpperInvariant();
var (livePrice, liveBid, liveAsk) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
var (livePrice, liveBid, liveAsk, preChange) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
if (!livePrice.HasValue) return null;
return new LivePriceDto(
cleanIsin,
Math.Round(livePrice.Value, 2),
0m, // Percent change optional
preChange ?? 0m,
liveBid.HasValue ? Math.Round(liveBid.Value, 2) : null,
liveAsk.HasValue ? Math.Round(liveAsk.Value, 2) : null
);
}
private async Task<TechnicalAnalysisDto?> FullRefreshAsync(string cleanIsin, CancellationToken cancellationToken)
private async Task<TechnicalAnalysisDto?> FullRefreshAsync(string cleanIsin, string? requestedTicker, CancellationToken cancellationToken)
{
_logger.LogInformation("[{Channel}] Full refresh for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
_logger.LogInformation("[{Channel}] Full refresh for ISIN {Isin} (RequestedTicker: {Ticker})", "TechnicalAnalysisChannel", cleanIsin, requestedTicker ?? "None");
var tickerTask = _yahooScraper.ResolveTickerFromIsinAsync(cleanIsin, cancellationToken);
var macroTask = FetchMacroDataAsync(cancellationToken);
string? ticker = requestedTicker;
if (string.IsNullOrWhiteSpace(ticker))
{
ticker = await _yahooScraper.ResolveTickerFromIsinAsync(cleanIsin, cancellationToken);
}
await Task.WhenAll(tickerTask, macroTask);
var ticker = await tickerTask;
var querySymbol = !string.IsNullOrEmpty(ticker) ? ticker : cleanIsin;
var (vix, gspc, dxy) = await macroTask;
var yahooResult = await _yahooScraper.FetchHistoricalCandlesWithCurrencyAsync(querySymbol, "1y", "1d", cancellationToken);
// Lade 2y Daten für saubere Indikator-Aufwärmphasen
var yahooResult = await _yahooScraper.FetchHistoricalCandlesWithCurrencyAsync(querySymbol, "2y", "1d", cancellationToken);
var candles = yahooResult.Candles;
var currency = yahooResult.Currency;
if (candles.Count == 0 && querySymbol != cleanIsin)
{
yahooResult = await _yahooScraper.FetchHistoricalCandlesWithCurrencyAsync(cleanIsin, "1y", "1d", cancellationToken);
yahooResult = await _yahooScraper.FetchHistoricalCandlesWithCurrencyAsync(cleanIsin, "2y", "1d", cancellationToken);
candles = yahooResult.Candles;
currency = yahooResult.Currency;
}
@@ -147,67 +151,60 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
return null;
}
// In RAM-Cache sichern
_candleCache[cleanIsin] = (candles.Select(CloneCandle).ToList(), querySymbol, currency, DateTime.UtcNow);
// Live-Preis einpflegen
await MergeLivePriceAsync(cleanIsin, candles, querySymbol, cancellationToken);
await MergeLivePriceAsync(cleanIsin, candles, querySymbol, currency, cancellationToken);
var resultDto = BuildDto(cleanIsin, querySymbol, currency, candles, vix, gspc, dxy);
// Synchron und sicher in DB persistieren
await PersistToDbCacheAsync(cleanIsin, querySymbol, resultDto, cancellationToken);
return resultDto;
}
private async Task<TechnicalAnalysisDto> BuildAnalysisWithLivePriceAsync(
string cleanIsin, List<MarketCandleEntity> cachedCandles, string querySymbol, string currency, CancellationToken cancellationToken)
string cleanIsin, List<MarketCandleEntity> cachedCandles, string querySymbol, string currency,
CancellationToken cancellationToken)
{
var candles = cachedCandles.Select(CloneCandle).ToList();
var livePriceTask = FetchLivePriceAsync(cleanIsin, cancellationToken);
var macroTask = FetchMacroDataAsync(cancellationToken);
await Task.WhenAll(livePriceTask, macroTask);
var (livePrice, liveBid, liveAsk) = await livePriceTask;
var (livePrice, liveBid, liveAsk, preChange) = await livePriceTask; // Task-Result direkt nutzen
var (vix, gspc, dxy) = await macroTask;
if (livePrice.HasValue && livePrice.Value > 0m)
{
var today = DateTime.UtcNow.Date;
var lastCandle = candles.LastOrDefault(c => c.Timestamp.Date == today);
if (lastCandle != null)
{
lastCandle.Close = livePrice.Value;
lastCandle.High = Math.Max(lastCandle.High, livePrice.Value);
lastCandle.Low = Math.Min(lastCandle.Low, livePrice.Value);
if (liveBid.HasValue) lastCandle.Bid = liveBid.Value;
if (liveAsk.HasValue) lastCandle.Ask = liveAsk.Value;
}
else
{
var prevClose = candles.LastOrDefault()?.Close ?? livePrice.Value;
candles.Add(new MarketCandleEntity
{
Symbol = querySymbol, Interval = "1d", Timestamp = today,
Open = prevClose, High = Math.Max(prevClose, livePrice.Value),
Low = Math.Min(prevClose, livePrice.Value), Close = livePrice.Value,
Volume = 1000, Bid = liveBid, Ask = liveAsk
});
}
}
ApplyLivePriceToCandles(cleanIsin, candles, querySymbol, currency, livePrice, liveBid, liveAsk);
return BuildDto(cleanIsin, querySymbol, currency, candles, vix, gspc, dxy);
}
private async Task MergeLivePriceAsync(string cleanIsin, List<MarketCandleEntity> candles, string querySymbol, CancellationToken cancellationToken)
private async Task MergeLivePriceAsync(string cleanIsin, List<MarketCandleEntity> candles, string querySymbol, string currency,
CancellationToken cancellationToken)
{
var (livePrice, liveBid, liveAsk, _) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
ApplyLivePriceToCandles(cleanIsin, candles, querySymbol, currency, livePrice, liveBid, liveAsk);
}
private void ApplyLivePriceToCandles(
string cleanIsin, List<MarketCandleEntity> candles, string querySymbol, string candleCurrency,
decimal? livePrice, decimal? liveBid, decimal? liveAsk)
{
var (livePrice, liveBid, liveAsk) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
if (!livePrice.HasValue || livePrice.Value <= 0m) return;
// Währungsschutz: Trade Republic liefert IMMER EUR.
// Wenn die Kerzenhistorie USD ist (z.B. AAPL), darf der EUR-Livepreis NICHT direkt injiziert werden!
if (candleCurrency.Equals("USD", StringComparison.OrdinalIgnoreCase) && !cleanIsin.StartsWith("DE") && !cleanIsin.StartsWith("AT"))
{
_logger.LogDebug("[{Channel}] Skipping direct EUR live price injection for USD asset {Isin}", "TechnicalAnalysisChannel", cleanIsin);
return;
}
var today = DateTime.UtcNow.Date;
var lastCandle = candles.LastOrDefault(c => c.Timestamp.Date == today);
var lastCandle = candles.LastOrDefault(c => c.Timestamp.Date == today) ?? candles.LastOrDefault();
if (lastCandle != null)
{
lastCandle.Close = livePrice.Value;
@@ -216,39 +213,42 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
if (liveBid.HasValue) lastCandle.Bid = liveBid.Value;
if (liveAsk.HasValue) lastCandle.Ask = liveAsk.Value;
}
else
{
var prevClose = candles.LastOrDefault()?.Close ?? livePrice.Value;
candles.Add(new MarketCandleEntity
{
Symbol = querySymbol, Interval = "1d", Timestamp = today,
Open = prevClose, High = Math.Max(prevClose, livePrice.Value),
Low = Math.Min(prevClose, livePrice.Value), Close = livePrice.Value,
Volume = 1000, Bid = liveBid, Ask = liveAsk
});
}
}
private async Task<(decimal? livePrice, decimal? liveBid, decimal? liveAsk)> FetchLivePriceAsync(string cleanIsin, CancellationToken cancellationToken)
private async Task<(decimal? livePrice, decimal? liveBid, decimal? liveAsk, decimal? preChange)> FetchLivePriceAsync(
string cleanIsin, CancellationToken cancellationToken)
{
decimal? livePrice = null;
decimal? liveBid = null;
decimal? liveAsk = null;
decimal? preChange = null;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(1500); // Maximal 1.5 Sekunden Wartezeit auf Ticker
cts.CancelAfter(1500);
var trTask = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
int? subId = await _trService.SubscribeRealtimeTickerAsync(cleanIsin, tick =>
{
if (tick.Last != null && tick.Last.PriceValue > 0m)
decimal? effectivePrice = tick.Bid?.PriceValue > 0m
? tick.Bid.PriceValue
: (tick.Last?.PriceValue > 0m ? tick.Last.PriceValue : null);
if (effectivePrice.HasValue)
{
livePrice = tick.Last.PriceValue;
livePrice = tick.Last?.PriceValue ?? effectivePrice.Value;
liveBid = tick.Bid?.PriceValue;
liveAsk = tick.Ask?.PriceValue;
decimal prePrice = tick.Pre?.PriceValue ?? 0m;
if (prePrice > 0m)
{
preChange = Math.Round(((effectivePrice.Value - prePrice) / prePrice) * 100m, 2);
}
trTask.TrySetResult(true);
}
}, cts.Token);
@@ -260,7 +260,7 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
await trTask.Task.WaitAsync(cts.Token);
}
catch (OperationCanceledException) { }
await _trService.UnsubscribeRealtimeTickerAsync(subId.Value);
}
}
@@ -269,10 +269,11 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
_logger.LogWarning(ex, "[{Channel}] Real-time price fetch skipped for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
}
return (livePrice, liveBid, liveAsk);
return (livePrice, liveBid, liveAsk, preChange);
}
private async Task<(MacroDataEntity vix, MacroDataEntity gspc, MacroDataEntity dxy)> FetchMacroDataAsync(CancellationToken cancellationToken)
private async Task<(MacroDataEntity vix, MacroDataEntity gspc, MacroDataEntity dxy)> FetchMacroDataAsync(
CancellationToken cancellationToken)
{
var vixTask = _yahooScraper.FetchMacroTickerAsync("^VIX", cancellationToken);
var gspcTask = _yahooScraper.FetchMacroTickerAsync("^GSPC", cancellationToken);
@@ -287,7 +288,8 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
return (vix, gspc, dxy);
}
private TechnicalAnalysisDto BuildDto(string cleanIsin, string querySymbol, string currency, List<MarketCandleEntity> candles, MacroDataEntity vix, MacroDataEntity gspc, MacroDataEntity dxy)
private TechnicalAnalysisDto BuildDto(string cleanIsin, string querySymbol, string currency,
List<MarketCandleEntity> candles, MacroDataEntity vix, MacroDataEntity gspc, MacroDataEntity dxy)
{
var vixRegime = vix.Value > 25m ? "HighVolatility" : (vix.Value > 18m ? "Moderate" : "LowVolatility");
var summaryText = $"Markt-Vola (VIX: {vix.Value:F1}) ist {vixRegime}. S&P 500 Trend ist {gspc.TrendState}. DXY: {dxy.Value:F1}.";
@@ -312,7 +314,7 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
MarketRegime: marketRegime, Currency: currency);
}
private async Task<TechnicalAnalysisDto?> GetFromDbCacheAsync(string cleanIsin, CancellationToken cancellationToken)
private async Task<TechnicalAnalysisDto?> GetFromDbCacheAsync(string cleanIsin, string? requestedTicker, CancellationToken cancellationToken)
{
try
{
@@ -324,6 +326,10 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
if (cached != null && DateTime.UtcNow - cached.CalculatedAt < DbCacheTtl)
{
if (!string.IsNullOrWhiteSpace(requestedTicker) && !string.Equals(cached.Ticker, requestedTicker, StringComparison.OrdinalIgnoreCase))
{
return null; // Ticker mismatch, force refresh required
}
return JsonSerializer.Deserialize<TechnicalAnalysisDto>(cached.AnalysisJson);
}
}
@@ -335,7 +341,8 @@ public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
return null;
}
private async Task PersistToDbCacheAsync(string cleanIsin, string querySymbol, TechnicalAnalysisDto dto, CancellationToken cancellationToken)
private async Task PersistToDbCacheAsync(string cleanIsin, string querySymbol, TechnicalAnalysisDto dto,
CancellationToken cancellationToken)
{
try
{