feat(TA): update technical analysis service

This commit is contained in:
2026-08-09 21:01:42 +02:00
parent 05d55a324c
commit c74a4456af
18 changed files with 2288 additions and 0 deletions
@@ -0,0 +1,100 @@
using FinlyticTechnicalAnalysis.Database;
using FinlyticTechnicalAnalysis.Entities;
using Microsoft.EntityFrameworkCore;
namespace FinlyticTechnicalAnalysis.Services;
public interface ISettingsDbService
{
/// <summary>
/// Gets the settings.
/// </summary>
Task<TaSettingsEntity> GetSettingsAsync();
/// <summary>
/// Saves the settings.
/// </summary>
Task<TaSettingsEntity> SaveSettingsAsync(TaSettingsEntity settings);
/// <summary>
/// Updates settings from a dictionary.
/// </summary>
Task UpdateSettingsFromDictionaryAsync(Dictionary<string, string> dictionary);
}
public class SettingsDbService : ISettingsDbService
{
private readonly TechnicalAnalysisDbContext _context;
public SettingsDbService(TechnicalAnalysisDbContext context)
{
_context = context;
}
/// <summary>
/// Gets the settings.
/// </summary>
public async Task<TaSettingsEntity> GetSettingsAsync()
{
var settings = await _context.Settings.AsNoTracking().FirstOrDefaultAsync();
if (settings == null)
{
settings = new TaSettingsEntity { Id = Guid.NewGuid() };
_context.Settings.Add(settings);
await _context.SaveChangesAsync();
_context.ChangeTracker.Clear();
}
return settings;
}
/// <summary>
/// Saves the settings.
/// </summary>
public async Task<TaSettingsEntity> SaveSettingsAsync(TaSettingsEntity settings)
{
var existing = await _context.Settings.FirstOrDefaultAsync();
if (existing == null)
{
if (settings.Id == Guid.Empty) settings.Id = Guid.NewGuid();
_context.Settings.Add(settings);
}
else
{
existing.EmaShortPeriod = settings.EmaShortPeriod;
existing.SmaMediumPeriod = settings.SmaMediumPeriod;
existing.SmaLongPeriod = settings.SmaLongPeriod;
existing.RsiOverboughtLimit = settings.RsiOverboughtLimit;
existing.RsiOversoldLimit = settings.RsiOversoldLimit;
existing.SupertrendMultiplier = settings.SupertrendMultiplier;
existing.UpdatedAt = settings.UpdatedAt;
_context.Settings.Update(existing);
}
await _context.SaveChangesAsync();
return settings;
}
/// <summary>
/// Updates settings from a dictionary.
/// </summary>
public async Task UpdateSettingsFromDictionaryAsync(Dictionary<string, string> dictionary)
{
var settings = await GetSettingsAsync();
foreach (var (key, value) in dictionary)
{
if (string.Equals(key, "EmaShortPeriod", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out var esp))
settings.EmaShortPeriod = esp;
else if (string.Equals(key, "SmaMediumPeriod", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out var smp))
settings.SmaMediumPeriod = smp;
else if (string.Equals(key, "SmaLongPeriod", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out var slp))
settings.SmaLongPeriod = slp;
else if (string.Equals(key, "RsiOverboughtLimit", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, out var rsiOb))
settings.RsiOverboughtLimit = rsiOb;
else if (string.Equals(key, "RsiOversoldLimit", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, out var rsiOs))
settings.RsiOversoldLimit = rsiOs;
else if (string.Equals(key, "SupertrendMultiplier", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, out var stm))
settings.SupertrendMultiplier = stm;
}
settings.UpdatedAt = DateTime.UtcNow;
await SaveSettingsAsync(settings);
}
}
@@ -0,0 +1,650 @@
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
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<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];
// 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<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();
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<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);
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<PatternPointDto>
{
new(slice[idx1].Timestamp, neckline),
new(futureTime, neckline)
},
LowerLine: new List<PatternPointDto>
{
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<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);
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)
},
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);
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)
},
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 < 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<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));
}
}
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)
{
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<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));
}
}
}
}
@@ -0,0 +1,378 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FinlyticCore.Dtos.TechnicalAnalysis;
using FinlyticCore.Services.TradeRepublic;
using FinlyticTechnicalAnalysis.Database;
using FinlyticTechnicalAnalysis.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FinlyticTechnicalAnalysis.Services;
public interface ITechnicalAnalysisDbService
{
Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, CancellationToken cancellationToken = default);
Task<LivePriceDto?> GetLivePriceAsync(string isin, CancellationToken cancellationToken = default);
}
public class TechnicalAnalysisDbService : ITechnicalAnalysisDbService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IYahooMarketDataScraper _yahooScraper;
private readonly ITradeRepublicService _trService;
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);
public TechnicalAnalysisDbService(
IServiceScopeFactory scopeFactory,
IYahooMarketDataScraper yahooScraper,
ITradeRepublicService trService,
ITechnicalAnalysisCalculator calculator,
ILogger<TechnicalAnalysisDbService> logger)
{
_scopeFactory = scopeFactory;
_yahooScraper = yahooScraper;
_trService = trService;
_calculator = calculator;
_logger = logger;
}
public async Task<TechnicalAnalysisDto?> GetAnalysisAsync(string isin, bool forceRefresh = false, 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)
{
_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)
{
return await BuildAnalysisWithLivePriceAsync(cleanIsin, ramEntry.Candles, ramEntry.Symbol, ramEntry.Currency, cancellationToken);
}
// 2. Layer-2: Prüfen ob frische Daten in der Datenbank liegen
if (!forceRefresh)
{
var dbDto = await GetFromDbCacheAsync(cleanIsin, cancellationToken);
if (dbDto != null)
{
_logger.LogDebug("[{Channel}] DB-Cache Hit for ISIN {Isin}.", "TechnicalAnalysisChannel", cleanIsin);
return dbDto;
}
}
// 3. Cache Miss / ForceRefresh: Vollständige Neuberechnung
return await FullRefreshAsync(cleanIsin, cancellationToken);
}
finally
{
semaphore.Release();
// Speicher aufräumen, falls Lock nicht mehr genutzt wird
if (semaphore.CurrentCount == 1)
{
_perIsinLocks.TryRemove(cleanIsin, out _);
}
}
}
public async Task<LivePriceDto?> GetLivePriceAsync(string isin, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(isin)) return null;
var cleanIsin = isin.Trim().ToUpperInvariant();
var (livePrice, liveBid, liveAsk) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
if (!livePrice.HasValue) return null;
return new LivePriceDto(
cleanIsin,
Math.Round(livePrice.Value, 2),
0m, // Percent change optional
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)
{
_logger.LogInformation("[{Channel}] Full refresh for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
var tickerTask = _yahooScraper.ResolveTickerFromIsinAsync(cleanIsin, cancellationToken);
var macroTask = FetchMacroDataAsync(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);
var candles = yahooResult.Candles;
var currency = yahooResult.Currency;
if (candles.Count == 0 && querySymbol != cleanIsin)
{
yahooResult = await _yahooScraper.FetchHistoricalCandlesWithCurrencyAsync(cleanIsin, "1y", "1d", cancellationToken);
candles = yahooResult.Candles;
currency = yahooResult.Currency;
}
if (candles.Count == 0)
{
_logger.LogWarning("[{Channel}] No candles retrieved for {Symbol}", "TechnicalAnalysisChannel", querySymbol);
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);
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)
{
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 (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
});
}
}
return BuildDto(cleanIsin, querySymbol, currency, candles, vix, gspc, dxy);
}
private async Task MergeLivePriceAsync(string cleanIsin, List<MarketCandleEntity> candles, string querySymbol, CancellationToken cancellationToken)
{
var (livePrice, liveBid, liveAsk) = await FetchLivePriceAsync(cleanIsin, cancellationToken);
if (!livePrice.HasValue || livePrice.Value <= 0m) return;
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
});
}
}
private async Task<(decimal? livePrice, decimal? liveBid, decimal? liveAsk)> FetchLivePriceAsync(string cleanIsin, CancellationToken cancellationToken)
{
decimal? livePrice = null;
decimal? liveBid = null;
decimal? liveAsk = null;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(1500); // Maximal 1.5 Sekunden Wartezeit auf Ticker
var trTask = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
int? subId = await _trService.SubscribeRealtimeTickerAsync(cleanIsin, tick =>
{
if (tick.Last != null && tick.Last.PriceValue > 0m)
{
livePrice = tick.Last.PriceValue;
liveBid = tick.Bid?.PriceValue;
liveAsk = tick.Ask?.PriceValue;
trTask.TrySetResult(true);
}
}, cts.Token);
if (subId.HasValue)
{
try
{
await trTask.Task.WaitAsync(cts.Token);
}
catch (OperationCanceledException) { }
await _trService.UnsubscribeRealtimeTickerAsync(subId.Value);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[{Channel}] Real-time price fetch skipped for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
}
return (livePrice, liveBid, liveAsk);
}
private async Task<(MacroDataEntity vix, MacroDataEntity gspc, MacroDataEntity dxy)> FetchMacroDataAsync(CancellationToken cancellationToken)
{
var vixTask = _yahooScraper.FetchMacroTickerAsync("^VIX", cancellationToken);
var gspcTask = _yahooScraper.FetchMacroTickerAsync("^GSPC", cancellationToken);
var dxyTask = _yahooScraper.FetchMacroTickerAsync("DX-Y.NY", cancellationToken);
await Task.WhenAll(vixTask, gspcTask, dxyTask);
var vix = await vixTask ?? new MacroDataEntity { Symbol = "^VIX", Value = 18.5m, TrendState = "Moderate" };
var gspc = await gspcTask ?? new MacroDataEntity { Symbol = "^GSPC", Value = 5500m, TrendState = "Bullish" };
var dxy = await dxyTask ?? new MacroDataEntity { Symbol = "DX-Y.NY", Value = 104.2m, TrendState = "Neutral" };
return (vix, gspc, 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}.";
var marketRegime = new MarketRegimeDto(
VixValue: vix.Value, VixRegime: vixRegime,
MarketTrend: gspc.TrendState, DxyValue: dxy.Value,
DxyState: dxy.TrendState == "Bullish" ? "DollarStrengthening" : "DollarWeakening",
SummaryText: summaryText);
var (indicators, patterns, signals) = _calculator.CalculateAnalysis(candles, currency);
var candleDtos = candles.Select(c => new CandleDto(
Timestamp: c.Timestamp, Open: c.Open, High: c.High,
Low: c.Low, Close: c.Close, Volume: c.Volume,
Bid: c.Bid, Ask: c.Ask)).ToList();
return new TechnicalAnalysisDto(
Isin: cleanIsin, Ticker: querySymbol, CompanyName: querySymbol,
LastUpdated: DateTime.UtcNow, Candles: candleDtos,
Indicators: indicators, Patterns: patterns, Signals: signals,
MarketRegime: marketRegime, Currency: currency);
}
private async Task<TechnicalAnalysisDto?> GetFromDbCacheAsync(string cleanIsin, CancellationToken cancellationToken)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<TechnicalAnalysisDbContext>();
var cached = await db.CachedAnalyses
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Isin == cleanIsin, cancellationToken);
if (cached != null && DateTime.UtcNow - cached.CalculatedAt < DbCacheTtl)
{
return JsonSerializer.Deserialize<TechnicalAnalysisDto>(cached.AnalysisJson);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[{Channel}] Failed to read DB cache for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
}
return null;
}
private async Task PersistToDbCacheAsync(string cleanIsin, string querySymbol, TechnicalAnalysisDto dto, CancellationToken cancellationToken)
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<TechnicalAnalysisDbContext>();
var json = JsonSerializer.Serialize(dto);
var existing = await db.CachedAnalyses.FirstOrDefaultAsync(c => c.Isin == cleanIsin, cancellationToken);
if (existing != null)
{
existing.Ticker = querySymbol;
existing.AnalysisJson = json;
existing.CalculatedAt = DateTime.UtcNow;
}
else
{
db.CachedAnalyses.Add(new CachedAnalysisEntity
{
Isin = cleanIsin,
Ticker = querySymbol,
AnalysisJson = json,
CalculatedAt = DateTime.UtcNow
});
}
await db.SaveChangesAsync(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "[{Channel}] Failed to persist TA DB cache for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
}
}
private static MarketCandleEntity CloneCandle(MarketCandleEntity c) => new()
{
Symbol = c.Symbol, Interval = c.Interval, Timestamp = c.Timestamp,
Open = c.Open, High = c.High, Low = c.Low, Close = c.Close,
Volume = c.Volume, Bid = c.Bid, Ask = c.Ask
};
}
@@ -0,0 +1,227 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FinlyticCore.Services.Yahoo;
using FinlyticTechnicalAnalysis.Entities;
using Microsoft.Extensions.Logging;
namespace FinlyticTechnicalAnalysis.Services;
public record YahooCandlesResult(
List<MarketCandleEntity> Candles,
string Currency
);
public interface IYahooMarketDataScraper
{
/// <summary>
/// Resolves ticker from ISIN.
/// </summary>
Task<string?> ResolveTickerFromIsinAsync(string isin, CancellationToken cancellationToken = default);
/// <summary>
/// Fetches historical candles.
/// </summary>
Task<List<MarketCandleEntity>> FetchHistoricalCandlesAsync(string symbol, string range = "1y", string interval = "1d", CancellationToken cancellationToken = default);
/// <summary>
/// Fetches historical candles with currency.
/// </summary>
Task<YahooCandlesResult> FetchHistoricalCandlesWithCurrencyAsync(string symbol, string range = "1y", string interval = "1d", CancellationToken cancellationToken = default);
/// <summary>
/// Fetches macro ticker.
/// </summary>
Task<MacroDataEntity?> FetchMacroTickerAsync(string symbol, CancellationToken cancellationToken = default);
}
public class YahooMarketDataScraper : IYahooMarketDataScraper
{
private readonly YahooFinanceClient _yahooClient;
private readonly ILogger<YahooMarketDataScraper> _logger;
public YahooMarketDataScraper(YahooFinanceClient yahooClient, ILogger<YahooMarketDataScraper> logger)
{
_yahooClient = yahooClient;
_logger = logger;
}
/// <summary>
/// Resolves ticker from ISIN using Yahoo Search API.
/// </summary>
public async Task<string?> ResolveTickerFromIsinAsync(string isin, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(isin)) return null;
var cleanIsin = isin.Trim().ToUpperInvariant();
if (cleanIsin.Contains('.'))
{
return cleanIsin;
}
try
{
var searchResult = await _yahooClient.SearchAsync(cleanIsin, quotesCount: 10, newsCount: 0, cancellationToken);
if (searchResult?.Quotes != null && searchResult.Quotes.Count > 0)
{
var symbolList = searchResult.Quotes
.Select(q => q.Symbol)
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => s!)
.ToList();
if (symbolList.Count > 0)
{
if (cleanIsin.StartsWith("US", StringComparison.OrdinalIgnoreCase))
{
var noDotSymbol = symbolList.FirstOrDefault(s => !s.Contains('.'));
if (noDotSymbol != null) return noDotSymbol;
}
return symbolList[0];
}
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[{Channel}] Failed to resolve Yahoo ticker for ISIN {Isin}", "TechnicalAnalysisChannel", cleanIsin);
}
return null;
}
/// <summary>
/// Fetches historical candles.
/// </summary>
public async Task<List<MarketCandleEntity>> FetchHistoricalCandlesAsync(string symbol, string range = "1y", string interval = "1d", CancellationToken cancellationToken = default)
{
var result = await FetchHistoricalCandlesWithCurrencyAsync(symbol, range, interval, cancellationToken);
return result.Candles;
}
/// <summary>
/// Fetches historical candles with currency metadata using authenticated Crumb/Cookie flow.
/// </summary>
public async Task<YahooCandlesResult> FetchHistoricalCandlesWithCurrencyAsync(string symbol, string range = "1y", string interval = "1d", CancellationToken cancellationToken = default)
{
var results = new List<MarketCandleEntity>();
string detectedCurrency = FallbackCurrencyBySymbol(symbol);
if (string.IsNullOrWhiteSpace(symbol)) return new YahooCandlesResult(results, detectedCurrency);
try
{
var chartDto = await _yahooClient.GetChartAsync(symbol, range, interval, cancellationToken);
var resultObj = chartDto?.Chart?.Result?.FirstOrDefault();
if (resultObj == null)
{
_logger.LogWarning("[{Channel}] No chart data returned from Yahoo Client for symbol {Symbol}", "TechnicalAnalysisChannel", symbol);
return new YahooCandlesResult(results, detectedCurrency);
}
// Extract currency metadata
if (!string.IsNullOrWhiteSpace(resultObj.Meta?.Currency))
{
detectedCurrency = resultObj.Meta.Currency.ToUpperInvariant();
}
var timestamps = resultObj.Timestamp;
var quote = resultObj.Indicators?.Quote?.FirstOrDefault();
if (timestamps == null || quote == null || timestamps.Count == 0)
{
return new YahooCandlesResult(results, detectedCurrency);
}
var opens = quote.Open ?? [];
var highs = quote.High ?? [];
var lows = quote.Low ?? [];
var closes = quote.Close ?? [];
var volumes = quote.Volume ?? [];
for (int i = 0; i < timestamps.Count; i++)
{
var dt = DateTimeOffset.FromUnixTimeSeconds(timestamps[i]).UtcDateTime;
var open = i < opens.Count && opens[i].HasValue ? (decimal)opens[i]!.Value : 0m;
var high = i < highs.Count && highs[i].HasValue ? (decimal)highs[i]!.Value : open;
var low = i < lows.Count && lows[i].HasValue ? (decimal)lows[i]!.Value : open;
var close = i < closes.Count && closes[i].HasValue ? (decimal)closes[i]!.Value : open;
var vol = i < volumes.Count && volumes[i].HasValue ? (long)volumes[i]!.Value : 0L;
// Skip invalid or empty weekend/holiday records
if (close <= 0m && open <= 0m) continue;
results.Add(new MarketCandleEntity
{
Symbol = symbol.ToUpperInvariant(),
Interval = interval,
Timestamp = dt,
Open = open,
High = Math.Max(high, Math.Max(open, close)),
Low = Math.Min(low, Math.Min(open, close)),
Close = close,
Volume = vol
});
}
_logger.LogInformation("[{Channel}] Successfully fetched {Count} candles for {Symbol} ({Range}, {Interval}, Currency: {Currency})",
"TechnicalAnalysisChannel", results.Count, symbol, range, interval, detectedCurrency);
}
catch (Exception ex)
{
_logger.LogError(ex, "[{Channel}] Error fetching historical candles for {Symbol}", "TechnicalAnalysisChannel", symbol);
}
return new YahooCandlesResult(results, detectedCurrency);
}
/// <summary>
/// Fetches macro ticker data (e.g., ^VIX, ^GSPC, DX-Y.NY).
/// </summary>
public async Task<MacroDataEntity?> FetchMacroTickerAsync(string symbol, CancellationToken cancellationToken = default)
{
var candles = await FetchHistoricalCandlesAsync(symbol, "5d", "1d", cancellationToken);
if (candles.Count == 0) return null;
var lastCandle = candles.Last();
var prevCandle = candles.Count > 1 ? candles[^2] : lastCandle;
var trendState = lastCandle.Close >= prevCandle.Close ? "Bullish" : "Bearish";
if (symbol == "^VIX")
{
trendState = lastCandle.Close > 25m ? "HighVolatility" : (lastCandle.Close > 18m ? "Moderate" : "LowVolatility");
}
return new MacroDataEntity
{
Symbol = symbol,
Value = lastCandle.Close,
PreviousClose = prevCandle.Close,
TrendState = trendState,
LastUpdatedAt = DateTime.UtcNow
};
}
private static string FallbackCurrencyBySymbol(string symbol)
{
if (string.IsNullOrWhiteSpace(symbol)) return "EUR";
if (symbol.EndsWith(".DE", StringComparison.OrdinalIgnoreCase) ||
symbol.EndsWith(".SG", StringComparison.OrdinalIgnoreCase) ||
symbol.EndsWith(".VI", StringComparison.OrdinalIgnoreCase) ||
symbol.EndsWith(".F", StringComparison.OrdinalIgnoreCase))
{
return "EUR";
}
if (!symbol.Contains('.'))
{
return "USD";
}
return "EUR";
}
}