feat(backtest): saved strategy presets (strategy editor v1)
Persist named backtest-strategy presets so a staking config (bankroll, min-score, stake rule, flat/percent/Kelly params) can be saved, listed, loaded back into the form, and deleted. The per-run date range is not part of a preset. - Domain: SavedStrategy record (name trimmed + bounded to 80 chars, Create() factory) wrapping the pure BacktestStrategy. - Persistence: SavedStrategyEntity + config (TEXT decimals, unique case-insensitive NOCASE index on Name), repository, mapping, and a hand-trimmed AddSavedStrategies migration (additive — only the new table). Case-insensitive names mean save-by-name overwrites instead of creating near-duplicates. - Application: SaveStrategyUseCase (upsert by name, keeps Id+CreatedAt) + DeleteStrategyUseCase. - UI: presets panel on the Backtest page (load/save/delete) + service methods; fraction<->percent round-trip; en/ru resx. - Fix: pin Sports.Code as ValueGeneratedNever — it is the bookmaker's natural sport id, not an autoincrement surrogate. Corrects long-standing model-snapshot drift; the snapshot is regenerated to match the DB. - 25 tests across all four layers: domain validation, real-SQLite round-trip incl. case-insensitive lookup/uniqueness, the upsert use case, and the service percent mapping.
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
using FluentAssertions;
|
||||
using Marathon.Application.Abstractions;
|
||||
using Marathon.Application.UseCases;
|
||||
using Marathon.Domain.Backtesting;
|
||||
using Marathon.UI.Services;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Marathon.UI.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Covers the saved-strategy surface of <see cref="BacktestService"/> — chiefly the
|
||||
/// fraction↔percent conversion (domain stores fractions, the form/VM speak percent)
|
||||
/// and the form-validation guard. Run-simulation behaviour is covered elsewhere.
|
||||
/// </summary>
|
||||
public sealed class BacktestServiceStrategyTests
|
||||
{
|
||||
private readonly ISavedStrategyRepository _strategies = Substitute.For<ISavedStrategyRepository>();
|
||||
private readonly IAnomalyRepository _anomalies = Substitute.For<IAnomalyRepository>();
|
||||
private readonly IEventRepository _events = Substitute.For<IEventRepository>();
|
||||
private readonly IResultRepository _results = Substitute.For<IResultRepository>();
|
||||
|
||||
private BacktestService CreateSut()
|
||||
{
|
||||
var run = new RunBacktestUseCase(_anomalies, _events, _results, NullLogger<RunBacktestUseCase>.Instance);
|
||||
var save = new SaveStrategyUseCase(_strategies, NullLogger<SaveStrategyUseCase>.Instance);
|
||||
var delete = new DeleteStrategyUseCase(_strategies, NullLogger<DeleteStrategyUseCase>.Instance);
|
||||
return new BacktestService(run, save, delete, _strategies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListStrategiesAsync_ConvertsStoredFractionsToPercent()
|
||||
{
|
||||
var preset = new SavedStrategy(
|
||||
Guid.NewGuid(),
|
||||
"Quarter Kelly",
|
||||
new BacktestStrategy(1000m, 0.45m, StakeRule.Kelly, 50m, PercentOfBankroll: 0.03m, KellyFraction: 0.25m),
|
||||
DateTimeOffset.UtcNow);
|
||||
_strategies.ListAsync(Arg.Any<CancellationToken>()).Returns(new[] { preset });
|
||||
|
||||
var vms = await CreateSut().ListStrategiesAsync(CancellationToken.None);
|
||||
|
||||
vms.Should().ContainSingle();
|
||||
vms[0].Name.Should().Be("Quarter Kelly");
|
||||
vms[0].StakeRule.Should().Be(StakeRule.Kelly);
|
||||
vms[0].PercentOfBankrollPercent.Should().Be(3m); // 0.03 fraction → 3%
|
||||
vms[0].KellyFractionPercent.Should().Be(25m); // 0.25 fraction → 25%
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveStrategyAsync_PersistsFormPercents_AsFractions()
|
||||
{
|
||||
_strategies.GetByNameAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns((SavedStrategy?)null);
|
||||
var form = new BacktestForm
|
||||
{
|
||||
StartingBankroll = 1000m,
|
||||
MinScore = 0.5m,
|
||||
StakeRule = StakeRule.PercentOfBankroll,
|
||||
FlatStake = 50m,
|
||||
PercentOfBankrollPercent = 4m,
|
||||
KellyFractionPercent = 25m,
|
||||
};
|
||||
|
||||
var vm = await CreateSut().SaveStrategyAsync("PoB", form, CancellationToken.None);
|
||||
|
||||
vm.PercentOfBankrollPercent.Should().Be(4m);
|
||||
await _strategies.Received(1).AddAsync(
|
||||
Arg.Is<SavedStrategy>(s => s.Name == "PoB" && s.Strategy.PercentOfBankroll == 0.04m),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveStrategyAsync_Throws_And_DoesNotPersist_When_FormInvalid()
|
||||
{
|
||||
var badForm = new BacktestForm { StartingBankroll = 0m }; // fails IsValid
|
||||
|
||||
var act = async () => await CreateSut().SaveStrategyAsync("X", badForm, CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<ArgumentException>();
|
||||
await _strategies.DidNotReceive().AddAsync(Arg.Any<SavedStrategy>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteStrategyAsync_DelegatesToRepository()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
|
||||
await CreateSut().DeleteStrategyAsync(id, CancellationToken.None);
|
||||
|
||||
await _strategies.Received(1).DeleteAsync(id, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user