Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46)
ci / test (postgres) (push) Successful in 3m52s
ci / test (sqlite) (push) Failing after 2m41s
ci / image (push) Skipped

An independent review found these, now fixed and tested:

- Risk limits could be raised through PUT /api/settings without the
  phrase and the password. The API now refuses risk keys.
- The reference equity counted results twice after reduced to real and
  after a demotion. Each ledger now keeps a baseline, and carried results
  stay in the ledger's currency until the reference is computed.
- An instrument could be bought by a second strategy in the same account
  (SPEC 8.6), and purchases under way did not hold their cash, so several
  purchases sent together could exceed it. Both are refused or shrunk now.
- After an automatic trip of the switch there was no way to restart from
  the interface. Rischio now shows the trip of both worlds and the restart.
- The fresh password of SPEC 12.4 could be tried without limit. Five wrong
  attempts in 15 minutes now lock it.
- Observation to simulation skipped the 90 days of live signals.
- A new build changed the qualification of a strategy with real money,
  "Ferma tutto" counted as a critical incident, raising risk ignored
  demotion conditions in progress, and weekends counted as stock sessions.
- The 12.4 confirmation now summarises capital, first purchases and limits,
  and live strategies show the gap with their simulated twin.

The backtest converts each bar with the rate fixed before it opens, the
day before, and the report now counts how often correctives and risk
changed a decision. crypto_trend is still not passed: the broad universe
now falls 32.8%. The outcome file also keeps the qualified parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 16:48:41 +01:00
1 parent 17d6b8db38
commit 9ac159a7db
27 files changed
+1015 -532

No files matched your search

+48 -4
View File
@@ -24,7 +24,9 @@ internal sealed record StrategyCard(
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo)
int? DaysToGo,
IReadOnlyList<string> Summary,
decimal? TwinGap)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
@@ -74,6 +76,11 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
.ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
var limits = await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
decimal? reference = services.Trading?.Risk is { } risk ? await risk.ReferenceAsync(cancellationToken).ConfigureAwait(false) : null;
async Task<string> SymbolAsync(Guid instrument) =>
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
.ConfigureAwait(false) ?? "?";
var cards = new List<StrategyCard>();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
@@ -112,8 +119,45 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
var symbols = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
{
symbols.Add(await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", p.InstrumentId)),
cancellationToken).ConfigureAwait(false) ?? "?");
symbols.Add(await SymbolAsync(p.InstrumentId).ConfigureAwait(false));
}
// What the confirmation of SPEC 12.4 changes: the capital used, the purchases of the first cycle (estimated
// from what the simulation holds today) and the limits with their base.
var summary = new List<string>();
if (stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
{
var toReduced = stage.Stage == StrategyStages.Simulation;
var factor = toReduced ? StrategyStages.ReducedShare : 1m;
var simEquity = equities.FirstOrDefault(e => e.AccountId == stage.AccountId && e.Strategy == stage.Strategy);
var simUsd = accounts.FirstOrDefault(a => a.Id == stage.AccountId).Currency == "USD";
decimal SimEur(decimal amount) => simUsd ? (rate > 0m ? amount / rate : 0m) : amount;
summary.Add(toReduced
? $"Capitale usato: un quarto di quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m) * factor, decimals: 0)}."
: $"Capitale usato: tutto quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m), decimals: 0)}.");
var buys = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == stage.AccountId && p.Strategy == stage.Strategy && p.Quantity > 0m))
{
buys.Add($"{await SymbolAsync(p.InstrumentId).ConfigureAwait(false)} per circa {Format.Money(SimEur(p.Value) * factor, decimals: 0)}");
}
summary.Add(buys.Count == 0
? "Acquisti al primo ciclo: nessuno per ora, la simulazione non tiene posizioni."
: (toReduced ? "Acquisti al primo ciclo, stimati da ciò che la simulazione tiene oggi: " : "Al primo ciclo le posizioni vere crescono fino alla misura piena: ") +
string.Join(", ", buys) + ".");
summary.Add("Limiti che valgono: perdita in un giorno " + Format.Percent(limits.DailyLoss * 100m, 1) + ", calo dal massimo " +
Format.Percent(limits.DrawdownHalf * 100m, 0) + " e " + Format.Percent(limits.DrawdownStop * 100m, 0) + ", una posizione " +
Format.Percent(limits.MaxPosition * 100m, 0) + ", rischio di un'operazione " + Format.Percent(limits.MaxTradeRisk * 100m, 1) +
", misurati sul patrimonio di riferimento" + (reference is { } r ? $" (oggi {Format.Money(r, decimals: 0)})" : "") +
(toReduced ? ", e in reale ridotto su un quarto di esso." : "."));
}
// The simulated twin against the real account (SPEC 12.3): the gap of results, as a share of the capital used.
decimal? twinGap = null;
if (stage.HasTwin && stage.AccountId is { } twinAccount &&
equities.FirstOrDefault(e => e.AccountId == twinAccount && e.Strategy == stage.Strategy) is { Flows: > 0m } twin && equity is { Flows: > 0m } real)
{
twinGap = ((real.Equity - real.Flows) / real.Flows * 100m) - ((twin.Equity - twin.Flows) / twin.Flows * 100m);
}
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
@@ -126,7 +170,7 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
requirements, StageBook.Phrase(stage.Strategy, next), toGo));
requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();