public class IndicatorParameters
{
public int EMAFastPeriod { get; set; }
public int EMASlowPeriod { get; set; }
public int RSIPeriod { get; set; }
public int ATRPeriod { get; set; }
}
public class ForexAnalysisService
{
// Variable statique pour suivre le drawdown actuel
private static double currentDrawdown = 0;
public static async Task<List<PairAnalysisResult>> AnalyseAsync(ForexAnalysisRequest request, RiskManagementParameters riskParams)
{
ConcurrentDictionary<string, PairAnalysisResult> results = new ConcurrentDictionary<string, PairAnalysisResult>();
int maxDegreeOfParallelism = 5;
SemaphoreSlim semaphore = new SemaphoreSlim(maxDegreeOfParallelism);
List<Task> tasks = new List<Task>();
foreach (var pair in request.Forex)
{
await semaphore.WaitAsync();
var task = Task.Run(async () =>
{
try
{
// Vérifier si le drawdown maximal a été atteint
if (currentDrawdown >= riskParams.MaxDrawdownPercent)
{
Console.WriteLine("Drawdown maximal atteint. Arrêt des nouvelles positions.");
return;
}
var intervalDataMap = new Dictionary<string, List<Candle>>();
// Charger les données pour les intervalles récupérés de l'API
foreach (var intervalConfig in request.IntervalConfig)
{
if (intervalConfig.FetchFromAPI)
{
string interval = intervalConfig.Interval;
List<Candle> data = await LoadForexDataAsync(pair, interval);
await Task.Delay(2000); // Délai pour respecter les limitations de l'API
if (data == null || data.Count == 0) continue;
intervalDataMap[interval] = data;
}
}
// Calculer les intervalles non récupérés de l'API
foreach (var intervalConfig in request.IntervalConfig)
{
if (!intervalConfig.FetchFromAPI)
{
string interval = intervalConfig.Interval;
intervalDataMap[interval] = CalculateHigherTimeFrameData(interval, intervalDataMap);
}
}
// Effectuer l'analyse en fonction des intervalles disponibles
var analysisResult = PerformAnalysis(pair, intervalDataMap, riskParams);
if (analysisResult != null)
{
results[pair] = analysisResult;
}
}
finally
{
semaphore.Release();
}
});
tasks.Add(task);
}
await Task.WhenAll(tasks);
return results.Values
.OrderByDescending(oo => oo.Scoring)
.ToList();
}
// Fonction pour effectuer l'analyse sur une paire donnée
private static PairAnalysisResult PerformAnalysis(string pair, Dictionary<string, List<Candle>> intervalDataMap, RiskManagementParameters riskParams)
{
if (intervalDataMap.Count == 0)
return null;
// Liste pour stocker les scores et les indicateurs pour chaque intervalle
var scoredIntervals = new List<(double Score, double Weight, string Interval, double LastClose, Dictionary<string, double> Indicators)>();
foreach (var interval in intervalDataMap.Keys)
{
var data = intervalDataMap[interval];
var indicatorParams = GetIndicatorParametersForInterval(interval);
var indicators = CalculateIndicators(data, indicatorParams); // Utilisation des paramètres spécifiques au timeframe
double score = CalculateScore(indicators);
double weight = GetIntervalWeight(interval);
scoredIntervals.Add((Score: score, Weight: weight, Interval: interval, LastClose: data.Last().Close, Indicators: indicators));
}
// Calcul du score moyen pondéré
double totalWeightedScore = scoredIntervals.Sum(s => s.Score * s.Weight);
double totalWeight = scoredIntervals.Sum(s => s.Weight);
double weightedAverageScore = totalWeightedScore / totalWeight * 10; // Échelle de -10 à +10
// Déterminer la tendance majoritaire basée sur les croisements EMA sur tous les intervalles
int bullishTrendCount = scoredIntervals.Count(s => s.Indicators["EMA_Fast"] > s.Indicators["EMA_Slow"]);
int bearishTrendCount = scoredIntervals.Count - bullishTrendCount;
string majorityTrend = bullishTrendCount > bearishTrendCount ? "Haussière" : "Baissière";
// Calcul du Entry Point (EP) en utilisant le timeframe le plus court
var shortTermInterval = scoredIntervals.OrderBy(s => GetIntervalWeight(s.Interval)).First();
var shortTermIndicators = shortTermInterval.Indicators;
double entryPoint = shortTermInterval.LastClose;
// Vérifier le signal d'entrée basé sur le croisement EMA et la confirmation RSI
bool entrySignal = false;
if (majorityTrend == "Haussière")
{
// Pour les positions longues
entrySignal = shortTermIndicators["EMA_Fast"] > shortTermIndicators["EMA_Slow"] &&
shortTermIndicators["RSI"] < 70; // Éviter le surachat
}
else
{
// Pour les positions courtes
entrySignal = shortTermIndicators["EMA_Fast"] < shortTermIndicators["EMA_Slow"] &&
shortTermIndicators["RSI"] > 30; // Éviter la survente
}
if (!entrySignal)
{
// Pas de signal d'entrée valide
return null;
}
// Calcul du Take Profit (TP) et du Stop Loss (SL) en utilisant l'ATR pour la volatilité
var middleInterval = scoredIntervals.OrderBy(s => GetIntervalWeight(s.Interval)).ElementAt(scoredIntervals.Count / 2);
double volatility = middleInterval.Indicators["ATR"]; // Utiliser l'ATR calculé précédemment
double stopLoss = volatility * 1; // SL à 1 * ATR
double takeProfit = stopLoss * 2; // TP à un ratio risque/récompense de 1:2
// Calcul de la taille de la position en fonction du risque maximal par trade
double maxRiskPerTrade = riskParams.AccountBalance * (riskParams.MaxRiskPerTradePercent / 100);
// Calcul du Take Profit (TP) et du Stop Loss (SL) en prix
double stopLossPrice = majorityTrend == "Haussière" ? entryPoint - stopLoss : entryPoint + stopLoss;
double takeProfitPrice = majorityTrend == "Haussière" ? entryPoint + takeProfit : entryPoint - takeProfit;
// Calcul de la taille de la position en lots
double positionSizeInLots = CalculatePositionSizeInLots(pair, entryPoint, stopLossPrice, riskParams);
// Retourner le résultat de l'analyse
// Retourner le résultat de l'analyse
return new PairAnalysisResult
{
Pair = pair,
TakeProfit = takeProfitPrice,
StopLoss = stopLossPrice,
MajorityDirection = majorityTrend,
EntryPoint = entryPoint,
Scoring = weightedAverageScore,
PositionSize = Math.Round(positionSizeInLots, 2) // Arrondi à 2 décimales
};
}
private static double CalculatePositionSizeInLots(string pair, double entryPrice, double stopLossPrice, RiskManagementParameters riskParams)
{
// Calcul du risque maximal par trade en valeur monétaire
double maxRiskPerTrade = riskParams.AccountBalance * (riskParams.MaxRiskPerTradePercent / 100);
// Déterminer le pipFactor en fonction de la paire
int pipFactor = pair.Contains("JPY") ? 100 : 10000;
// Calcul du stop loss en pips
double stopLossPips = Math.Abs(entryPrice - stopLossPrice) * pipFactor;
// Valeur du pip pour 1 lot standard
double pipValuePerStandardLot = CalculatePipValuePerStandardLot(pair, entryPrice);
// Calcul de la taille de la position en lots
double positionSizeInLots = maxRiskPerTrade / (stopLossPips * pipValuePerStandardLot);
return positionSizeInLots;
}
// Méthode pour calculer la valeur du pip pour 1 lot standard
private static double CalculatePipValuePerStandardLot(string pair, double entryPrice)
{
// Pour les paires où USD est la devise de contrepartie (par exemple, EURUSD)
if (pair.EndsWith("USD"))
{
return 10.0; // 10 USD par pip pour 1 lot standard
}
else if (pair.StartsWith("USD"))
{
// Pour les paires où USD est la devise de base (par exemple, USDCHF)
return 10.0 / entryPrice; // Convertir en devise de contrepartie
}
else
{
// Pour les paires croisées (par exemple, EURGBP)
// Vous devrez obtenir le taux de change entre la devise de contrepartie et votre devise de compte
// Pour simplification, nous supposons ici une valeur de 10 USD
return 10.0; // Ajustez en fonction de votre devise de compte
}
}
// Fonction pour obtenir les paramètres des indicateurs en fonction du timeframe
private static IndicatorParameters GetIndicatorParametersForInterval(string interval)
{
switch (interval)
{
case "1m":
return new IndicatorParameters
{
EMAFastPeriod = 5,
EMASlowPeriod = 15,
RSIPeriod = 7,
ATRPeriod = 14
};
case "5m":
return new IndicatorParameters
{
EMAFastPeriod = 7,
EMASlowPeriod = 17,
RSIPeriod = 9,
ATRPeriod = 14
};
case "15m":
return new IndicatorParameters
{
EMAFastPeriod = 9,
EMASlowPeriod = 21,
RSIPeriod = 14,
ATRPeriod = 14
};
case "30m":
return new IndicatorParameters
{
EMAFastPeriod = 12,
EMASlowPeriod = 26,
RSIPeriod = 14,
ATRPeriod = 14
};
case "1h":
return new IndicatorParameters
{
EMAFastPeriod = 12,
EMASlowPeriod = 26,
RSIPeriod = 14,
ATRPeriod = 14
};
case "4h":
return new IndicatorParameters
{
EMAFastPeriod = 21,
EMASlowPeriod = 50,
RSIPeriod = 14,
ATRPeriod = 14
};
case "1d":
return new IndicatorParameters
{
EMAFastPeriod = 50,
EMASlowPeriod = 200,
RSIPeriod = 14,
ATRPeriod = 14
};
default:
// Paramètres par défaut si l'intervalle n'est pas spécifié
return new IndicatorParameters
{
EMAFastPeriod = 9,
EMASlowPeriod = 21,
RSIPeriod = 14,
ATRPeriod = 14
};
}
}
// Fonction pour calculer les timeframes plus grands à partir des plus petits
public static List<Candle> CalculateHigherTimeFrameData(string interval, Dictionary<string, List<Candle>> intervalDataMap)
{
// Déterminer le plus petit intervalle disponible pour le calcul
var availableIntervals = intervalDataMap.Keys.ToList();
var baseInterval = GetBaseIntervalForAggregation(interval, availableIntervals);
if (baseInterval != null)
{
int groupSize = GetGroupSize(baseInterval, interval);
if (groupSize > 0)
{
return AggregateCandles(intervalDataMap[baseInterval], groupSize);
}
}
return null;
}
// Fonction pour déterminer le meilleur intervalle de base pour l'agrégation
private static string GetBaseIntervalForAggregation(string targetInterval, List<string> availableIntervals)
{
var intervalOrder = new List<string> { "1m", "5m", "15m", "30m", "1h", "4h", "1d" };
int targetIndex = intervalOrder.IndexOf(targetInterval);
for (int i = targetIndex - 1; i >= 0; i--)
{
if (availableIntervals.Contains(intervalOrder[i]))
{
return intervalOrder[i];
}
}
return null;
}
// Fonction pour calculer le groupSize en fonction des intervalles
static int GetGroupSize(string baseInterval, string targetInterval)
{
var intervalToMinutes = new Dictionary<string, int>
{
{ "1m", 1 },
{ "5m", 5 },
{ "15m", 15 },
{ "30m", 30 },
{ "1h", 60 },
{ "4h", 240 },
{ "1d", 1440 }
};
if (intervalToMinutes.ContainsKey(baseInterval) && intervalToMinutes.ContainsKey(targetInterval))
{
int baseMinutes = intervalToMinutes[baseInterval];
int targetMinutes = intervalToMinutes[targetInterval];
if (targetMinutes % baseMinutes == 0)
{
return targetMinutes / baseMinutes;
}
}
return -1; // Agrégation impossible
}
static async Task<List<Candle>> LoadForexDataAsync(string pair, string interval)
{
// Convertir la paire de devises au format Yahoo Finance
string symbol = pair + "=X";
string url = $"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?interval={interval}&range=1mo";
using (HttpClient client = new HttpClient())
{
// Ajouter un en-tête User-Agent
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
try
{
var response = await client.GetAsync(url);
// Vérifier si le code de statut indique un succès
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
var chart = json["chart"];
var error = chart["error"];
if (error.Type != JTokenType.Null)
{
Console.WriteLine($"Erreur lors de la récupération des données pour {pair} avec intervalle {interval}: {error["description"]}");
return null;
}
var result = chart["result"][0];
var timestamp = result["timestamp"];
var indicators = result["indicators"];
var quote = indicators["quote"][0];
var opens = quote["open"].ToObject<List<double?>>();
var highs = quote["high"].ToObject<List<double?>>();
var lows = quote["low"].ToObject<List<double?>>();
var closes = quote["close"].ToObject<List<double?>>();
var volumes = quote["volume"].ToObject<List<long?>>();
List<Candle> candles = new List<Candle>();
for (int i = 0; i < timestamp.Count(); i++)
{
if (closes[i] == null)
continue;
DateTime time = DateTimeOffset.FromUnixTimeSeconds(timestamp[i].ToObject<long>()).UtcDateTime;
candles.Add(new Candle
{
Time = time,
Open = opens[i] ?? 0,
High = highs[i] ?? 0,
Low = lows[i] ?? 0,
Close = closes[i] ?? 0,
Volume = volumes[i] ?? 0
});
}
return candles;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Erreur lors de la récupération des données pour {pair} avec intervalle {interval}: {ex.Message}");
return null;
}
}
}
// Fonction pour agréger les bougies
static List<Candle> AggregateCandles(List<Candle> candles, int groupSize)
{
List<Candle> aggregatedCandles = new List<Candle>();
// Trier les bougies par date
var sortedCandles = candles.OrderBy(c => c.Time).ToList();
int totalCandles = sortedCandles.Count;
int numberOfAggregatedCandles = totalCandles / groupSize;
for (int i = 0; i < numberOfAggregatedCandles * groupSize; i += groupSize)
{
var group = sortedCandles.Skip(i).Take(groupSize).ToList();
Candle aggregatedCandle = new Candle
{
Time = group.First().Time,
Open = group.First().Open,
High = group.Max(c => c.High),
Low = group.Min(c => c.Low),
Close = group.Last().Close,
Volume = group.Sum(c => c.Volume)
};
aggregatedCandles.Add(aggregatedCandle);
}
return aggregatedCandles;
}
static Dictionary<string, double> CalculateIndicators(List<Candle> data, IndicatorParameters indicatorParams)
{
var indicators = new Dictionary<string, double>();
// Récupérer les prix de clôture et volumes
var closePrices = data.Select(c => c.Close).ToList();
var volumes = data.Select(c => (double)c.Volume).ToList();
// a. Moyennes mobiles (EMA)
indicators["EMA_Fast"] = CalculateEMA(closePrices, indicatorParams.EMAFastPeriod);
indicators["EMA_Slow"] = CalculateEMA(closePrices, indicatorParams.EMASlowPeriod);
// b. RSI
indicators["RSI"] = CalculateRSI(closePrices, indicatorParams.RSIPeriod);
// c. ATR
indicators["ATR"] = CalculateATR(data, indicatorParams.ATRPeriod);
// Dernier prix de clôture
indicators["LastClose"] = closePrices.Last();
return indicators;
}
static int CalculateScore(Dictionary<string, double> indicators)
{
int score = 0;
double lastClose = indicators["LastClose"];
// 1. EMA Fast vs EMA Slow
if (indicators["EMA_Fast"] > indicators["EMA_Slow"])
score += 2;
else
score -= 2;
// 2. RSI
if (indicators["RSI"] < 30)
score += 2; // Survente, possible retournement haussier
else if (indicators["RSI"] > 70)
score -= 2; // Surachat, possible retournement baissier
// Limiter le score entre -10 et +10
score = Math.Max(-10, Math.Min(10, score));
return score;
}
// Fonctions de calcul des indicateurs
// a. EMA (Exponential Moving Average)
static double CalculateEMA(List<double> prices, int period)
{
if (prices.Count < period)
return 0.0;
double multiplier = 2.0 / (period + 1);
double ema = prices.Take(period).Average();
for (int i = period; i < prices.Count; i++)
{
ema = ((prices[i] - ema) * multiplier) + ema;
}
return ema;
}
// b. RSI (Relative Strength Index)
static double CalculateRSI(List<double> prices, int period)
{
if (prices.Count < period + 1)
return 0.0;
double gain = 0.0, loss = 0.0;
for (int i = prices.Count - period - 1; i < prices.Count - 1; i++)
{
double diff = prices[i + 1] - prices[i];
if (diff >= 0)
gain += diff;
else
loss -= diff;
}
if (loss == 0)
return 100;
double rs = gain / loss;
double rsi = 100 - (100 / (1 + rs));
return rsi;
}
// c. ATR (Average True Range)
static double CalculateATR(List<Candle> candles, int period)
{
if (candles.Count < period + 1)
return 0.0;
List<double> trueRanges = new List<double>();
for (int i = candles.Count - period; i < candles.Count; i++)
{
double highLow = candles[i].High - candles[i].Low;
double highClosePrev = Math.Abs(candles[i].High - candles[i - 1].Close);
double lowClosePrev = Math.Abs(candles[i].Low - candles[i - 1].Close);
double trueRange = Math.Max(highLow, Math.Max(highClosePrev, lowClosePrev));
trueRanges.Add(trueRange);
}
return trueRanges.Average();
}
// Fonction pour obtenir le poids de l'intervalle
static double GetIntervalWeight(string interval)
{
var intervalWeights = new Dictionary<string, double>
{
{ "1m", 1.0 },
{ "5m", 1.0 },
{ "15m", 1.2 },
{ "30m", 1.2 },
{ "1h", 1.5 },
{ "4h", 1.8 },
{ "1d", 2.0 }
};
if (intervalWeights.ContainsKey(interval))
{
return intervalWeights[interval];
}
else
{
// Retourner un poids par défaut si l'intervalle n'est pas spécifié
return 1.0;
}
}
}