Files
Anubis/src/Anubis.Server/StrategiesView.cs
T
Alby96andClaude Opus 5.5 9ac159a7db
ci / test (postgres) (push) Successful in 3m52s
ci / test (sqlite) (push) Failing after 2m41s
ci / image (push) Skipped
Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46)
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>
2026-11-11 16:48:41 +01:00

211 lines
12 KiB
C#

using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A strategy of the Strategie screen: its stage, results, requirements and what the user can do next.</summary>
internal sealed record StrategyCard(
StrategyStage Stage,
string Name,
string Description,
IReadOnlyList<string> Rules,
string Account,
string Currency,
decimal CapitalEur,
decimal ResultEur,
decimal ResultPercent,
decimal WorstFall,
int Closed,
int Winners,
IReadOnlyList<string> Open,
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo,
IReadOnlyList<string> Summary,
decimal? TwinGap)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
public bool AllMet => Requirements.All(r => r.Met);
}
/// <summary>
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
/// strategy with its requirements, and the ones in observation with the reason.
/// </summary>
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
{
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
{
[StrategyNames.CryptoTrend] =
[
"Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC",
"Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni",
"Più una moneta è agitata, meno ne compra",
"Mai a leva, mai al ribasso",
],
[StrategyNames.EquityMomentum] =
[
"Rifà la classifica ogni lunedì e tiene fino a 12 titoli",
"Vende chi esce dai primi 30 o tocca lo stop",
"Compra solo quando il mercato nel suo insieme sale",
"Solo azioni singole, nessun ETF americano",
],
[StrategyNames.EquityMeanrev] =
[
"Solo titoli sopra la loro media a 200 giorni",
"Esce al rimbalzo, oppure dopo 5 sedute",
"Salta i giorni prima delle trimestrali",
"Mai uscita nello stesso giorno dell'acquisto",
],
};
public static async Task<StrategiesView> LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts",
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken)
.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))
{
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
{
continue;
}
var family = StrategyCatalog.Find(stage.Strategy);
var ledgerAccount = stage.OrdersAccount ?? stage.AccountId;
var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount);
var usd = account.Currency == "USD";
decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount;
var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy);
// As on Conti: each position is valued to the cent before the sum, so both pages show the same figure.
var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero));
var result = equity is null ? 0m : equity.Cash + held - equity.Flows;
var since = stage.StageSince ?? DateTimeOffset.MinValue;
var (curve, trades) = await services.Db.ReadAsync(async s =>
{
var c = await s.QueryAsync(
"SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"),
("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
return (c, t);
}, cancellationToken).ConfigureAwait(false);
var peak = 0m;
var worst = 0m;
foreach (var p in curve)
{
peak = Math.Max(peak, p.Index);
worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m);
}
var symbols = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
{
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);
var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced;
var days = requirements.FirstOrDefault(r => r.Key == "days");
int? toGo = days is { Met: false } && stage.StageSince is { } from
? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays)))
: null;
var flows = equity?.Flows ?? 0m;
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, summary, twinGap));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
}
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
public static bool IsPending(Requirement requirement)
{
ArgumentNullException.ThrowIfNull(requirement);
return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione");
}
/// <summary>Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice.</summary>
public static string ObservationReason(StrategyStage stage)
{
ArgumentNullException.ThrowIfNull(stage);
if (stage.Qualification is { Passed: false } q)
{
return q.Verdict;
}
if (stage.Qualification is null)
{
return "Il backtest non è ancora stato fatto: finché manca resta in osservazione.";
}
return stage.StageReason switch
{
"user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.",
var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".",
};
}
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
}