Fix genetic backend

This commit is contained in:
2025-07-11 14:11:41 +07:00
parent d04d8f310d
commit e43a1af5ef
15 changed files with 542 additions and 205 deletions

View File

@@ -105,5 +105,6 @@ Key Principles
- Do not update ManagingApi.ts, once you made a change on the backend endpoint, execute the command to regenerate ManagingApi.ts on the frontend; cd src/Managing.Nswag && dotnet build
- Do not reference new react library if a component already exist in mollecules or atoms
- After finishing the editing, build the project
- you have to pass from controller -> application -> repository, do not inject repository inside controllers
Follow the official Microsoft documentation and ASP.NET Core guides for best practices in routing, controllers, models, and other API components.

View File

@@ -25,10 +25,10 @@
"Uri": "http://localhost:9200"
},
"AllowedHosts": "*",
"WorkerPricesFifteenMinutes": true,
"WorkerPricesOneHour": true,
"WorkerPricesFourHours": true,
"WorkerPricesOneDay": true,
"WorkerPricesFifteenMinutes": false,
"WorkerPricesOneHour": false,
"WorkerPricesFourHours": false,
"WorkerPricesOneDay": false,
"WorkerPricesFiveMinutes": false,
"WorkerFee": false,
"WorkerPositionManager": false,

View File

@@ -103,6 +103,25 @@ public class BacktestController : BaseController
return Ok(_backtester.DeleteBacktestByUser(user, id));
}
/// <summary>
/// Retrieves all backtests for a specific genetic request ID.
/// This endpoint is used to view the results of a genetic algorithm optimization.
/// </summary>
/// <param name="requestId">The request ID to filter backtests by.</param>
/// <returns>A list of backtests associated with the specified request ID.</returns>
[HttpGet]
[Route("ByRequestId/{requestId}")]
public async Task<ActionResult<IEnumerable<Backtest>>> GetBacktestsByRequestId(string requestId)
{
if (string.IsNullOrEmpty(requestId))
{
return BadRequest("Request ID is required");
}
var backtests = _backtester.GetBacktestsByRequestId(requestId);
return Ok(backtests);
}
/// <summary>
/// Runs a backtest with the specified configuration.
/// The returned backtest includes a complete TradingBotConfig that preserves all

View File

@@ -7,6 +7,7 @@ public interface IBacktestRepository
{
void InsertBacktestForUser(User user, Backtest result);
IEnumerable<Backtest> GetBacktestsByUser(User user);
IEnumerable<Backtest> GetBacktestsByRequestId(string requestId);
Backtest GetBacktestByIdForUser(User user, string id);
void DeleteBacktestByIdForUser(User user, string id);
void DeleteAllBacktestsForUser(User user);

View File

@@ -49,6 +49,7 @@ namespace Managing.Application.Abstractions.Services
bool DeleteBacktest(string id);
bool DeleteBacktests();
IEnumerable<Backtest> GetBacktestsByUser(User user);
IEnumerable<Backtest> GetBacktestsByRequestId(string requestId);
Backtest GetBacktestByIdForUser(User user, string id);
bool DeleteBacktestByUser(User user, string id);
bool DeleteBacktestsByUser(User user);

View File

@@ -79,6 +79,7 @@ public interface IGeneticService
/// Runs the genetic algorithm for a specific request
/// </summary>
/// <param name="request">The genetic request to process</param>
/// <param name="cancellationToken">Cancellation token to stop the algorithm</param>
/// <returns>The genetic algorithm result</returns>
Task<GeneticAlgorithmResult> RunGeneticAlgorithm(GeneticRequest request);
Task<GeneticAlgorithmResult> RunGeneticAlgorithm(GeneticRequest request, CancellationToken cancellationToken = default);
}

View File

@@ -70,7 +70,7 @@ public class GeneticAlgorithmWorker : BaseWorker<GeneticAlgorithmWorker>
_geneticService.UpdateGeneticRequest(request);
// Run genetic algorithm using the service
var results = await _geneticService.RunGeneticAlgorithm(request);
var results = await _geneticService.RunGeneticAlgorithm(request, cancellationToken);
// Update request with results
request.Status = GeneticRequestStatus.Completed;

View File

