From 259e479b1837072fbb766e6e1ecdc45566b15202 Mon Sep 17 00:00:00 2001 From: cryptooda Date: Fri, 18 Jul 2025 19:00:35 +0700 Subject: [PATCH] Fix random SL to respect RR --- src/Managing.Application/GeneticService.cs | 27 +++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/Managing.Application/GeneticService.cs b/src/Managing.Application/GeneticService.cs index c3ce964..4913098 100644 --- a/src/Managing.Application/GeneticService.cs +++ b/src/Managing.Application/GeneticService.cs @@ -532,10 +532,7 @@ public class TradingBotChromosome : ChromosomeBase return geneIndex switch { 0 => new Gene(GetRandomInRange((0.9, _maxTakeProfit))), // Take profit (0.9% to max TP) - 1 => new Gene( - GetRandomInRange( - GeneticService.ParameterRanges - ["stopLoss"])), // Stop loss (will be constrained during initialization) + 1 => new Gene(GetRandomInRange((0.2, 50.0))), // Stop loss (will be constrained in GetTradingBotConfig) 2 => new Gene(GetRandomIntInRange(GeneticService.ParameterRanges["cooldownPeriod"])), // Cooldown period 3 => new Gene(GetRandomIntInRange(GeneticService.ParameterRanges["maxLossStreak"])), // Max loss streak _ => new Gene(0) @@ -708,9 +705,18 @@ public class TradingBotChromosome : ChromosomeBase // Get stop loss from chromosome (gene 1) var stopLoss = Convert.ToDouble(genes[1].Value); - // Only enforce minimum stop loss to cover fees, allow any risk-reward ratio above that + // Enforce proper risk-reward constraints var minStopLoss = 0.2; // Minimum 0.2% to cover fees - stopLoss = Math.Max(minStopLoss, stopLoss); + var maxStopLoss = takeProfit / 1.1; // Ensure risk-reward ratio is at least 1.1:1 + + // Generate a random stop loss between min and max + var randomStopLoss = GetRandomInRange((minStopLoss, maxStopLoss)); + + // Use the random value instead of clamping the original + stopLoss = randomStopLoss; + + // Log the generated values (for debugging) + Console.WriteLine($"Generated: TP={takeProfit:F2}%, SL={stopLoss:F2}% (RR={takeProfit/stopLoss:F2}:1)"); // Get loopback period from gene 4 var loopbackPeriod = Convert.ToInt32(genes[4].Value); @@ -835,10 +841,15 @@ public class TradingBotChromosome : ChromosomeBase var takeProfit = GetRandomInRange((0.9, _maxTakeProfit)); ReplaceGene(0, new Gene(takeProfit)); - // Generate stop loss independently (gene 1) - only enforce minimum to cover fees - var stopLoss = GetRandomInRange(GeneticService.ParameterRanges["stopLoss"]); + // Generate stop loss with proper constraints (gene 1) + var minStopLoss = 0.2; // Minimum 0.2% to cover fees + var maxStopLoss = takeProfit / 1.1; // Ensure risk-reward ratio is at least 1.1:1 + var stopLoss = GetRandomInRange((minStopLoss, maxStopLoss)); ReplaceGene(1, new Gene(stopLoss)); + // Log the initial values (for debugging) + Console.WriteLine($"Initialized: TP={takeProfit:F2}%, SL={stopLoss:F2}% (RR={takeProfit/stopLoss:F2}:1)"); + // Initialize remaining genes normally for (int i = 2; i < Length; i++) {