@@ -80,8 +80,7 @@ namespace Managing.Application.Backtesting
bool withCandles = false,
string requestId = null)
{
var account = await GetAccountFromConfig(config);
var candles = GetCandles(account, config.Ticker, config.Timeframe, startDate, endDate);
var candles = GetCandles(config.Ticker, config.Timeframe, startDate, endDate);
var result = await RunBacktestWithCandles(config, candles, user, withCandles, requestId);
@@ -165,7 +164,7 @@ namespace Managing.Application.Backtesting
};
}
private List<Candle> GetCandles(Account account, Ticker ticker, Timeframe timeframe,
private List<Candle> GetCandles(Ticker ticker, Timeframe timeframe,
DateTime startDate, DateTime endDate)
{
var candles = _exchangeService.GetCandlesInflux(TradingExchanges.Evm, ticker,
@@ -400,6 +399,12 @@ namespace Managing.Application.Backtesting
return backtests;
}
public IEnumerable<Backtest> GetBacktestsByRequestId(string requestId)
{
var backtests = _backtestRepository.GetBacktestsByRequestId(requestId).ToList();
return backtests;
}
public Backtest GetBacktestByIdForUser(User user, string id)
{
var backtest = _backtestRepository.GetBacktestByIdForUser(user, id);
@@ -462,7 +467,5 @@ namespace Managing.Application.Backtesting
return false;
}
}
}
}

View File

@@ -42,39 +42,47 @@ public class GeneticService : IGeneticService
[IndicatorType.EmaTrend] = new() { ["period"] = 14.0 },
[IndicatorType.StDev] = new() { ["period"] = 14.0 },
[IndicatorType.ThreeWhiteSoldiers] = new() { ["period"] = 14.0 },
[IndicatorType.MacdCross] = new() {
[IndicatorType.MacdCross] = new()
{
["fastPeriods"] = 12.0,
["slowPeriods"] = 26.0,
["signalPeriods"] = 9.0
},
[IndicatorType.DualEmaCross] = new() {
[IndicatorType.DualEmaCross] = new()
{
["fastPeriods"] = 12.0,
["slowPeriods"] = 26.0
},
[IndicatorType.SuperTrend] = new() {
[IndicatorType.SuperTrend] = new()
{
["period"] = 14.0,
["multiplier"] = 3.0
},
[IndicatorType.SuperTrendCrossEma] = new() {
[IndicatorType.SuperTrendCrossEma] = new()
{
["period"] = 14.0,
["multiplier"] = 3.0
},
[IndicatorType.ChandelierExit] = new() {
[IndicatorType.ChandelierExit] = new()
{
["period"] = 14.0,
["multiplier"] = 3.0
},
[IndicatorType.StochRsiTrend] = new() {
[IndicatorType.StochRsiTrend] = new()
{
["period"] = 14.0,
["stochPeriods"] = 14.0,
["signalPeriods"] = 9.0,
["smoothPeriods"] = 3.0
},
[IndicatorType.Stc] = new() {
[IndicatorType.Stc] = new()
{
["cyclePeriods"] = 10.0,
["fastPeriods"] = 12.0,
["slowPeriods"] = 26.0
},
[IndicatorType.LaggingStc] = new() {
[IndicatorType.LaggingStc] = new()
{
["cyclePeriods"] = 10.0,
["fastPeriods"] = 12.0,
["slowPeriods"] = 26.0
@@ -82,64 +90,79 @@ public class GeneticService : IGeneticService
};
// Indicator-specific parameter ranges
public static readonly Dictionary<IndicatorType, Dictionary<string, (double min, double max)>> IndicatorParameterRanges = new()
{
[IndicatorType.RsiDivergence] = new() {
["period"] = (5.0, 50.0)
},
[IndicatorType.RsiDivergenceConfirm] = new() {
["period"] = (5.0, 50.0)
},
[IndicatorType.EmaCross] = new() {
["period"] = (5.0, 200.0)
},
[IndicatorType.EmaTrend] = new() {
["period"] = (5.0, 200.0)
},
[IndicatorType.StDev] = new() {
["period"] = (5.0, 50.0)
},
[IndicatorType.ThreeWhiteSoldiers] = new() {
["period"] = (5.0, 50.0)
},
[IndicatorType.MacdCross] = new() {
["fastPeriods"] = (10.0, 50.0),
["slowPeriods"] = (20.0, 100.0),
["signalPeriods"] = (5.0, 20.0)
},
[IndicatorType.DualEmaCross] = new() {
["fastPeriods"] = (5.0, 300.0),
["slowPeriods"] = (5.0, 300.0)
},
[IndicatorType.SuperTrend] = new() {
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.SuperTrendCrossEma] = new() {
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.ChandelierExit] = new() {
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.StochRsiTrend] = new() {
["period"] = (5.0, 50.0),
["stochPeriods"] = (5.0, 30.0),
["signalPeriods"] = (3.0, 15.0),
["smoothPeriods"] = (1.0, 10.0)
},
[IndicatorType.Stc] = new() {
["cyclePeriods"] = (5.0, 30.0),
["fastPeriods"] = (5.0, 50.0),
["slowPeriods"] = (10.0, 100.0)
},
[IndicatorType.LaggingStc] = new() {
["cyclePeriods"] = (5.0, 30.0),
["fastPeriods"] = (5.0, 50.0),
["slowPeriods"] = (10.0, 100.0)
}
};
public static readonly Dictionary<IndicatorType, Dictionary<string, (double min, double max)>>
IndicatorParameterRanges = new()
{
[IndicatorType.RsiDivergence] = new()
{
["period"] = (5.0, 50.0)
},
[IndicatorType.RsiDivergenceConfirm] = new()
{
["period"] = (5.0, 50.0)
},
[IndicatorType.EmaCross] = new()
{
["period"] = (5.0, 200.0)
},
[IndicatorType.EmaTrend] = new()
{
["period"] = (5.0, 200.0)
},
[IndicatorType.StDev] = new()
{
["period"] = (5.0, 50.0)
},
[IndicatorType.ThreeWhiteSoldiers] = new()
{
["period"] = (5.0, 50.0)
},
[IndicatorType.MacdCross] = new()
{
["fastPeriods"] = (10.0, 50.0),
["slowPeriods"] = (20.0, 100.0),
["signalPeriods"] = (5.0, 20.0)
},
[IndicatorType.DualEmaCross] = new()
{
["fastPeriods"] = (5.0, 300.0),
["slowPeriods"] = (5.0, 300.0)
},
[IndicatorType.SuperTrend] = new()
{
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.SuperTrendCrossEma] = new()
{
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.ChandelierExit] = new()
{
["period"] = (5.0, 50.0),
["multiplier"] = (1.0, 10.0)
},
[IndicatorType.StochRsiTrend] = new()
{
["period"] = (5.0, 50.0),
["stochPeriods"] = (5.0, 30.0),
["signalPeriods"] = (3.0, 15.0),
["smoothPeriods"] = (1.0, 10.0)
},
[IndicatorType.Stc] = new()
{
["cyclePeriods"] = (5.0, 30.0),
["fastPeriods"] = (5.0, 50.0),
["slowPeriods"] = (10.0, 100.0)
},
[IndicatorType.LaggingStc] = new()
{
["cyclePeriods"] = (5.0, 30.0),
["fastPeriods"] = (5.0, 50.0),
["slowPeriods"] = (10.0, 100.0)
}
};
// Indicator type to parameter mapping
public static readonly Dictionary<IndicatorType, string[]> IndicatorParamMapping = new()
@@ -236,8 +259,10 @@ public class GeneticService : IGeneticService
/// Runs the genetic algorithm for a specific request
/// </summary>
/// <param name="request">The genetic request to process</param>
/// <param name="cancellationToken">Cancellation token to stop the algorithm</param>
/// <returns>The genetic algorithm result</returns>
public async Task<GeneticAlgorithmResult> RunGeneticAlgorithm(GeneticRequest request)
public async Task<GeneticAlgorithmResult> RunGeneticAlgorithm(GeneticRequest request,
CancellationToken cancellationToken = default)
{
try
{
@@ -247,15 +272,39 @@ public class GeneticService : IGeneticService
request.Status = GeneticRequestStatus.Running;
UpdateGeneticRequest(request);
// Create chromosome for trading bot configuration
var chromosome = new TradingBotChromosome(request.EligibleIndicators, request.MaxTakeProfit);
// Create or resume chromosome for trading bot configuration
TradingBotChromosome chromosome;
Population population;
if (!string.IsNullOrEmpty(request.BestChromosome) && request.CurrentGeneration > 0)
{
// Resume from previous state (best chromosome only)
chromosome = new TradingBotChromosome(request.EligibleIndicators, request.MaxTakeProfit);
var savedChromosome = JsonSerializer.Deserialize<double[]>(request.BestChromosome);
if (savedChromosome != null)
{
chromosome.ReplaceGenes(0, savedChromosome.Select(g => new Gene(g)).ToArray());
}
population = new Population(request.PopulationSize, request.PopulationSize, chromosome);
_logger.LogInformation(
"Resuming genetic algorithm for request {RequestId} from generation {Generation} with best chromosome",
request.RequestId, request.CurrentGeneration);
}
else
{
// Start fresh
chromosome = new TradingBotChromosome(request.EligibleIndicators, request.MaxTakeProfit);
population = new Population(request.PopulationSize, request.PopulationSize, chromosome);
_logger.LogInformation("Starting fresh genetic algorithm for request {RequestId}", request.RequestId);
}
// Create fitness function
var fitness = new TradingBotFitness(_backtester, request);
// Create genetic algorithm with better configuration
var ga = new GeneticAlgorithm(
new Population(request.PopulationSize, request.PopulationSize, chromosome),
population,
fitness,
GetSelection(request.SelectionMethod),
new UniformCrossover(),
@@ -266,12 +315,71 @@ public class GeneticService : IGeneticService
CrossoverProbability = 0.7f // Fixed crossover rate as in frontend
};
// Custom termination condition that checks for cancellation
var originalTermination = ga.Termination;
ga.Termination = new GenerationNumberTermination(request.Generations);
// Add cancellation check in the generation event
// Run the genetic algorithm with periodic checks for cancellation
var generationCount = 0;
ga.GenerationRan += (sender, e) =>
{
generationCount = ga.GenerationsNumber;
// Update progress every 5 generations
if (generationCount % 5 == 0)
{
var bestFitness = ga.BestChromosome?.Fitness ?? 0;
request.CurrentGeneration = generationCount;
request.BestFitnessSoFar = bestFitness;
if (ga.BestChromosome is TradingBotChromosome bestChromosome)
{
var genes = bestChromosome.GetGenes();
var geneValues = genes.Select(g =>
{
if (g.Value is double doubleValue) return doubleValue;
if (g.Value is int intValue) return (double)intValue;
return Convert.ToDouble(g.Value.ToString());
}).ToArray();
request.BestChromosome = JsonSerializer.Serialize(geneValues);
}
UpdateGeneticRequest(request);
}
// Check for cancellation
if (cancellationToken.IsCancellationRequested)
{
ga.Stop();
}
};
// Run the genetic algorithm
ga.Start();
// Check if the algorithm was cancelled
if (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation("Genetic algorithm cancelled for request {RequestId}", request.RequestId);
// Update request status to pending so it can be resumed
request.Status = GeneticRequestStatus.Pending;
UpdateGeneticRequest(request);
return new GeneticAlgorithmResult
{
BestFitness = request.BestFitnessSoFar ?? 0,
BestIndividual = request.BestIndividual ?? "unknown",
ProgressInfo = request.ProgressInfo,
CompletedAt = DateTime.UtcNow
};
}
// Get the best chromosome
var bestChromosome = ga.BestChromosome as TradingBotChromosome;
var bestFitness = ga.BestChromosome.Fitness.Value;
var bestFitness = ga.BestChromosome?.Fitness ?? 0;
_logger.LogInformation("Genetic algorithm completed for request {RequestId}. Best fitness: {Fitness}",
request.RequestId, bestFitness);
@@ -346,10 +454,17 @@ public class TradingBotChromosome : ChromosomeBase
// 7+: Indicator parameters (period, fastPeriods, etc.)
public TradingBotChromosome(List<IndicatorType> eligibleIndicators, double maxTakeProfit)
: base(4 + 4 + eligibleIndicators.Count * 8) // Trading params + indicator selection + indicator params
: base(4 + 1 + 4 +
eligibleIndicators.Count * 8) // Trading params + loopback + indicator selection + indicator params
{
_eligibleIndicators = eligibleIndicators;
_maxTakeProfit = maxTakeProfit;
// Initialize all genes
for (int i = 0; i < Length; i++)
{
ReplaceGene(i, GenerateGene(i));
}
}
public override Gene GenerateGene(int geneIndex)
@@ -366,7 +481,12 @@ public class TradingBotChromosome : ChromosomeBase
_ => new Gene(0)
};
}
else if (geneIndex < 8)
else if (geneIndex == 4)
{
// LoopbackPeriod gene (always between 5 and 20)
return new Gene(GetRandomIntInRange((5, 20)));
}
else if (geneIndex < 9)
{
// Indicator selection (0 = not selected, 1 = selected)
return new Gene(_random.Next(2));
@@ -374,44 +494,44 @@ public class TradingBotChromosome : ChromosomeBase
else
{
// Indicator parameters
var indicatorIndex = (geneIndex - 8) / 8;
var paramIndex = (geneIndex - 8) % 8;
var indicatorIndex = (geneIndex - 9) / 8;
var paramIndex = (geneIndex - 9) % 8;
if (indicatorIndex < _eligibleIndicators.Count)
{
var indicator = _eligibleIndicators[indicatorIndex];
var paramName = GetParameterName(paramIndex);
if (paramName != null && GeneticService.IndicatorParamMapping.ContainsKey(indicator))
{
var requiredParams = GeneticService.IndicatorParamMapping[indicator];
if (requiredParams.Contains(paramName))
{
// Use indicator-specific ranges only
if (GeneticService.IndicatorParameterRanges.ContainsKey(indicator) &&
GeneticService.IndicatorParameterRanges[indicator].ContainsKey(paramName))
{
var indicatorRange = GeneticService.IndicatorParameterRanges[indicator][paramName];
if (paramName != null && GeneticService.IndicatorParamMapping.ContainsKey(indicator))
{
var requiredParams = GeneticService.IndicatorParamMapping[indicator];
if (requiredParams.Contains(paramName))
{
// Use indicator-specific ranges only
if (GeneticService.IndicatorParameterRanges.ContainsKey(indicator) &&
GeneticService.IndicatorParameterRanges[indicator].ContainsKey(paramName))
{
var indicatorRange = GeneticService.IndicatorParameterRanges[indicator][paramName];
// 70% chance to use default value, 30% chance to use random value within indicator-specific range
if (_random.NextDouble() < 0.7)
{
var defaultValues = GeneticService.DefaultIndicatorValues[indicator];
return new Gene(defaultValues[paramName]);
}
else
{
return new Gene(GetRandomInRange(indicatorRange));
}
}
else
{
// If no indicator-specific range is found, use default value only
var defaultValues = GeneticService.DefaultIndicatorValues[indicator];
return new Gene(defaultValues[paramName]);
}
}
}
// 70% chance to use default value, 30% chance to use random value within indicator-specific range
if (_random.NextDouble() < 0.7)
{
var defaultValues = GeneticService.DefaultIndicatorValues[indicator];
return new Gene(defaultValues[paramName]);
}
else
{
return new Gene(GetRandomInRange(indicatorRange));
}
}
else
{
// If no indicator-specific range is found, use default value only
var defaultValues = GeneticService.DefaultIndicatorValues[indicator];
return new Gene(defaultValues[paramName]);
}
}
}
}
return new Gene(0);
@@ -437,7 +557,7 @@ public class TradingBotChromosome : ChromosomeBase
for (int i = 0; i < 4; i++) // Check first 4 indicator slots
{
if (genes[4 + i].Value.ToString() == "1" && i < _eligibleIndicators.Count)
if (genes[5 + i].Value.ToString() == "1" && i < _eligibleIndicators.Count)
{
var indicator = new GeneticIndicator
{
@@ -445,7 +565,7 @@ public class TradingBotChromosome : ChromosomeBase
};
// Add parameters for this indicator
var baseIndex = 8 + i * 8;
var baseIndex = 9 + i * 8;
var paramName = GetParameterName(0); // period
if (paramName != null && HasParameter(_eligibleIndicators[i], paramName))
{
@@ -530,8 +650,11 @@ public class TradingBotChromosome : ChromosomeBase
stopLoss = GetRandomInRange((minStopLoss, maxStopLoss));
}
// Get loopback period from gene 4
var loopbackPeriod = Convert.ToInt32(genes[4].Value);
// Build scenario using selected indicators
var scenario = new Scenario($"Genetic_{request.RequestId}_Scenario", 1);
var scenario = new Scenario($"Genetic_{request.RequestId}_Scenario", loopbackPeriod);
foreach (var geneticIndicator in selectedIndicators)
{
@@ -554,7 +677,7 @@ public class TradingBotChromosome : ChromosomeBase
return new TradingBotConfig
{
Name = $"Genetic_{request.RequestId}",
AccountName = "genetic_account",
AccountName = "Oda-embedded",
Ticker = request.Ticker,
Timeframe = request.Timeframe,
BotTradingBalance = request.Balance,
@@ -612,11 +735,11 @@ public class TradingBotChromosome : ChromosomeBase
};
}
private bool HasParameter(IndicatorType indicator, string paramName)
{
return GeneticService.IndicatorParamMapping.ContainsKey(indicator) &&
GeneticService.IndicatorParamMapping[indicator].Contains(paramName);
}
private bool HasParameter(IndicatorType indicator, string paramName)
{
return GeneticService.IndicatorParamMapping.ContainsKey(indicator) &&
GeneticService.IndicatorParamMapping[indicator].Contains(paramName);
}
}
/// <summary>
@@ -665,7 +788,7 @@ public class TradingBotFitness : IFitness
_request.StartDate,
_request.EndDate,
_request.User,
false, // Don't save individual backtests
true, // Don't save individual backtests
false, // Don't include candles
_request.RequestId
).Result;
@@ -689,28 +812,30 @@ public class TradingBotFitness : IFitness
var stats = backtest.Statistics;
// Multi-objective fitness function (matching frontend)
var pnlScore = Math.Max(0, (double)stats.TotalPnL / 1000); // Normalize PnL
var winRateScore = backtest.WinRate / 100.0; // Normalize win rate
var riskRewardScore = Math.Min(2, (double)stats.WinningTrades / Math.Max(1, Math.Abs((double)stats.LoosingTrades)));
var consistencyScore = 1 - Math.Abs((double)stats.TotalPnL - (double)backtest.FinalPnl) / Math.Max(1, Math.Abs((double)stats.TotalPnL));
// Multi-objective fitness function (matching frontend)
var pnlScore = Math.Max(0, (double)stats.TotalPnL / 1000); // Normalize PnL
var winRateScore = backtest.WinRate / 100.0; // Normalize win rate
var riskRewardScore =
Math.Min(2, (double)stats.WinningTrades / Math.Max(1, Math.Abs((double)stats.LoosingTrades)));
var consistencyScore = 1 - Math.Abs((double)stats.TotalPnL - (double)backtest.FinalPnl) /
Math.Max(1, Math.Abs((double)stats.TotalPnL));
// Risk-reward ratio bonus
var riskRewardRatio = (double)(config.MoneyManagement.TakeProfit / config.MoneyManagement.StopLoss);
var riskRewardBonus = Math.Min(0.2, (riskRewardRatio - 1.1) * 0.1);
// Risk-reward ratio bonus
var riskRewardRatio = (double)(config.MoneyManagement.TakeProfit / config.MoneyManagement.StopLoss);
var riskRewardBonus = Math.Min(0.2, (riskRewardRatio - 1.1) * 0.1);
// Drawdown score (normalized to 0-1, where lower drawdown is better)
var maxDrawdownPc = Math.Abs((double)stats.MaxDrawdownPc);
var drawdownScore = Math.Max(0, 1 - (maxDrawdownPc / 50));
// Drawdown score (normalized to 0-1, where lower drawdown is better)
var maxDrawdownPc = Math.Abs((double)stats.MaxDrawdownPc);
var drawdownScore = Math.Max(0, 1 - (maxDrawdownPc / 50));
// Weighted combination
var fitness =
pnlScore * 0.3 +
winRateScore * 0.2 +
riskRewardScore * 0.2 +
consistencyScore * 0.1 +
riskRewardBonus * 0.1 +
drawdownScore * 0.1;
// Weighted combination
var fitness =
pnlScore * 0.3 +
winRateScore * 0.2 +
riskRewardScore * 0.2 +
consistencyScore * 0.1 +
riskRewardBonus * 0.1 +
drawdownScore * 0.1;
return Math.Max(0, fitness);
}

View File

@@ -154,6 +154,21 @@ public class GeneticRequest
/// Progress information (JSON serialized)
/// </summary>
public string? ProgressInfo { get; set; }
/// <summary>
/// The best chromosome found so far (JSON serialized)
/// </summary>
public string? BestChromosome { get; set; }
/// <summary>
/// Current generation number when the algorithm was stopped
/// </summary>
public int CurrentGeneration { get; set; }
/// <summary>
/// The best fitness score achieved so far
/// </summary>
public double? BestFitnessSoFar { get; set; }
}
/// <summary>

View File

@@ -32,6 +32,15 @@ public class BacktestRepository : IBacktestRepository
return backtests.Select(b => MongoMappers.Map(b));
}
public IEnumerable<Backtest> GetBacktestsByRequestId(string requestId)
{
var backtests = _backtestRepository.AsQueryable()
.Where(b => b.RequestId == requestId)
.ToList();
return backtests.Select(b => MongoMappers.Map(b));
}
public Backtest GetBacktestByIdForUser(User user, string id)
{
var backtest = _backtestRepository.FindById(id);

View File

@@ -27,5 +27,9 @@ namespace Managing.Infrastructure.Databases.MongoDb.Collections
public string? BestIndividual { get; set; }
public string? ErrorMessage { get; set; }
public string? ProgressInfo { get; set; }
public string? BestChromosome { get; set; }
public double? BestFitnessSoFar { get; set; }
public int CurrentGeneration { get; set; }
public DateTime? UpdatedAt { get; set; }
}
}

View File

@@ -498,6 +498,44 @@ export class BacktestClient extends AuthorizedApiBase {
return Promise.resolve<Backtest>(null as any);
}
backtest_GetBacktestsByRequestId(requestId: string): Promise<Backtest[]> {
let url_ = this.baseUrl + "/Backtest/ByRequestId/{requestId}";
if (requestId === undefined || requestId === null)
throw new Error("The parameter 'requestId' must be defined.");
url_ = url_.replace("{requestId}", encodeURIComponent("" + requestId));
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processBacktest_GetBacktestsByRequestId(_response);
});
}
protected processBacktest_GetBacktestsByRequestId(response: Response): Promise<Backtest[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as Backtest[];
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Backtest[]>(null as any);
}
backtest_Run(request: RunBacktestRequest): Promise<Backtest> {
let url_ = this.baseUrl + "/Backtest/Run";
url_ = url_.replace(/[?&]$/, "");
@@ -3251,6 +3289,7 @@ export interface Backtest {
user: User;
indicatorsValues: { [key in keyof typeof IndicatorType]?: IndicatorsResultBase; };
score: number;
requestId?: string | null;
}
export interface TradingBotConfig {
@@ -3691,6 +3730,9 @@ export interface GeneticRequest {
bestIndividual?: string | null;
errorMessage?: string | null;
progressInfo?: string | null;
bestChromosome?: string | null;
currentGeneration?: number;
bestFitnessSoFar?: number | null;
}
export enum GeneticRequestStatus {

View File

@@ -236,6 +236,7 @@ export interface Backtest {
user: User;
indicatorsValues: { [key in keyof typeof IndicatorType]?: IndicatorsResultBase; };
score: number;
requestId?: string | null;
}
export interface TradingBotConfig {
@@ -676,6 +677,9 @@ export interface GeneticRequest {
bestIndividual?: string | null;
errorMessage?: string | null;
progressInfo?: string | null;
bestChromosome?: string | null;
currentGeneration?: number;
bestFitnessSoFar?: number | null;
}
export enum GeneticRequestStatus {

View File

@@ -4,6 +4,7 @@ import {useQuery} from '@tanstack/react-query'
import useApiUrlStore from '../../app/store/apiStore'
import {
type Backtest,
BacktestClient,
type GeneticRequest,
IndicatorType,
@@ -55,6 +56,10 @@ const BacktestGeneticBundle: React.FC = () => {
const [isSubmitting, setIsSubmitting] = useState(false)
const [selectedIndicators, setSelectedIndicators] = useState<IndicatorType[]>(ALL_INDICATORS)
const [geneticRequests, setGeneticRequests] = useState<GeneticRequest[]>([])
const [selectedRequest, setSelectedRequest] = useState<GeneticRequest | null>(null)
const [isViewModalOpen, setIsViewModalOpen] = useState(false)
const [backtests, setBacktests] = useState<Backtest[]>([])
const [isLoadingBacktests, setIsLoadingBacktests] = useState(false)
// Form setup
const {register, handleSubmit, watch, setValue, formState: {errors}} = useForm<GeneticBundleFormData>({
@@ -187,6 +192,30 @@ const BacktestGeneticBundle: React.FC = () => {
}
}
// Handle view details
const handleViewDetails = async (request: GeneticRequest) => {
setSelectedRequest(request)
setIsViewModalOpen(true)
setIsLoadingBacktests(true)
try {
const backtestsData = await backtestClient.backtest_GetBacktestsByRequestId(request.requestId)
setBacktests(backtestsData)
} catch (error) {
console.error('Error fetching backtests:', error)
new Toast('Failed to load backtest details', false)
} finally {
setIsLoadingBacktests(false)
}
}
// Close view modal
const closeViewModal = () => {
setIsViewModalOpen(false)
setSelectedRequest(null)
setBacktests([])
}
return (
<div className="space-y-6">
<div className="card bg-base-100 shadow-xl">
@@ -433,10 +462,7 @@ const BacktestGeneticBundle: React.FC = () => {
<td>
<div className="flex gap-2">
<button
onClick={() => {
// TODO: Implement view details
new Toast('View details not implemented yet', false)
}}
onClick={() => handleViewDetails(request)}
className="btn btn-sm btn-outline"
>
View
@@ -465,6 +491,92 @@ const BacktestGeneticBundle: React.FC = () => {
</div>
</div>
)}
{/* View Details Modal */}
{isViewModalOpen && selectedRequest && (
<div className="modal modal-open">
<div className="modal-box w-11/12 max-w-6xl">
<h3 className="font-bold text-lg mb-4">
Genetic Request Details - {selectedRequest.requestId.slice(0, 8)}...
</h3>
<div className="grid grid-cols-2 gap-4 mb-6">
<div>
<strong>Ticker:</strong> {selectedRequest.ticker}
</div>
<div>
<strong>Timeframe:</strong> {selectedRequest.timeframe}
</div>
<div>
<strong>Status:</strong>
<span className={`badge ${getStatusBadgeColor(selectedRequest.status)} ml-2`}>
{selectedRequest.status}
</span>
</div>
<div>
<strong>Created:</strong> {new Date(selectedRequest.createdAt).toLocaleString()}
</div>
{selectedRequest.completedAt && (
<div>
<strong>Completed:</strong> {new Date(selectedRequest.completedAt).toLocaleString()}
</div>
)}
</div>
<div className="mb-6">
<h4 className="font-semibold mb-2">Backtest Results ({backtests.length})</h4>
{isLoadingBacktests ? (
<div className="flex justify-center">
<span className="loading loading-spinner loading-md"></span>
</div>
) : backtests.length > 0 ? (
<div className="overflow-x-auto">
<table className="table table-zebra">
<thead>
<tr>
<th>ID</th>
<th>Final PnL</th>
<th>Win Rate</th>
<th>Growth %</th>
<th>Score</th>
<th>Positions</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{backtests.map((backtest) => (
<tr key={backtest.id}>
<td className="font-mono text-xs">{backtest.id.slice(0, 8)}...</td>
<td className={backtest.finalPnl >= 0 ? 'text-success' : 'text-error'}>
${backtest.finalPnl.toFixed(2)}
</td>
<td>{backtest.winRate}%</td>
<td className={backtest.growthPercentage >= 0 ? 'text-success' : 'text-error'}>
{backtest.growthPercentage.toFixed(2)}%
</td>
<td>{backtest.score.toFixed(2)}</td>
<td>{backtest.positions?.length || 0}</td>
<td>{new Date(backtest.startDate).toLocaleDateString()}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="text-center text-gray-500 py-8">
No backtest results found for this request.
</div>
)}
</div>
<div className="modal-action">
<button onClick={closeViewModal} className="btn">
Close
</button>
</div>
</div>
</div>
)}
</div>
)
}