Lines)[] waiting = candidates
+ ? [(StrategyNames.StockAthBreakout, StrategyNames.Label(StrategyNames.StockAthBreakout), CandidateProtocol.StockWaiting(), CandidateProtocol.StockExplanation)]
+ : [(StrategyNames.EquityMomentum, "Momentum azioni", EquityProtocol.Waiting(StrategyNames.EquityMomentum), EquityProtocol.Explanation),
+ (StrategyNames.EquityMeanrev, "Ritorno alla media azioni", EquityProtocol.Waiting(StrategyNames.EquityMeanrev), EquityProtocol.Explanation)];
+ foreach (var w in waiting)
{
- var waiting = EquityProtocol.Waiting(strategy);
- await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false);
- await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false);
+ await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".md"), ProtocolReport.Waiting(w.Strategy, w.Name, w.Waiting, w.Lines)).ConfigureAwait(false);
+ await File.WriteAllTextAsync(Path.Combine(outDir, w.Strategy + ".outcome.json"), BacktestOutcomes.ToJson(w.Waiting)).ConfigureAwait(false);
}
await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false);
diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor
index 0c657ce..b7482cb 100644
--- a/src/Anubis.Server/Components/Pages/Strategie.razor
+++ b/src/Anubis.Server/Components/Pages/Strategie.razor
@@ -23,12 +23,14 @@
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
{
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
+ // The candidates count among the observed ones, the discarded ones no more (mockup 04).
+ var count = here.Count + (stage == StrategyStages.Observation ? v.Candidates.Count(x => !x.Archived) : 0);
@(i + 1)
@Capital(StrategyStages.Label(stage))
@StageText(stage)
- @if (here.Count == 0)
+ @if (count == 0)
{
Nessuna strategia
}
@@ -38,7 +40,7 @@
{
}
- @(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")
+ @(count == 1 ? "1 strategia" : $"{count} strategie")
}
@@ -189,9 +191,9 @@
In osservazione
Prova una nuova strategia nel laboratorio
- @if (watching.Count == 0)
+ @if (watching.Count == 0 && v.Candidates.Count == 0)
{
- Nessuna strategia di base in osservazione.
+ Nessuna strategia in osservazione.
}
else
{
@@ -209,7 +211,26 @@
}
else if (!passed)
{
- @(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")
+ @(StrategiesView.IsWaiting(s.Stage) ? "In attesa dei dati" : "Non supera i test")
+ }
+
+ }
+ @foreach (var s in v.Candidates)
+ {
+ @s.Name
+
+ @s.Text@if (!Shell.IsDemo && StrategiesView.ReportOf(s.Stage) is { } report) { Rapporto: @report}
+ @if (s.Archived)
+ {
+ Non supera i test
+ }
+ else if (s.Waiting)
+ {
+ In attesa dei dati
+ }
+ else
+ {
+ @(Math.Min(s.Days, StageBook.ObservationDays)) giorni su @StageBook.ObservationDays
}
}
diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs
index 2dccabf..f4ea2ac 100644
--- a/src/Anubis.Server/StrategiesView.cs
+++ b/src/Anubis.Server/StrategiesView.cs
@@ -34,11 +34,45 @@ internal sealed record StrategyCard(
}
///
-/// 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.
+/// A candidate of SPEC 8.4 on the same screen: only the signals collected so far, or why it was discarded. It has no
+/// capital, no card and no button.
///
-internal sealed record StrategiesView(IReadOnlyList Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
+internal sealed record CandidateLine(StrategyStage Stage, string Name, int Signals, int Days)
{
+ public bool Archived => StageBook.IsArchived(Stage);
+
+ public bool Waiting => StrategiesView.IsWaiting(Stage);
+
+ public string Text
+ {
+ get
+ {
+ if (Archived)
+ {
+ return Stage.Qualification!.Verdict;
+ }
+
+ var signals = $"Raccoglie segnali senza fare ordini: {Signals} in {Days} {(Days == 1 ? "giorno" : "giorni")}.";
+ return signals + " " + (Waiting ? Stage.Qualification!.Verdict
+ : Days < StageBook.ObservationDays ? $"Servono almeno {StageBook.ObservationDays} giorni per giudicarla."
+ : $"I {StageBook.ObservationDays} giorni di segnali sono raccolti; resta senza capitale.");
+ }
+ }
+}
+
+///
+/// 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, the candidates of 8.4 among them.
+///
+internal sealed record StrategiesView(IReadOnlyList Cards, IReadOnlyList Candidates, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
+{
+ /// Whether a strategy's backtest could not be run yet for lack of data: not the same as having failed it.
+ public static bool IsWaiting(StrategyStage stage)
+ {
+ ArgumentNullException.ThrowIfNull(stage);
+ return stage.Qualification is { Passed: false, PlanHash: null };
+ }
+
/// What each base strategy does, in four lines (SPEC 8).
public static readonly IReadOnlyDictionary> Rules = new Dictionary>(StringComparer.Ordinal)
{
@@ -82,9 +116,19 @@ internal sealed record StrategiesView(IReadOnlyList Cards, bool Li
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();
+ var candidates = new List();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
- if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
+ if (StrategyNames.IsCandidate(stage.Strategy))
+ {
+ var observedFrom = stage.StageSince ?? clock.UtcNow;
+ var signals = await services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM ml_features WHERE source = @l AND strategy = @s AND decided_at >= @f",
+ ("l", Anubis.Learning.CaseSources.Live), ("s", stage.Strategy), ("f", observedFrom)), cancellationToken).ConfigureAwait(false);
+ candidates.Add(new CandidateLine(stage, StrategyNames.Label(stage.Strategy), (int)signals, Math.Max(0, (int)(clock.UtcNow - observedFrom).TotalDays)));
+ continue;
+ }
+
+ if (!StrategyNames.IsBase(stage.Strategy))
{
continue;
}
@@ -174,7 +218,8 @@ internal sealed record StrategiesView(IReadOnlyList Cards, bool Li
}
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);
+ return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))],
+ [.. candidates.OrderBy(c => c.Archived).ThenBy(c => c.Name, StringComparer.Ordinal)], liveAllowed, live);
}
/// A requirement not met yet only because time has to pass or nothing could be measured so far.
diff --git a/src/Anubis/Backtest/CandidateProtocol.cs b/src/Anubis/Backtest/CandidateProtocol.cs
new file mode 100644
index 0000000..1005799
--- /dev/null
+++ b/src/Anubis/Backtest/CandidateProtocol.cs
@@ -0,0 +1,54 @@
+using System.Globalization;
+using Anubis.Data;
+using Anubis.Strategies;
+using Anubis.Trading;
+
+namespace Anubis.Backtest;
+
+///
+/// The protocol of SPEC 12.2 for the candidates of 8.4. crypto_relative_momentum runs once, on the broad universe
+/// of crypto_trend: choosing three coins among three would say nothing. stock_ath_breakout waits for the Alpaca
+/// history. Dates, capital, grid, costs and thresholds are those of the base strategies, fixed before the run; the
+/// outcome is written whatever it is, and neither outcome gives a candidate any capital.
+///
+public static class CandidateProtocol
+{
+ public static string ReportPath(string strategy) => "docs/backtests/" + strategy + ".md";
+
+ public static async Task RunCryptoAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action? progress, CancellationToken cancellationToken)
+ {
+ var broad = await CryptoTrendProtocol.BroadAsync(new ResearchStore(researchRoot), to, cancellationToken).ConfigureAwait(false);
+ if (!broad.Contains("BTCEUR"))
+ {
+ throw new InvalidOperationException("Manca lo storico di BTC in euro: scarica prima gli archivi Binance e il cambio BCE.");
+ }
+
+ var run = await CryptoTrendProtocol.RunOneAsync(CryptoRelativeMomentumFamily.Instance, "Universo ampio",
+ $"Le 3 monete più forti a 30 giorni tra le 10 con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).",
+ broad, to, now, researchRoot, PriorTrials.None, progress, cancellationToken).ConfigureAwait(false);
+ return new ProtocolOutcome(QualificationOf(run), [run]);
+ }
+
+ public static Qualification QualificationOf(ProtocolRun run)
+ {
+ ArgumentNullException.ThrowIfNull(run);
+ var report = run.Report;
+ var it = CultureInfo.GetCultureInfo("it-IT");
+ var verdict = report.Passed
+ ? "Protocollo superato sui dati storici. Resta in osservazione: servono anche 90 giorni di segnali dal vivo, e una candidata non riceve capitale senza una tua decisione."
+ : "Scartata nei test: " + string.Join("; ", report.Checks.Where(c => c.Passed == false).Select(c => CryptoTrendProtocol.Describe(c, it))) + ". Resta in archivio, non riceve capitale.";
+ return CryptoTrendProtocol.Measured(run, report.Strategy, report.Passed, verdict, ReportPath(report.Strategy));
+ }
+
+ public static readonly IReadOnlyList StockExplanation =
+ [
+ "Per provare questa strategia servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.",
+ "Le regole sono già fissate (ADR 0020): compra all'apertura dopo una chiusura sopra tutte le chiusure precedenti, con almeno 300 sedute di storia; esce solo con lo stop a 10 ATR(42) sotto il massimo raggiunto. La storia raccolta parte dal 2016: un titolo che aveva un massimo più alto prima di allora conta lo stesso come nuovo massimo.",
+ "Finché manca il backtest la strategia resta in osservazione, senza capitale: scrive i suoi segnali quando ci sono i dati e non manda mai ordini.",
+ ];
+
+ public static Qualification StockWaiting() => EquityProtocol.Waiting(StrategyNames.StockAthBreakout) with
+ {
+ Verdict = "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare. Raccoglie solo segnali, senza capitale.",
+ };
+}
diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs
index 24a98cc..8c1d445 100644
--- a/src/Anubis/Backtest/Laboratory.cs
+++ b/src/Anubis/Backtest/Laboratory.cs
@@ -138,7 +138,7 @@ public sealed partial class Laboratory : IDisposable
family.Id,
family.Version,
grid,
- new TrialData(request.Source, request.Venue, symbols, request.From, request.To),
+ new TrialData(request.Source, request.Venue, symbols, request.From, request.To) { FullHistory = family.NeedsFullHistory },
request.InitialCapital,
[1m, 2m, 3m],
TrialValidation.Default,
@@ -146,7 +146,7 @@ public sealed partial class Laboratory : IDisposable
BacktestEngine.Version,
now)
{
- ReferenceShare = StrategyPipeline.DefaultShare(family.Id),
+ ReferenceShare = StrategyPipeline.ResearchShare(family.Id),
Slippage = slippage == SlippageTable.Standard ? null : slippage,
};
var variants = ParameterGrid.Of(family, plan.Grid).Count;
diff --git a/src/Anubis/Backtest/Protocol.cs b/src/Anubis/Backtest/Protocol.cs
index f8fa647..0561eb4 100644
--- a/src/Anubis/Backtest/Protocol.cs
+++ b/src/Anubis/Backtest/Protocol.cs
@@ -209,17 +209,23 @@ public static class CryptoTrendProtocol
verdict = "Protocollo non superato. " + string.Join(". ", failures) + ". Resta in osservazione.";
}
- var taker = PaperOptions.Okx().TakerFee;
+ return Measured(main, Strategy, passed, verdict, ReportPath);
+ }
+
+ /// The figures an outcome keeps of the trial it comes from (SPEC 12.3), verdict aside.
+ internal static Qualification Measured(ProtocolRun main, string strategy, bool passed, string verdict, string report)
+ {
+ var fee = StrategyNames.IsCrypto(strategy) ? PaperOptions.Okx().TakerFee : 0m;
return new Qualification
{
Passed = passed,
Verdict = verdict,
- Report = ReportPath,
+ Report = report,
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
ExpectedSlippageBp = main.ExpectedSlippageBp,
- RoundTripCost = Math.Round(2m * (taker + (main.ExpectedSlippageBp / 10_000m)), 6),
+ RoundTripCost = Math.Round(2m * (fee + (main.ExpectedSlippageBp / 10_000m)), 6),
ExpectedPathP5 = [.. PathBootstrap.Percentile(main.DailyReturns, PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed)
.Select(x => Math.Round(x, 4))],
};
@@ -241,7 +247,7 @@ public static class CryptoTrendProtocol
return $"{check.Name.ToLower(CultureInfo.GetCultureInfo("it-IT"))} {value}, serve {check.Comparison} {threshold}";
}
- private static async Task RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList symbols, DateOnly to,
+ internal static async Task RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList symbols, DateOnly to,
DateTimeOffset now, string researchRoot, PriorTrials prior, Action? progress, CancellationToken cancellationToken)
{
var request = new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, symbols, From, to, Capital, null);
diff --git a/src/Anubis/Backtest/ProtocolReport.cs b/src/Anubis/Backtest/ProtocolReport.cs
index fe0dc52..5ac0594 100644
--- a/src/Anubis/Backtest/ProtocolReport.cs
+++ b/src/Anubis/Backtest/ProtocolReport.cs
@@ -47,6 +47,11 @@ public static class ProtocolReport
b.AppendLine();
b.AppendLine("## Cosa conserva il bot").AppendLine();
+ if (StrategyNames.IsCandidate(first.Strategy))
+ {
+ b.AppendLine("Una candidata non opera e non riceve capitale: queste cifre restano come documentazione, e servirebbero solo se un giorno avanzasse.").AppendLine();
+ }
+
b.AppendLine(Text($"- Calo massimo del backtest: {Pct(-(double)q.MaxDrawdown)}. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3)."));
b.AppendLine(Text($"- Scostamento di prezzo previsto: {q.ExpectedSlippageBp.ToString("0.##", It)} punti base; costo stimato di andata e ritorno {Pct((double)q.RoundTripCost, 2)}."));
if (q.ExpectedPathP5.Count > 0)
diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs
index 5612949..eeeb31f 100644
--- a/src/Anubis/Backtest/Report.cs
+++ b/src/Anubis/Backtest/Report.cs
@@ -249,11 +249,11 @@ public static class TrialRunner
"Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.",
"Sharpe e volatilità sono calcolati senza tasso privo di rischio.",
};
- if (StrategyPipeline.IsBase(family.Id))
+ if (StrategyPipeline.ResearchShare(family.Id) is { } researched)
{
- var share = plan.ReferenceShare ?? StrategyPipeline.DefaultShare(family.Id) ?? 1m;
+ var share = plan.ReferenceShare ?? researched;
result.Add(string.Create(CultureInfo.GetCultureInfo("it-IT"),
- $"Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo."));
+ $"{(family.Id == StrategyNames.CryptoTrend ? "Limiti di rischio e regime crypto applicati" : "Limiti di rischio applicati")} come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo."));
}
else
{
diff --git a/src/Anubis/Backtest/RiskStage.cs b/src/Anubis/Backtest/RiskStage.cs
index d5cdda9..23c170c 100644
--- a/src/Anubis/Backtest/RiskStage.cs
+++ b/src/Anubis/Backtest/RiskStage.cs
@@ -227,11 +227,22 @@ public static class StrategyPipeline
public static bool IsBase(string strategy) => DefaultShare(strategy) is not null;
+ ///
+ /// The share of the bot the risk limits assume for a strategy in a trial: the default one for the base strategies,
+ /// that of its market for a candidate (SPEC 8.4), which has none of its own. Null for the examples.
+ ///
+ public static decimal? ResearchShare(string strategy) => DefaultShare(strategy) ?? strategy switch
+ {
+ StrategyNames.CryptoRelativeMomentum => 0.40m,
+ StrategyNames.StockAthBreakout => 0.45m,
+ _ => null,
+ };
+
public static BacktestOptions For(string strategy, BacktestDataset data, BacktestOptions options, decimal? share = null)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(options);
- if (!IsBase(strategy))
+ if (ResearchShare(strategy) is not { } researched)
{
return options;
}
@@ -242,6 +253,6 @@ public static class StrategyPipeline
correctives = [new CryptoRegimeStage(bitcoin.Symbol)];
}
- return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? DefaultShare(strategy) };
+ return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? researched };
}
}
diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs
index 916a72e..65615fc 100644
--- a/src/Anubis/Backtest/Trials.cs
+++ b/src/Anubis/Backtest/Trials.cs
@@ -28,8 +28,12 @@ public sealed record TrialData(string Source, string Venue, IReadOnlyListCalendar days of history before the start: a year of 252 sessions, a 360-day lookback, 400 days of listing.
public const int WarmupDays = 450;
+ /// Every bar there is before the start, for a strategy that needs the whole history (an all-time high).
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
+ public bool FullHistory { get; init; }
+
/// The first day read from the history.
- public DateOnly HistoryStart() => From.AddDays(-WarmupDays);
+ public DateOnly HistoryStart() => FullHistory ? new DateOnly(2009, 1, 1) : From.AddDays(-WarmupDays);
}
///
diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs
index c0ed982..0240946 100644
--- a/src/Anubis/Demo/DemoMode.cs
+++ b/src/Anubis/Demo/DemoMode.cs
@@ -142,6 +142,36 @@ public static class DemoMode
.ConfigureAwait(false);
}
+ // F.3: the two candidates, one collecting signals for 31 days and one discarded.
+ foreach (var (name, account, since, qualification) in new[]
+ {
+ (Trading.StrategyNames.StockAthBreakout, alpaca, 31, (Trading.Qualification?)null),
+ (Trading.StrategyNames.CryptoRelativeMomentum, okx, 58, new Trading.Qualification
+ {
+ Passed = false,
+ Verdict = "Scartata nei test: tolti i costi, il risultato è vicino a zero. Resta in archivio, non riceve capitale.",
+ Report = "docs/backtests/crypto_relative_momentum.md",
+ PlanHash = "esempio",
+ }),
+ })
+ {
+ await s.ExecuteAsync(
+ "INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, qualification, capital, share, state, created_at, updated_at) " +
+ "VALUES (@id, @n, @a, 'observation', @since, @q, 0, 0, @st, @t, @t)",
+ cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-since)),
+ ("q", qualification is null ? null : new DbJson(JsonSerializer.Serialize(qualification, Trading.Qualification.Json))), ("st", new DbJson("{}")), ("t", now)).ConfigureAwait(false);
+ }
+
+ foreach (var i in Enumerable.Range(0, 14))
+ {
+ var at = now.AddDays(-30 + (2 * i));
+ await s.ExecuteAsync(
+ "INSERT INTO ml_features (id, strategy, symbol, source, decided_day, decided_at, stage, reason, weight, features, multiplier, created_at) " +
+ "VALUES (@id, @n, @sy, 'live', @d, @t, 'observation', 'ath_entry', 0.02, @f, 1, @t)",
+ cancellationToken, ("id", ids.Next()), ("n", Trading.StrategyNames.StockAthBreakout), ("sy", "SEGNALE" + (i + 1).ToString(_it)), ("d", DateOnly.FromDateTime(at.UtcDateTime).ToString("yyyy-MM-dd", _it)),
+ ("f", new DbJson("{}")), ("t", at)).ConfigureAwait(false);
+ }
+
var started = now.AddDays(-60);
await s.ExecuteAsync("INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, 'EUR', 'USD', @d, @r, 'ecb', @t)",
cancellationToken, ("id", ids.Next()), ("d", DateOnly.FromDateTime(Now.DateTime).ToString("yyyy-MM-dd", _it)), ("r", UsdRate), ("t", now.AddMinutes(-21)))
diff --git a/src/Anubis/Learning/Clues.cs b/src/Anubis/Learning/Clues.cs
index f21938f..44ea0ff 100644
--- a/src/Anubis/Learning/Clues.cs
+++ b/src/Anubis/Learning/Clues.cs
@@ -108,7 +108,7 @@ public static class Clues
public static string? MarketOf(string strategy, StrategyContext context)
{
ArgumentNullException.ThrowIfNull(context);
- if (strategy != StrategyNames.CryptoTrend)
+ if (!StrategyNames.IsCrypto(strategy))
{
return StrategyNames.MarketSymbol;
}
@@ -176,7 +176,7 @@ public static class Clues
Put(Vix, outside.Vix);
Put(Funding, outside.BtcFunding);
Put(OpenInterest, outside.BtcOpenInterest);
- if (strategy != StrategyNames.CryptoTrend && outside.Earnings is { } earnings)
+ if (!StrategyNames.IsCrypto(strategy) && outside.Earnings is { } earnings)
{
Put(EarningsDays, earnings.TryGetValue(intent.Symbol, out var day) ? Math.Clamp(day.DayNumber - context.Day.DayNumber, 0, FarReport) : FarReport);
}
diff --git a/src/Anubis/Learning/Discoveries.cs b/src/Anubis/Learning/Discoveries.cs
index 8494a6b..70c385a 100644
--- a/src/Anubis/Learning/Discoveries.cs
+++ b/src/Anubis/Learning/Discoveries.cs
@@ -73,6 +73,8 @@ public static class DiscoveryFinder
StrategyNames.CryptoTrend => "i segnali di trend sulle crypto",
StrategyNames.EquityMomentum => "i segnali sulle azioni più forti",
StrategyNames.EquityMeanrev => "i rimbalzi sulle azioni",
+ StrategyNames.StockAthBreakout => "i nuovi massimi sulle azioni",
+ StrategyNames.CryptoRelativeMomentum => "i segnali sulle crypto più forti",
_ => "i segnali",
};
diff --git a/src/Anubis/Learning/Examples.cs b/src/Anubis/Learning/Examples.cs
index 5cb86eb..3a47e35 100644
--- a/src/Anubis/Learning/Examples.cs
+++ b/src/Anubis/Learning/Examples.cs
@@ -103,8 +103,8 @@ public sealed class SingleOperation(IStrategy inner, Example example) : IStrateg
public IReadOnlyList Schedule() => inner.Schedule();
- /// Only equity_momentum needs the others, to know the rank; the rest look at their own instrument.
- public static bool NeedsUniverse(string strategy) => strategy == StrategyNames.EquityMomentum;
+ /// The strategies that rank need the others; the rest look at their own instrument.
+ public static bool NeedsUniverse(string strategy) => strategy is StrategyNames.EquityMomentum or StrategyNames.CryptoRelativeMomentum;
public IReadOnlyList Universe(UniverseContext context) => NeedsUniverse(inner.Id) ? inner.Universe(context) : [example.Symbol];
diff --git a/src/Anubis/Learning/LearningDesk.cs b/src/Anubis/Learning/LearningDesk.cs
index 49b84d2..c354173 100644
--- a/src/Anubis/Learning/LearningDesk.cs
+++ b/src/Anubis/Learning/LearningDesk.cs
@@ -175,7 +175,7 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(create);
- if (!StrategyPipeline.IsBase(strategy))
+ if (StrategyPipeline.ResearchShare(strategy) is null)
{
return null;
}
diff --git a/src/Anubis/Strategies/Candidates.cs b/src/Anubis/Strategies/Candidates.cs
new file mode 100644
index 0000000..ef13439
--- /dev/null
+++ b/src/Anubis/Strategies/Candidates.cs
@@ -0,0 +1,378 @@
+using Anubis.Data;
+
+namespace Anubis.Strategies;
+
+/// The fixed rules of crypto_relative_momentum (SPEC 8.4, ADR 0020).
+public sealed record CryptoRelativeMomentumSettings
+{
+ /// Days of the return that ranks the coins.
+ public int Lookback { get; init; } = 30;
+
+ /// The strongest coins bought.
+ public int Positions { get; init; } = 3;
+
+ /// A coin held leaves when it falls out of these.
+ public int Keep => Positions + 2;
+
+ /// Only with Bitcoin above its average of these days.
+ public int MarketTrend { get; init; } = 200;
+
+ public int AtrLength { get; init; } = 20;
+
+ public double AtrMultiple { get; init; } = 3;
+
+ public int VolatilityWindow { get; init; } = 90;
+
+ public double StrategyVolatility { get; init; } = 0.20;
+}
+
+///
+/// crypto_relative_momentum (SPEC 8.4), a candidate: among the ten coins of crypto_trend's universe, the
+/// strongest over 30 days, only with Bitcoin in a trend. The review is on the Sunday close; every close moves the
+/// trailing stops and leaves everything when Bitcoin falls below its average.
+///
+public sealed class CryptoRelativeMomentum(CryptoRelativeMomentumSettings? settings = null) : IStrategy
+{
+ private static readonly string[] Bitcoin = ["BTC-EUR", "BTCEUR", "BTCUSDT"];
+
+ private readonly CryptoRelativeMomentumSettings _settings = settings ?? new CryptoRelativeMomentumSettings();
+ private readonly CryptoTrend _universe = new();
+
+ public string Id => CryptoRelativeMomentumFamily.FamilyId;
+
+ public string Version => CryptoRelativeMomentumFamily.FamilyVersion;
+
+ public CryptoRelativeMomentumSettings Settings => _settings;
+
+ public IReadOnlyList Schedule() => [DecisionTime.AfterClose];
+
+ /// The same ten coins as crypto_trend: live, the universe saved for it.
+ public IReadOnlyList Universe(UniverseContext context) => _universe.Universe(context);
+
+ public IReadOnlyList Decide(StrategyContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var held = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key).Order(StringComparer.Ordinal).ToList();
+ if (!MarketUp(context))
+ {
+ return [.. held.Select(s => new Intent(s, 0m, Reasons.ExitMarket))];
+ }
+
+ var intents = new SortedDictionary(StringComparer.Ordinal);
+ foreach (var symbol in held)
+ {
+ if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
+ {
+ intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop };
+ }
+ }
+
+ if (context.Day.DayOfWeek != DayOfWeek.Sunday || context.Portfolio.Equity <= 0m)
+ {
+ return [.. intents.Values];
+ }
+
+ var ranking = context.Universe.Select(s => (Symbol: s, Return: Indicators.Momentum(context.Bars(s), _settings.Lookback, 0)))
+ .Where(s => s.Return is not null).OrderByDescending(s => s.Return).ThenBy(s => s.Symbol, StringComparer.Ordinal).ToList();
+ var keep = new HashSet(ranking.Take(_settings.Keep).Select(r => r.Symbol), StringComparer.Ordinal);
+ foreach (var symbol in held.Where(s => !keep.Contains(s)))
+ {
+ intents[symbol] = new Intent(symbol, 0m, Reasons.ExitRank);
+ }
+
+ var kept = held.Where(keep.Contains).ToList();
+ var entries = ranking.Take(_settings.Positions).Where(r => r.Return > 0 && !held.Contains(r.Symbol)).Take(Math.Max(0, _settings.Positions - kept.Count)).ToList();
+
+ // Equal parts; one factor, never above 1, when the estimated volatility of the whole is above the limit.
+ var part = 1d / _settings.Positions;
+ var all = kept.Concat(entries.Select(e => e.Symbol)).Select(s => (context.Bars(s), part)).ToList();
+ var volatility = Indicators.PortfolioVolatility(all, _settings.VolatilityWindow, context.PeriodsPerYear);
+ var factor = volatility is { } v && v > _settings.StrategyVolatility ? _settings.StrategyVolatility / v : 1;
+ var weight = Math.Round((decimal)(part * factor), 6, MidpointRounding.ToZero);
+ foreach (var (symbol, momentum) in entries)
+ {
+ if (Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is > 0 and var atr)
+ {
+ intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8), Strength = momentum };
+ }
+ }
+
+ return [.. intents.Values];
+ }
+
+ private bool MarketUp(StrategyContext context)
+ {
+ var bitcoin = context.Universe.FirstOrDefault(s => Symbols.BaseOf(context.Spec(s), s) == "BTC") ?? Bitcoin.FirstOrDefault(s => context.Bars(s).Count > 0);
+ if (bitcoin is null)
+ {
+ return false;
+ }
+
+ var bars = context.Bars(bitcoin);
+ return Indicators.Sma(bars, _settings.MarketTrend) is { } average && bars.Close(bars.Count - 1) > average;
+ }
+
+ public static class Reasons
+ {
+ public const string Entry = "relative_entry";
+ public const string ExitRank = "relative_exit_rank";
+ public const string ExitMarket = "relative_exit_market";
+ public const string StopMoved = "relative_stop";
+ }
+}
+
+public sealed class CryptoRelativeMomentumFamily : IStrategyFamily
+{
+ public const string FamilyId = "crypto_relative_momentum";
+
+ public const string FamilyVersion = "1";
+
+ public static CryptoRelativeMomentumFamily Instance { get; } = new();
+
+ public string Id => FamilyId;
+
+ public string Version => FamilyVersion;
+
+ public string Name => "Momentum relativo tra crypto";
+
+ public string Description =>
+ "Strategia candidata, senza capitale: ogni settimana tiene le 3 crypto salite di più in 30 giorni tra le 10 più scambiate, solo mentre Bitcoin sta sopra la sua media di 200 giorni. " +
+ "Ognuna ha uno stop che sale con il prezzo.";
+
+ public IReadOnlyList Parameters =>
+ [
+ new("lookback", "Giorni del rendimento che fa la classifica", 30m, [20m, 30m, 40m], 5m, 200m, Whole: true),
+ new("positions", "Numero di monete", 3m, [2m, 3m, 4m], 1m, 10m, Whole: true),
+ ];
+
+ public IStrategy Create(StrategyParameters parameters)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
+ return new CryptoRelativeMomentum(new CryptoRelativeMomentumSettings { Lookback = parameters.Whole("lookback"), Positions = parameters.Whole("positions") });
+ }
+}
+
+/// The fixed rules of stock_ath_breakout (SPEC 8.4, ADR 0020).
+public sealed record StockAthBreakoutSettings
+{
+ public int UniverseSize { get; init; } = EquityUniverse.Size;
+
+ /// Sessions of history before a high counts as the highest ever.
+ public int MinSessions { get; init; } = EquityUniverse.MinSessions;
+
+ public int MaxPositions { get; init; } = 20;
+
+ public int AtrLength { get; init; } = 42;
+
+ public double AtrMultiple { get; init; } = 10;
+
+ public int VolatilityWindow { get; init; } = 60;
+
+ /// Volatility each stock adds: weight = this / its volatility, up to the cap.
+ public double StockVolatility { get; init; } = 0.02;
+
+ public double Cap { get; init; } = 0.10;
+
+ /// A purchase smaller than this share of the capital is not worth its order.
+ public double Minimum { get; init; } = 0.005;
+
+ public double StrategyVolatility { get; init; } = 0.20;
+
+ /// When the new highs of a day are more than the free places: the strongest over these sessions first.
+ public int Strength { get; init; } = 63;
+}
+
+///
+/// stock_ath_breakout (SPEC 8.4), a candidate: buys the stocks of 8.2 that close at the highest price of their
+/// history, at the next open, and leaves only through a trailing stop 10 ATR(42) below the highest close. "Ever" is
+/// the history there is, which for the bot starts in 2016: the strategy needs all of it.
+///
+public sealed class StockAthBreakout(StockAthBreakoutSettings? settings = null) : IStrategy
+{
+ private readonly StockAthBreakoutSettings _settings = settings ?? new StockAthBreakoutSettings();
+ private readonly Dictionary _highs = new(StringComparer.Ordinal);
+
+ public string Id => StockAthBreakoutFamily.FamilyId;
+
+ public string Version => StockAthBreakoutFamily.FamilyVersion;
+
+ public StockAthBreakoutSettings Settings => _settings;
+
+ public IReadOnlyList Schedule() => [DecisionTime.AfterClose];
+
+ /// The universe of 8.2, the one saved for equity_momentum.
+ public IReadOnlyList Universe(UniverseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ return context.Members?.Invoke(EquityMomentumFamily.FamilyId, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize);
+ }
+
+ public IReadOnlyList Decide(StrategyContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var equity = context.Portfolio.Equity;
+ var intents = new SortedDictionary(StringComparer.Ordinal);
+ var weights = new List<(BarSeries Bars, double Weight)>();
+ var open = 0;
+ foreach (var (symbol, holding) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).OrderBy(h => h.Key, StringComparer.Ordinal))
+ {
+ open++;
+ var bars = context.Bars(symbol);
+ if (bars.Count > 0 && equity > 0m)
+ {
+ weights.Add((bars, (double)holding.Quantity * bars.Close(bars.Count - 1) / (double)equity));
+ }
+
+ if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
+ {
+ intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop };
+ }
+ }
+
+ var highs = new List<(string Symbol, double Strength, double Atr, double Weight)>();
+ foreach (var symbol in context.Universe)
+ {
+ var bars = context.Bars(symbol);
+ if (Tracker(symbol).IsNewHigh(bars) && bars.Count >= _settings.MinSessions && !context.Portfolio.Holds(symbol)
+ && Indicators.Atr(bars, _settings.AtrLength) is > 0 and var atr
+ && Indicators.Volatility(bars, _settings.VolatilityWindow, context.PeriodsPerYear) is > 0 and var volatility)
+ {
+ highs.Add((symbol, Indicators.Momentum(bars, _settings.Strength, 0) ?? 0, atr, Math.Min(_settings.Cap, _settings.StockVolatility / volatility)));
+ }
+ }
+
+ var slots = _settings.MaxPositions - open;
+ if (slots <= 0 || equity <= 0m || highs.Count == 0)
+ {
+ return [.. intents.Values];
+ }
+
+ var entries = highs.OrderByDescending(h => h.Strength).ThenBy(h => h.Symbol, StringComparer.Ordinal).Take(slots).ToList();
+ var whole = Indicators.PortfolioVolatility([.. weights, .. entries.Select(e => (context.Bars(e.Symbol), e.Weight))], _settings.VolatilityWindow, context.PeriodsPerYear);
+ var factor = whole is { } w && w > _settings.StrategyVolatility ? _settings.StrategyVolatility / w : 1;
+ var free = 1 - weights.Sum(x => x.Weight);
+ foreach (var (symbol, strength, atr, wanted) in entries)
+ {
+ var weight = Math.Min(wanted * factor, free);
+ if (weight < _settings.Minimum)
+ {
+ continue;
+ }
+
+ intents[symbol] = new Intent(symbol, Math.Round((decimal)weight, 6, MidpointRounding.ToZero), Reasons.Entry)
+ {
+ StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8),
+ Strength = strength,
+ };
+ free -= weight;
+ }
+
+ return [.. intents.Values];
+ }
+
+ private HighTracker Tracker(string symbol)
+ {
+ if (!_highs.TryGetValue(symbol, out var tracker))
+ {
+ _highs[symbol] = tracker = new HighTracker();
+ }
+
+ return tracker;
+ }
+
+ public static class Reasons
+ {
+ public const string Entry = "ath_entry";
+ public const string StopMoved = "ath_stop";
+ }
+
+ ///
+ /// Where the highest close before the last bar is, walked one bar at a time. The bar is kept, not its price: adjusted
+ /// prices are anchored to the day they are read on.
+ ///
+ private sealed class HighTracker
+ {
+ private int _walked;
+ private int _highest = -1;
+ private DateOnly? _first;
+ private DateOnly? _last;
+
+ public bool IsNewHigh(BarSeries bars)
+ {
+ if (bars.Count < _walked || (_walked > 0 && (bars.FirstDay != _first || bars.Day(_walked - 1) != _last)))
+ {
+ _walked = 0;
+ _highest = -1;
+ }
+
+ if (bars.Count < 2)
+ {
+ return false;
+ }
+
+ // Every bar but the last: the last is the one that must beat them.
+ for (var i = _walked; i < bars.Count - 1; i++)
+ {
+ if (_highest < 0 || bars.Close(i) > bars.Close(_highest))
+ {
+ _highest = i;
+ }
+ }
+
+ _walked = bars.Count - 1;
+ _first = bars.FirstDay;
+ _last = bars.Day(_walked - 1);
+ return bars.Close(bars.Count - 1) > bars.Close(_highest);
+ }
+ }
+}
+
+public sealed class StockAthBreakoutFamily : IStrategyFamily
+{
+ public const string FamilyId = "stock_ath_breakout";
+
+ public const string FamilyVersion = "1";
+
+ public static StockAthBreakoutFamily Instance { get; } = new();
+
+ public string Id => FamilyId;
+
+ public string Version => FamilyVersion;
+
+ public string Name => "Nuovi massimi storici sulle azioni USA";
+
+ public string Description =>
+ "Strategia candidata, senza capitale: compra le azioni americane che chiudono al prezzo più alto della loro storia raccolta (dal 2016) e le tiene finché non scendono di 10 volte la loro oscillazione media sotto il massimo. " +
+ "Al massimo 20 titoli.";
+
+ public bool NeedsFullHistory => true;
+
+ public IReadOnlyList Parameters =>
+ [
+ new("stop_atr", "Stop in ATR sotto il massimo", 10m, [8m, 10m, 12m], 2m, 30m, Whole: true),
+ new("positions", "Numero massimo di titoli", 20m, [15m, 20m, 25m], 3m, 50m, Whole: true),
+ ];
+
+ public IStrategy Create(StrategyParameters parameters)
+ {
+ ArgumentNullException.ThrowIfNull(parameters);
+ return new StockAthBreakout(new StockAthBreakoutSettings { AtrMultiple = (double)parameters["stop_atr"], MaxPositions = parameters.Whole("positions") });
+ }
+}
+
+/// The stop that follows the highest close since the entry at some ATRs and can only rise.
+internal static class Trailing
+{
+ public static decimal? Stop(StrategyContext context, string symbol, int atrLength, double multiple)
+ {
+ var holding = context.Portfolio.Of(symbol)!;
+ var bars = context.Bars(symbol);
+ if (Indicators.Atr(bars, atrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high)
+ {
+ return null;
+ }
+
+ var candidate = Math.Round((decimal)(high - (multiple * atr)), 8);
+ return candidate <= 0m || (holding.Stop is { } current && candidate <= current) ? null : candidate;
+ }
+}
diff --git a/src/Anubis/Strategies/EquityStrategies.cs b/src/Anubis/Strategies/EquityStrategies.cs
index d33ad53..c771d03 100644
--- a/src/Anubis/Strategies/EquityStrategies.cs
+++ b/src/Anubis/Strategies/EquityStrategies.cs
@@ -115,7 +115,8 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
var stops = new Dictionary(StringComparer.Ordinal);
foreach (var symbol in held)
{
- if (TrailingStop(context, symbol) is { } stop)
+ // 3 ATR(20) below the highest close since the entry; it can only rise.
+ if (Trailing.Stop(context, symbol, _settings.AtrLength, _settings.AtrMultiple) is { } stop)
{
stops[symbol] = stop;
}
@@ -246,25 +247,6 @@ public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IS
return raw.ToDictionary(p => p.Key, p => Math.Round((decimal)(p.Value * factor), 6, MidpointRounding.ToZero), StringComparer.Ordinal);
}
- /// 3 ATR(20) below the highest close since the entry; it can only rise.
- private decimal? TrailingStop(StrategyContext context, string symbol)
- {
- var holding = context.Portfolio.Of(symbol)!;
- var bars = context.Bars(symbol);
- if (Indicators.Atr(bars, _settings.AtrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high)
- {
- return null;
- }
-
- var candidate = Math.Round((decimal)(high - (_settings.AtrMultiple * atr)), 8);
- if (candidate <= 0m || (holding.Stop is { } current && candidate <= current))
- {
- return null;
- }
-
- return candidate;
- }
-
public static class Reasons
{
public const string Entry = "momentum_entry";
diff --git a/src/Anubis/Strategies/Research.cs b/src/Anubis/Strategies/Research.cs
index 43a3290..9bc69b7 100644
--- a/src/Anubis/Strategies/Research.cs
+++ b/src/Anubis/Strategies/Research.cs
@@ -143,11 +143,14 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily
}
}
-/// The strategies the laboratory can test: the three of the bot first, then the examples.
+/// The strategies the laboratory can test: the three of the bot first, then the candidates (SPEC 8.4) and the examples.
public static class StrategyCatalog
{
public static IReadOnlyList All { get; } =
- [CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
+ [
+ CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, StockAthBreakoutFamily.Instance, CryptoRelativeMomentumFamily.Instance,
+ MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance,
+ ];
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
}
diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs
index fad72e4..da36652 100644
--- a/src/Anubis/Strategies/Strategy.cs
+++ b/src/Anubis/Strategies/Strategy.cs
@@ -326,6 +326,9 @@ public interface IStrategyFamily
IReadOnlyList Parameters { get; }
+ /// True when a window is not enough: the strategy reads every bar there is, such as an all-time high.
+ bool NeedsFullHistory => false;
+
/// False for a point of the grid that makes no sense (a short average longer than the long one).
bool Accepts(StrategyParameters parameters) => true;
diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs
index 21aa684..3c48873 100644
--- a/src/Anubis/Trading/Capital.cs
+++ b/src/Anubis/Trading/Capital.cs
@@ -21,8 +21,29 @@ public static class StrategyNames
(EquityMeanrev, Venues.Alpaca, 0.25m),
];
+ public const string StockAthBreakout = "stock_ath_breakout";
+ public const string CryptoRelativeMomentum = "crypto_relative_momentum";
+
+ ///
+ /// The candidates of SPEC 8.4: research and observation only. They have no share, no capital and no order code, so
+ /// they are never among the ones.
+ ///
+ public static readonly IReadOnlyList<(string Name, string Broker)> Candidates =
+ [
+ (StockAthBreakout, Venues.Alpaca),
+ (CryptoRelativeMomentum, Venues.Okx),
+ ];
+
+ public static bool IsBase(string strategy) => Base.Any(b => b.Name == strategy);
+
+ public static bool IsCandidate(string strategy) => Candidates.Any(c => c.Name == strategy);
+
+ /// The market of a strategy: crypto on OKX Europe, the others trade US stocks.
+ public static bool IsCrypto(string strategy) => BrokerOf(strategy) == Venues.Okx;
+
public static string BrokerOf(string strategy) =>
- Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy));
+ Base.FirstOrDefault(b => b.Name == strategy).Broker ?? Candidates.FirstOrDefault(c => c.Name == strategy).Broker
+ ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy));
/// The name the user reads (appendix F): short in tables, with the market in legends.
public static string Label(string strategy, bool withMarket = false) => strategy switch
@@ -30,6 +51,8 @@ public static class StrategyNames
CryptoTrend => "Trend crypto",
EquityMomentum => withMarket ? "Momentum azioni" : "Momentum",
EquityMeanrev => withMarket ? "Mean reversion azioni" : "Mean reversion",
+ StockAthBreakout => "Nuovi massimi storici sulle azioni USA",
+ CryptoRelativeMomentum => "Momentum relativo tra crypto",
_ => strategy,
};
@@ -84,7 +107,8 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
var given = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, amount FROM cash_ledger WHERE kind = @k AND strategy IS NOT NULL",
r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
- return rows.Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency,
+ // A candidate of SPEC 8.4 has no share and no capital: it is no part of any plan.
+ return rows.Where(r => !StrategyNames.IsCandidate(r.Strategy)).Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency,
r.Share ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Strategy).Share,
given.Where(g => g.Account == r.Account && g.Strategy == r.Strategy).Sum(g => g.Amount),
equities.Where(e => e.AccountId == r.Account && e.Strategy == r.Strategy).Sum(e => e.Cash))).ToList();
@@ -134,6 +158,11 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
public async Task SetSharesAsync(string broker, IReadOnlyDictionary shares, string changedBy, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(shares);
+ if (shares.Keys.Any(StrategyNames.IsCandidate))
+ {
+ throw new CapitalException("Una strategia candidata non riceve capitale.");
+ }
+
if (shares.Values.Any(v => v is < 0m or > 1m) || shares.Values.Sum() != 1m)
{
throw new CapitalException("Le quote vanno da 0 a 100% e insieme fanno 100%.");
diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs
index 9cc907d..3bc84e0 100644
--- a/src/Anubis/Trading/DiaryText.cs
+++ b/src/Anubis/Trading/DiaryText.cs
@@ -143,6 +143,10 @@ public static class DiaryText
public static string NoData(string strategy, string what) =>
$"{StrategyNames.Label(strategy, withMarket: true)}: nessuna decisione oggi. Mancano {what}: non apro nuove posizioni.";
+ /// A candidate (SPEC 8.4) found in a stage that trades: nothing in the program puts it there.
+ public static string CandidateStage(string strategy) =>
+ $"{StrategyNames.Label(strategy, withMarket: true)} è una strategia candidata ma nel database risulta fuori dall'osservazione: non la faccio decidere.";
+
/// A missed job done at the restart (SPEC 5.6).
public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) =>
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs
index 83b62a2..14d77de 100644
--- a/src/Anubis/Trading/LiveEngine.cs
+++ b/src/Anubis/Trading/LiveEngine.cs
@@ -119,6 +119,7 @@ public sealed partial class LiveEngine : IDisposable
///
public static readonly TimeSpan LateDataWait = TimeSpan.FromMinutes(30);
private readonly SemaphoreSlim _gate = new(1, 1);
+ private readonly HashSet _candidatesRefused = new(StringComparer.Ordinal);
public LiveEngine(Database db, IClock clock, Ledger ledger, StageBook stages, Func managers, Func> quotes,
IMarketCalendar? calendar = null, LiveEngineOptions? options = null, ILogger? logger = null)
@@ -216,6 +217,7 @@ public sealed partial class LiveEngine : IDisposable
}
await ReleaseAsync(now, cancellationToken).ConfigureAwait(false);
+ await CandidatesAsync(now, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -234,14 +236,74 @@ public sealed partial class LiveEngine : IDisposable
return;
}
+ await DecideAsync(CryptoMoment(StrategyNames.CryptoTrend, today, due, now), cancellationToken).ConfigureAwait(false);
+ }
+
+ private Moment CryptoMoment(string strategy, DateOnly today, DateTimeOffset due, DateTimeOffset now)
+ {
var deadline = At(today, Options.CryptoDeadline);
var day = today.AddDays(-1);
// The orders go at once. A decision made long after 00:05 (the bot was off) keeps 00:05 as its time, so its
// entries are checked against the price they were decided on (SPEC 5.6); waiting for the bars is not an absence.
var ordersDue = now - due > Options.RecoveredAfter ? due : now;
- await DecideAsync(new Moment(StrategyNames.CryptoTrend, day, Key(StrategyNames.CryptoTrend, day), due, now > deadline, deadline, now, ordersDue, deadline), cancellationToken)
- .ConfigureAwait(false);
+ return new Moment(strategy, day, Key(strategy, day), due, now > deadline, deadline, now, ordersDue, deadline);
+ }
+
+ ///
+ /// The candidates of SPEC 8.4, after everything that can trade: they only note their signals, and one that fails
+ /// is said and changes nothing for the others.
+ ///
+ private async Task CandidatesAsync(DateTimeOffset now, CancellationToken cancellationToken)
+ {
+ foreach (var (strategy, _) in StrategyNames.Candidates)
+ {
+ try
+ {
+ if (CandidateMoment(strategy, now) is not { } moment || await RunExistsAsync(moment.Key, cancellationToken).ConfigureAwait(false)
+ || await _stages.GetAsync(strategy, cancellationToken).ConfigureAwait(false) is not { } stage || StageBook.IsArchived(stage))
+ {
+ continue;
+ }
+
+ if (stage.Stage != StrategyStages.Observation)
+ {
+ // Nothing in the program puts a candidate there: whoever did, it does not trade.
+ if (_candidatesRefused.Add(strategy))
+ {
+ await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "candidate_stage", DiaryText.CandidateStage(strategy), null, cancellationToken),
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ continue;
+ }
+
+ await DecideAsync(moment, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ LogCandidateFailed(_logger, ex, strategy);
+ }
+ }
+ }
+
+ private Moment? CandidateMoment(string strategy, DateTimeOffset now)
+ {
+ if (StrategyNames.IsCrypto(strategy))
+ {
+ var today = DateOnly.FromDateTime(now.UtcDateTime);
+ var due = At(today, Options.CryptoDecision);
+ return now < due ? null : CryptoMoment(strategy, today, due, now);
+ }
+
+ if (_calendar is null || LastClosed(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, NewYork).DateTime), now) is not { } last
+ || now < last.CloseUtc + Options.SignalsAfterClose || NextSession(last.Date) is not { } next)
+ {
+ return null;
+ }
+
+ return new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, now >= next.OpenUtc, next.OpenUtc, now,
+ next.OpenUtc + Options.OrdersAfterOpen, next.CloseUtc);
}
private static DateTimeOffset At(DateOnly day, TimeOnly time) => new(day.ToDateTime(time), TimeSpan.Zero);
@@ -463,6 +525,11 @@ public sealed partial class LiveEngine : IDisposable
}
var observation = stage.Stage == StrategyStages.Observation;
+ if (!observation && StrategyNames.IsCandidate(m.Strategy))
+ {
+ return; // Never an order for a candidate, whatever its row says (SPEC 8.4).
+ }
+
var accountId = observation ? stage.AccountId : stage.OrdersAccount;
if (accountId is not { } account)
{
@@ -536,7 +603,7 @@ public sealed partial class LiveEngine : IDisposable
}
private async Task?> EarningsOfAsync(Moment m, CancellationToken cancellationToken) =>
- Earnings is null || m.Strategy == StrategyNames.CryptoTrend ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next;
+ Earnings is null || StrategyNames.IsCrypto(m.Strategy) ? null : (await Earnings(m.Day, cancellationToken).ConfigureAwait(false))?.Next;
private DateTimeOffset LateSince(string key, DateTimeOffset now)
{
@@ -571,7 +638,7 @@ public sealed partial class LiveEngine : IDisposable
/// The earnings calendar as the decision of reads it (SPEC 10.5, fourth row; 8.3).
private async Task WithEarningsAsync(BacktestOptions options, string strategy, DateOnly day, CancellationToken cancellationToken)
{
- if (Earnings is null || strategy == StrategyNames.CryptoTrend || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
+ if (Earnings is null || StrategyNames.IsCrypto(strategy) || await Earnings(day, cancellationToken).ConfigureAwait(false) is not { } earnings)
{
return options;
}
@@ -614,8 +681,13 @@ public sealed partial class LiveEngine : IDisposable
return;
}
- var what = m.Strategy == StrategyNames.CryptoTrend ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni";
+ var what = StrategyNames.IsCrypto(m.Strategy) ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni";
var text = DiaryText.NoData(m.Strategy, what);
+ if (StrategyNames.IsCandidate(m.Strategy))
+ {
+ return; // The strategies of its market already say it.
+ }
+
if (observation)
{
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.MissingBars, text, null, cancellationToken).ConfigureAwait(false);
@@ -905,8 +977,12 @@ public sealed partial class LiveEngine : IDisposable
.ConfigureAwait(false);
}
- await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary),
- new { decision = decisionId }, cancellationToken).ConfigureAwait(false);
+ if (plan.Summary.HasChanges || !StrategyNames.IsCandidate(m.Strategy))
+ {
+ await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary),
+ new { decision = decisionId }, cancellationToken).ConfigureAwait(false);
+ }
+
return;
}
@@ -952,7 +1028,7 @@ public sealed partial class LiveEngine : IDisposable
}
}
- var summary = m.Strategy == StrategyNames.CryptoTrend ? DiaryText.CryptoClose(plan.Summary) : DiaryText.StockSignals(plan.Summary);
+ var summary = StrategyNames.IsCrypto(m.Strategy) ? DiaryText.CryptoClose(plan.Summary) : DiaryText.StockSignals(plan.Summary);
if (mode == DecisionModes.ExitsOnly && plan.Notes.Any(n => n.Reason == LiveReasons.LateExitsOnly))
{
summary += " " + ReasonCatalog.Text(LiveReasons.LateExitsOnly);
@@ -961,7 +1037,7 @@ public sealed partial class LiveEngine : IDisposable
if (m.Now - m.Due > Options.RecoveredAfter)
{
// Made late because the bot was off (SPEC 5.6): said before what was decided.
- var what = m.Strategy == StrategyNames.CryptoTrend ? "la chiusura giornaliera crypto" : "il calcolo dei segnali sulle azioni";
+ var what = StrategyNames.IsCrypto(m.Strategy) ? "la chiusura giornaliera crypto" : "il calcolo dei segnali sulle azioni";
await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.Recovered, DiaryText.Recovered(what, m.Due, Zone), new { decision = decisionId },
cancellationToken).ConfigureAwait(false);
}
@@ -1352,7 +1428,7 @@ public sealed partial class LiveEngine : IDisposable
private DateOnly? LastClosed(string strategy)
{
var now = _clock.UtcNow;
- if (strategy == StrategyNames.CryptoTrend)
+ if (StrategyNames.IsCrypto(strategy))
{
return DateOnly.FromDateTime(now.UtcDateTime).AddDays(-1);
}
@@ -1364,7 +1440,7 @@ public sealed partial class LiveEngine : IDisposable
private async Task LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken, IReadOnlyList? extra = null,
DateOnly? since = null)
{
- var crypto = strategy == StrategyNames.CryptoTrend;
+ var crypto = StrategyNames.IsCrypto(strategy);
var venue = crypto ? Venues.Okx : Venues.Alpaca;
var members = await _universes.AsOfAsync(crypto ? Universes.Crypto : Universes.Equity, day, cancellationToken).ConfigureAwait(false);
var symbols = new SortedSet(members.Select(m => m.Symbol), StringComparer.Ordinal);
@@ -1383,8 +1459,8 @@ public sealed partial class LiveEngine : IDisposable
}
// The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The
- // stock strategies read windows: the warm-up of a trial is enough.
- var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
+ // stock strategies read windows: the warm-up of a trial is enough, unless the strategy says it needs everything.
+ var from = crypto || StrategyCatalog.Find(strategy) is { NeedsFullHistory: true } ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays);
from = since < from ? since.Value : from;
var instruments = new List();
var missing = new HashSet(StringComparer.Ordinal);
@@ -1490,6 +1566,9 @@ public sealed partial class LiveEngine : IDisposable
[LoggerMessage(Level = LogLevel.Warning, Message = "Asking for the missing bars failed")]
private static partial void LogDataRequestFailed(ILogger logger, Exception exception);
+ [LoggerMessage(Level = LogLevel.Error, Message = "The candidate strategy {Strategy} could not decide")]
+ private static partial void LogCandidateFailed(ILogger logger, Exception exception, string strategy);
+
[LoggerMessage(Level = LogLevel.Error, Message = "Planned order {Id} could not be released")]
private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id);
}
diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs
index 53a5b1e..6c9cd76 100644
--- a/src/Anubis/Trading/ReasonCatalog.cs
+++ b/src/Anubis/Trading/ReasonCatalog.cs
@@ -26,6 +26,12 @@ public static class ReasonCatalog
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
+ ["ath_entry"] = "Aveva chiuso al prezzo più alto della sua storia raccolta.",
+ ["ath_stop"] = "Lo stop di protezione è salito con il prezzo.",
+ ["relative_entry"] = "Era tra le crypto salite di più nell'ultimo mese, con Bitcoin in tendenza.",
+ ["relative_exit_rank"] = "Non era più tra le crypto più forti.",
+ ["relative_exit_market"] = "Bitcoin è sceso sotto la sua media a 200 giorni.",
+ ["relative_stop"] = "Lo stop di protezione è salito con il prezzo.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs
index b2c82bf..820229b 100644
--- a/src/Anubis/Trading/Stages.cs
+++ b/src/Anubis/Trading/Stages.cs
@@ -248,18 +248,37 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
return;
}
- if (qualification.Passed)
+ // A candidate (SPEC 8.4) has no capital and no order code: whatever its outcome, it stays in observation.
+ if (qualification.Passed && !StrategyNames.IsCandidate(strategy))
{
await MoveCoreAsync(s, strategy, current.Stage, StrategyStages.Simulation, "backtest_passed", "primo avvio", cancellationToken).ConfigureAwait(false);
}
else
{
await s.ExecuteAsync("UPDATE strategy_state SET stage_reason = @r, stage_since = COALESCE(stage_since, @t), updated_at = @t WHERE strategy = @s", cancellationToken,
- ("r", "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
+ ("r", qualification.Passed ? "candidate" : "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
}
+ ///
+ /// A candidate the protocol turned down on its data (SPEC 12.3): kept as documentation, it decides no more. One that
+ /// waits for its data has no plan yet. "Archived" is not a stage: it is read from the outcome.
+ ///
+ public static bool IsArchived(StrategyStage stage)
+ {
+ ArgumentNullException.ThrowIfNull(stage);
+ return StrategyNames.IsCandidate(stage.Strategy) && stage.Qualification is { Passed: false, PlanHash: not null };
+ }
+
+ private static void RefuseCandidate(string strategy)
+ {
+ if (StrategyNames.IsCandidate(strategy))
+ {
+ throw new LiveConfirmationException("candidate", "È una strategia candidata: raccoglie solo segnali e non riceve capitale.");
+ }
+ }
+
///
/// Moves a strategy between observation and simulation (the user's choice from the interface). Real money is
/// never reached this way: only does it.
@@ -271,6 +290,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
throw new LiveConfirmationException("procedure", "Per i soldi veri serve la procedura di conferma.");
}
+ RefuseCandidate(strategy);
var current = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy));
if (StrategyStages.IsLive(current.Stage))
{
@@ -360,6 +380,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
public async Task ConfirmLiveAsync(LiveConfirmation c, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(c);
+ RefuseCandidate(c.Strategy);
if (!consent.AllowLive)
{
throw new LiveConfirmationException(RiskReasons.NoConsent,
diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs
index d646536..9befc59 100644
--- a/src/Anubis/Trading/TradingService.cs
+++ b/src/Anubis/Trading/TradingService.cs
@@ -129,6 +129,15 @@ public static class AccountSetup
}
}
+ // The candidates of SPEC 8.4 only note their signals: in observation, with no capital and no share.
+ foreach (var (strategy, broker) in StrategyNames.Candidates)
+ {
+ var target = accounts.First(a => a.Broker == broker && a.Environment == TradingEnvironments.Simulation).AccountId;
+ await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) " +
+ "VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 0) ON CONFLICT (strategy) DO NOTHING", cancellationToken,
+ ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", StrategyNames.Observation), ("j", new DbJson("{}")), ("now", now)).ConfigureAwait(false);
+ }
+
return accounts;
}, cancellationToken).ConfigureAwait(false);
}
@@ -569,7 +578,7 @@ public sealed partial class TradingService : IDisposable
///
public async Task LoadOutcomesAsync(CancellationToken cancellationToken)
{
- foreach (var (strategy, _, _) in StrategyNames.Base)
+ foreach (var strategy in StrategyNames.Base.Select(b => b.Name).Concat(StrategyNames.Candidates.Select(c => c.Name)))
{
if (Backtest.BacktestOutcomes.Find(strategy) is { } outcome)
{
diff --git a/tests/Anubis.Tests/CandidateTests.cs b/tests/Anubis.Tests/CandidateTests.cs
new file mode 100644
index 0000000..b7777b7
--- /dev/null
+++ b/tests/Anubis.Tests/CandidateTests.cs
@@ -0,0 +1,370 @@
+using Anubis.Backtest;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Strategies;
+using Anubis.Trading;
+
+namespace Anubis.Tests;
+
+/// The candidates of SPEC 8.4 (issue #74): their rules, their protocol, and that they never trade.
+[TestClass]
+public sealed class CandidateTests
+{
+ private static readonly CancellationToken _none = CancellationToken.None;
+ private static readonly DateOnly Monday = new(2022, 1, 3);
+ private static readonly DateOnly LiveFrom = new(2026, 9, 1);
+
+ private static string[] Names => [.. StrategyNames.Candidates.Select(c => c.Name)];
+
+ private static BacktestDataset Coins(int days, double btcDrift, ulong seed = 40) =>
+ StrategyData.Crypto([.. new[] { "BTC", "ETH", "SOL", "XRP", "ADA", "LTC" }.Select((c, i) =>
+ (c, (IReadOnlyList)[.. BacktestData.Walk(days, seed + (ulong)i, start: 100, drift: i == 0 ? btcDrift : 0.0006 * (i - 1), volatility: 0.03).Select(b => b with { Volume = 1_000_000 })]))]);
+
+ private static BacktestDataset Stocks(int sessions, ulong seed = 300, int count = 25) =>
+ new([.. Enumerable.Range(0, count).Select(k => new BacktestInstrument(StrategyData.Share("S" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
+ StrategyData.OnBusinessDays([.. BacktestData.Walk(sessions, seed + (ulong)k, start: 50 + k, drift: 0.0004 * (k % 5), volatility: 0.015).Select(b => b with { Volume = 100_000 })], Monday)))], "USD");
+
+ // ---- crypto_relative_momentum ----
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheCryptoCandidateBuysTheStrongestOnSundaysOnlyWhileBitcoinRises()
+ {
+ var run = BacktestEngine.Run(new CryptoRelativeMomentum(), Coins(900, 0.002));
+ var entries = run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == CryptoRelativeMomentum.Reasons.Entry).Select(i => (d.Day, Intent: i))).ToList();
+ Assert.IsNotEmpty(entries);
+ Assert.IsTrue(entries.All(e => e.Day.DayOfWeek == DayOfWeek.Sunday), "the review is on the Sunday close");
+ Assert.IsTrue(entries.All(e => e.Intent.TargetWeight <= 1m / 3m && e.Intent.StopOffset > 0m && e.Intent.Strength > 0));
+ Assert.IsTrue(run.Fills.Where(f => f.Side == OrderSide.Buy).All(f => f.Day.DayOfWeek == DayOfWeek.Monday), "bought at the open of Monday");
+
+ // Never more than three coins at once.
+ var held = new Dictionary(StringComparer.Ordinal);
+ foreach (var day in run.Fills.GroupBy(f => f.Day))
+ {
+ foreach (var fill in day)
+ {
+ // A sale leaves a residue of the fee, which the engine writes off: it is no position.
+ held[fill.Symbol] = fill.Side == OrderSide.Buy ? held.GetValueOrDefault(fill.Symbol) + fill.Quantity : 0m;
+ }
+
+ Assert.IsLessThanOrEqualTo(3, held.Count(h => h.Value > 0m));
+ }
+
+ // Bitcoin up and down: an entry only on the days it closes above its average.
+ var mixed = Coins(1200, 0, seed: 90);
+ var bought = BacktestEngine.Run(new CryptoRelativeMomentum(), mixed).Decisions.Where(d => d.Proposed.Any(i => i.Reason == CryptoRelativeMomentum.Reasons.Entry)).ToList();
+ var sundays = mixed.Sessions.Where(d => d.DayOfWeek == DayOfWeek.Sunday && d > mixed.Sessions[450]).ToList();
+ bool Up(DateOnly day) => mixed["BTC-EUR"]!.SeriesThrough(day) is { } s && s.Close(s.Count - 1) > Indicators.Sma(s, 200);
+ Assert.IsTrue(bought.All(d => Up(d.Day)) && bought.Count > 0 && sundays.Any(d => !Up(d)), "the path must have both");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheCryptoCandidateLeavesEverythingWhenBitcoinFallsBelowItsAverage()
+ {
+ var data = Coins(900, -0.003);
+ var day = data.Sessions[^1];
+ var state = new PortfolioState(9_000m, new Dictionary { ["ETH-EUR"] = new(1m, 100m, null, day.AddDays(-3)) });
+ var intent = BacktestEngine.DecideOnce(new CryptoRelativeMomentum(), data, state, day).Proposed.Single();
+ Assert.AreEqual(("ETH-EUR", 0m, CryptoRelativeMomentum.Reasons.ExitMarket), (intent.Symbol, intent.TargetWeight!.Value, intent.Reason));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheCryptoCandidateRanksTheUniverseChosenForTheTrend()
+ {
+ var asked = new List();
+ var context = new UniverseContext(new DateOnly(2026, 5, 20), ["BTC-EUR"])
+ {
+ Members = (strategy, day) =>
+ {
+ asked.Add(strategy + " " + day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
+ return ["BTC-EUR", "ETH-EUR"];
+ },
+ };
+ CollectionAssert.AreEqual(new[] { "BTC-EUR", "ETH-EUR" }, new CryptoRelativeMomentum().Universe(context).ToArray());
+ CollectionAssert.AreEqual(new[] { "crypto_trend 2026-05-01" }, asked);
+ }
+
+ // ---- stock_ath_breakout ----
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheStockCandidateBuysOnlyTheHighestCloseOfTheWholeHistory()
+ {
+ // A high of 120, a long fall, and a close at 115 that beats everything of the last 400 sessions but not the old high.
+ var closes = Enumerable.Range(0, 100).Select(i => 100 + (0.2 * i)).Concat(Enumerable.Range(0, 400).Select(i => 80 + (0.05 * i))).Append(115d).ToList();
+ var bars = StrategyData.OnBusinessDays(StrategyData.FromCloses(closes, range: 1, volume: 100_000), Monday);
+ var context = new Func, IReadOnlyList>(b =>
+ {
+ var data = new BacktestDataset([new BacktestInstrument(StrategyData.Share("AAA"), b)], "USD");
+ return BacktestEngine.DecideOnce(new StockAthBreakout(), data, new PortfolioState(10_000m, new Dictionary()), data.Sessions[^1]).Proposed;
+ });
+ Assert.IsEmpty(context(bars), "115 is the highest of 400 sessions, not of all of them");
+ Assert.AreEqual(StockAthBreakout.Reasons.Entry, context([.. bars.Skip(100)]).Single().Reason, "with a short history the same close would look like a record");
+
+ var record = context([.. bars.Take(500), bars[^1] with { Close = 121, High = 122 }]).Single();
+ Assert.IsTrue(record.TargetWeight is > 0m and <= 0.10m);
+ Assert.IsGreaterThan(0m, record.StopOffset!.Value);
+ Assert.IsTrue(StockAthBreakoutFamily.Instance.NeedsFullHistory);
+ Assert.AreEqual(new DateOnly(2009, 1, 1), new TrialData(TrialSources.Database, Venues.Alpaca, ["AAA"], Monday, Monday.AddDays(30)) { FullHistory = true }.HistoryStart());
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void ThePlansAlreadyWrittenKeepTheirFingerprint()
+ {
+ var data = new TrialData(TrialSources.Research, EuroHistory.Venue, ["BTCEUR"], Monday, Monday.AddDays(30));
+ var plain = System.Text.Json.JsonSerializer.Serialize(data, TrialPlan.Json);
+ Assert.IsFalse(plain.Contains("full_history", StringComparison.Ordinal), plain);
+ StringAssert.Contains(System.Text.Json.JsonSerializer.Serialize(data with { FullHistory = true }, TrialPlan.Json), "\"full_history\":true");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheStockCandidateKeepsToItsPlacesItsCapitalAndAStopThatOnlyRises()
+ {
+ var strategy = new StockAthBreakout(new StockAthBreakoutSettings { MaxPositions = 6 });
+ var run = BacktestEngine.Run(strategy, Stocks(700));
+ Assert.IsTrue(run.Fills.Any(f => f.Side == OrderSide.Buy));
+ var held = new Dictionary(StringComparer.Ordinal);
+ foreach (var fill in run.Fills)
+ {
+ held[fill.Symbol] = held.GetValueOrDefault(fill.Symbol) + (fill.Side == OrderSide.Buy ? fill.Quantity : -fill.Quantity);
+ Assert.IsLessThanOrEqualTo(6, held.Count(h => h.Value > 0.0001m));
+ }
+
+ Assert.IsTrue(run.Fills.Where(f => f.Side == OrderSide.Sell).All(f => f.Reason is not StockAthBreakout.Reasons.Entry), "it leaves only through the stop");
+ foreach (var group in run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == StockAthBreakout.Reasons.StopMoved).Select(i => (d.Day, i.Symbol, Stop: i.Stop!.Value))).GroupBy(s => s.Symbol))
+ {
+ var list = group.OrderBy(s => s.Day).ToList();
+ for (var i = 1; i < list.Count; i++)
+ {
+ var exited = run.Fills.Any(f => f.Symbol == group.Key && f.Side == OrderSide.Sell && f.Day > list[i - 1].Day && f.Day <= list[i].Day);
+ Assert.IsTrue(exited || list[i].Stop > list[i - 1].Stop, $"{list[i - 1]} → {list[i]}");
+ }
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void NeitherCandidateLooksAhead()
+ {
+ var crypto = LookAheadCheck.Run(_ => new CryptoRelativeMomentum(), Coins(900, 0.002));
+ Assert.IsTrue(crypto.Passed, string.Join("\n", crypto.Mismatches.Take(3)));
+ var stock = LookAheadCheck.Run(_ => new StockAthBreakout(), Stocks(700));
+ Assert.IsTrue(stock.Passed, string.Join("\n", stock.Mismatches.Take(3)));
+ }
+
+ // ---- The protocol and its files ----
+
+ [TestMethod]
+ public void EveryCandidateHasItsOutcomeAndNoneHasAWayToTrade()
+ {
+ CollectionAssert.AreEqual(new[] { "crypto_trend", "equity_momentum", "equity_meanrev" }, StrategyNames.Base.Select(b => b.Name).ToArray());
+ foreach (var name in Names)
+ {
+ var outcome = BacktestOutcomes.Find(name);
+ Assert.IsNotNull(outcome, name);
+ Assert.AreEqual("docs/backtests/" + name + ".md", outcome.Report);
+ Assert.IsNotNull(StrategyCatalog.Find(name));
+ Assert.IsFalse(ClientOrderIds.StrategyCodes.ContainsKey(name), "without an order code the order manager refuses it");
+ Assert.IsNull(StrategyPipeline.DefaultShare(name));
+ Assert.IsNotNull(StrategyPipeline.ResearchShare(name), "its trials keep the risk limits");
+ Assert.AreNotEqual(name, StrategyNames.Label(name));
+ }
+
+ var crypto = BacktestOutcomes.Find(StrategyNames.CryptoRelativeMomentum)!;
+ Assert.IsNotNull(crypto.PlanHash, "it was run");
+ StringAssert.Contains(crypto.Verdict, crypto.Passed ? "Protocollo superato" : "Scartata nei test");
+ Assert.IsNull(BacktestOutcomes.Find(StrategyNames.StockAthBreakout)!.PlanHash, "it waits for the Alpaca history");
+ Assert.ThrowsExactly(() => ClientOrderIds.Build("ABCD", TradingEnvironments.Simulation, StrategyNames.CryptoRelativeMomentum, OrderPurpose.Entry, "ABCDEFGH", 0));
+ }
+
+ [TestMethod]
+ public async Task TheProtocolOfTheCandidateIsWrittenAsTheOthersAndLeavesTheirFilesAlone()
+ {
+ var folder = TempFolder.Create("candidate");
+ try
+ {
+ var store = new ResearchStore(Path.Combine(folder, "research"));
+ Directory.CreateDirectory(Path.Combine(folder, "research"));
+ var random = new Random(5);
+ var from = new DateOnly(2017, 8, 1);
+ var to = new DateOnly(2020, 12, 31);
+ foreach (var coin in new[] { "BTC", "ETH", "XRP", "LTC", "ADA" })
+ {
+ var price = 100d;
+ await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, Enumerable.Range(0, to.DayNumber - from.DayNumber + 1).Select(i =>
+ {
+ price *= 1 + 0.0005 + ((random.NextDouble() - 0.5) * 0.06);
+ var p = Math.Round((decimal)price, 6);
+ return new ResearchBar(new DateTimeOffset(from.AddDays(i).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), p, p * 1.01m, p * 0.99m, p, 1_000_000m) { QuoteVolume = p * 1_000_000m };
+ }).ToList(), _none);
+ }
+
+ var outcome = await CandidateProtocol.RunCryptoAsync(Path.Combine(folder, "research"), to, new DateTimeOffset(2021, 1, 2, 0, 0, 0, TimeSpan.Zero), null, _none);
+ Assert.HasCount(1, outcome.Runs, "a choice of three coins among three would say nothing");
+ Assert.HasCount(9, outcome.Runs[0].Report.Variants);
+ CollectionAssert.AreEqual(new[] { 1m, 2m, 3m }, outcome.Runs[0].Report.Costs.Select(c => c.Multiplier).ToArray());
+ Assert.IsTrue(outcome.Runs[0].Report.LookAhead.Passed);
+ Assert.AreEqual(outcome.Runs[0].Report.Passed, outcome.Qualification.Passed);
+ Assert.IsNotNull(outcome.Qualification.PlanHash);
+ StringAssert.Contains(ProtocolReport.Markdown(outcome, "crypto_relative_momentum", ["prova"], "anubis backtest candidates"), "Una candidata non opera");
+ }
+ finally
+ {
+ TempFolder.Delete(folder);
+ }
+ }
+
+ // ---- No capital, no order, no stage ----
+
+ private static StageBook Stages(TradingRig rig) => new(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
+
+ [TestMethod]
+ public async Task ACandidateWithAnOutcomeThatPassedStaysInObservationAndNobodyCanMoveIt()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
+ await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
+ var stages = Stages(rig);
+ var passed = new Qualification { Passed = true, Verdict = "ok", Report = "r", PlanHash = "h" };
+ foreach (var name in Names)
+ {
+ await stages.ApplyQualificationAsync(name, passed, _none).ConfigureAwait(false);
+ rig.Clock.Advance(TimeSpan.FromDays(200));
+ var stage = (await stages.GetAsync(name, _none).ConfigureAwait(false))!;
+ Assert.AreEqual((StrategyStages.Observation, 0m, 0m), (stage.Stage, stage.Capital, stage.Share));
+ Assert.IsFalse(StageBook.IsArchived(stage));
+ Assert.AreEqual("candidate", (await Assert.ThrowsExactlyAsync(() => stages.MoveAsync(name, StrategyStages.Simulation, "x", "utente", _none))).Code);
+ Assert.AreEqual("candidate", (await Assert.ThrowsExactlyAsync(() =>
+ stages.ConfirmLiveAsync(new LiveConfirmation(name, Guid.NewGuid(), "", "", null, "utente"), _none))).Code);
+ await stages.ApplyQualificationAsync(name, passed with { Passed = false }, _none).ConfigureAwait(false);
+ Assert.IsTrue(StageBook.IsArchived((await stages.GetAsync(name, _none).ConfigureAwait(false))!), "turned down on its data: archived");
+ await stages.ApplyQualificationAsync(name, passed with { Passed = false, PlanHash = null }, _none).ConfigureAwait(false);
+ Assert.IsFalse(StageBook.IsArchived((await stages.GetAsync(name, _none).ConfigureAwait(false))!), "waiting for its data is not turned down");
+ }
+
+ var crypto = (await stages.GetAsync(StrategyNames.CryptoTrend, _none).ConfigureAwait(false))! with { Qualification = passed with { Passed = false } };
+ Assert.IsFalse(StageBook.IsArchived(crypto), "only a candidate is archived");
+ }
+
+ [TestMethod]
+ public async Task TheCandidatesAreNoPartOfTheCapitalPlan()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ await AccountSetup.EnsureAsync(rig.Db, rig.Clock, false, false, _none).ConfigureAwait(false);
+ var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, new FxStore(rig.Db, rig.Clock));
+ await capital.SetAsync(Venues.Okx, 4_000m, "test", _none).ConfigureAwait(false);
+ var strategies = await capital.StrategiesAsync(Venues.Okx, _none).ConfigureAwait(false);
+ Assert.AreEqual((StrategyNames.CryptoTrend, 4_000m), (strategies.Single().Strategy, strategies.Single().Capital));
+ Assert.AreEqual(0m, (await Stages(rig).GetAsync(StrategyNames.CryptoRelativeMomentum, _none).ConfigureAwait(false))!.Capital);
+ await Assert.ThrowsExactlyAsync(() => capital.SetSharesAsync(Venues.Okx,
+ new Dictionary { [StrategyNames.CryptoTrend] = 0.5m, [StrategyNames.CryptoRelativeMomentum] = 0.5m }, "test", _none)).ConfigureAwait(false);
+ }
+
+ private static Task AddAsync(TradingRig rig, string strategy, Guid account, string stage, Qualification? outcome = null) =>
+ rig.Db.WriteAsync(s => s.ExecuteAsync(
+ "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since, qualification) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 0, @now, @q)",
+ _none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account), ("st", stage), ("j", new DbJson("{}")), ("now", rig.Clock.UtcNow),
+ ("q", outcome is null ? null : new DbJson(System.Text.Json.JsonSerializer.Serialize(outcome, Qualification.Json)))), _none);
+
+ [TestMethod]
+ public async Task TheLiveCandidateNotesItsSignalsAndSendsNothing()
+ {
+ await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(20), stage: StrategyStages.Observation).ConfigureAwait(false);
+ await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation).ConfigureAwait(false);
+ for (var day = LiveFrom; day <= LiveFrom.AddDays(20); day = day.AddDays(1))
+ {
+ await live.DayAsync(day, morning: 3).ConfigureAwait(false);
+ }
+
+ var runs = await live.Rig.QueryAsync("SELECT mode, state FROM engine_runs WHERE strategy = @s", r => (Mode: r.Text("mode"), State: r.TextOrNull("state")),
+ ("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
+ Assert.HasCount(21, runs);
+ Assert.IsTrue(runs.All(r => r.Mode == DecisionModes.Observation && r.State is null));
+ Assert.IsEmpty(live.Sent);
+ foreach (var table in new[] { "planned_orders", "orders", "fills", "executions" })
+ {
+ Assert.AreEqual(0, (await live.Rig.QueryAsync("SELECT COUNT(*) AS n FROM " + table, r => r.Number("n")).ConfigureAwait(false)).Single(), table);
+ }
+
+ var examples = await live.Rig.QueryAsync("SELECT symbol FROM ml_features WHERE strategy = @s", r => r.Text("symbol"), ("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
+ Assert.IsNotEmpty(examples, "its signals are examples too (SPEC 11.2)");
+ }
+
+ [TestMethod]
+ public async Task ACandidateOutOfObservationInTheDatabaseDecidesNothingAndItIsSaidOnce()
+ {
+ await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(3)).ConfigureAwait(false);
+ await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Simulation).ConfigureAwait(false);
+ for (var i = 0; i < 3; i++)
+ {
+ await live.DayAsync(LiveFrom.AddDays(i), morning: 3).ConfigureAwait(false);
+ }
+
+ var runs = await live.Rig.QueryAsync("SELECT strategy FROM engine_runs", r => r.Text("strategy")).ConfigureAwait(false);
+ Assert.HasCount(3, runs);
+ Assert.IsTrue(runs.All(r => r == StrategyNames.CryptoTrend));
+ Assert.HasCount(1, await live.Rig.QueryAsync("SELECT id FROM journal WHERE code = 'candidate_stage'", r => r.Id("id")).ConfigureAwait(false));
+ }
+
+ [TestMethod]
+ public async Task AnArchivedCandidateDecidesNoMoreAndAWaitingOneDoes()
+ {
+ foreach (var (plan, expected) in new[] { ("h", 0), (null, 2) })
+ {
+ await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(2)).ConfigureAwait(false);
+ await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation,
+ new Qualification { Passed = false, Verdict = "v", Report = "r", PlanHash = plan }).ConfigureAwait(false);
+ for (var i = 0; i < 2; i++)
+ {
+ await live.DayAsync(LiveFrom.AddDays(i), morning: 3).ConfigureAwait(false);
+ }
+
+ var runs = await live.Rig.QueryAsync("SELECT id FROM engine_runs WHERE strategy = @s", r => r.Id("id"), ("s", StrategyNames.CryptoRelativeMomentum)).ConfigureAwait(false);
+ Assert.HasCount(expected, runs, plan ?? "waiting");
+ }
+ }
+
+ [TestMethod]
+ public async Task ACandidateThatFailsStopsNobody()
+ {
+ await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(2)).ConfigureAwait(false);
+
+ // Its account does not exist any more and its outcome is not an outcome: reading its row throws.
+ await AddAsync(live.Rig, StrategyNames.CryptoRelativeMomentum, live.Okx.AccountId, StrategyStages.Observation).ConfigureAwait(false);
+ await live.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q WHERE strategy = @s", _none, ("q", new DbJson("[]")), ("s", StrategyNames.CryptoRelativeMomentum)), _none)
+ .ConfigureAwait(false);
+ await live.DayAsync(LiveFrom, morning: 3).ConfigureAwait(false);
+ Assert.AreEqual(0, live.Failures);
+ Assert.HasCount(1, await live.Rig.QueryAsync("SELECT id FROM engine_runs WHERE strategy = @s", r => r.Id("id"), ("s", StrategyNames.CryptoTrend)).ConfigureAwait(false));
+ }
+
+ [TestMethod]
+ public async Task TheStockCandidateLooksAtStocksWithTheirWholeHistory()
+ {
+ var last = LiveFrom.AddDays(8);
+ await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
+ await AddAsync(live.Rig, StrategyNames.StockAthBreakout, live.Alpaca.AccountId, StrategyStages.Observation).ConfigureAwait(false);
+
+ // A close above all the others, older than the 450 days the stock strategies read.
+ var bars = await live.Rig.QueryAsync("SELECT MIN(day) AS d FROM bars_1d", r => r.Text("d")).ConfigureAwait(false);
+ Assert.IsLessThan(LiveFrom.AddDays(-450), BarStore.ParseDay(bars.Single()));
+ for (var day = LiveFrom; day <= last; day = day.AddDays(1))
+ {
+ await live.SessionAsync(day).ConfigureAwait(false);
+ }
+
+ var decisions = await live.Rig.QueryAsync("SELECT symbol, data FROM decisions WHERE strategy = @s AND stage = 'strategy'", r => r.Text("symbol"), ("s", StrategyNames.StockAthBreakout))
+ .ConfigureAwait(false);
+ Assert.IsFalse(decisions.Contains(StrategyNames.MarketSymbol), "SPY is data");
+ Assert.IsGreaterThan(0, await CountAsync(live.Rig, StrategyNames.StockAthBreakout).ConfigureAwait(false));
+ Assert.AreEqual(0, (await live.Rig.QueryAsync("SELECT COUNT(*) AS n FROM planned_orders WHERE strategy = @s", r => r.Number("n"), ("s", StrategyNames.StockAthBreakout)).ConfigureAwait(false)).Single());
+ }
+
+ private static async Task CountAsync(TradingRig rig, string strategy) =>
+ (int)(await rig.QueryAsync("SELECT COUNT(*) AS n FROM engine_runs WHERE strategy = @s", r => r.Number("n"), ("s", strategy)).ConfigureAwait(false)).Single();
+}
diff --git a/tests/Anubis.Tests/StrategyScreensTests.cs b/tests/Anubis.Tests/StrategyScreensTests.cs
index 458f4ef..ed1416e 100644
--- a/tests/Anubis.Tests/StrategyScreensTests.cs
+++ b/tests/Anubis.Tests/StrategyScreensTests.cs
@@ -43,7 +43,9 @@ public sealed class StrategyScreensTests
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
var strategies = await server.TextAsync("/strategie");
- foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" })
+ foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni", "1 strategia", "Nuovi massimi storici sulle azioni USA",
+ "Raccoglie segnali senza fare ordini: 14 in 31 giorni. Servono almeno 90 giorni per giudicarla.", "31 giorni su 90", "Momentum relativo tra crypto",
+ "Scartata nei test: tolti i costi, il risultato è vicino a zero. Resta in archivio, non riceve capitale.", "Non supera i test" })
{
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
}
@@ -83,6 +85,19 @@ public sealed class StrategyScreensTests
StringAssert.Contains(page, "In attesa dei dati");
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
+ // The candidates of 8.4: the discarded one with its verdict, the other waiting, no button for either, and none by hand.
+ foreach (var text in new[] { "Momentum relativo tra crypto", "Scartata nei test", "Nuovi massimi storici sulle azioni USA", "0 in 0 giorni" })
+ {
+ StringAssert.Contains(page, text);
+ }
+
+ foreach (var (candidate, _) in StrategyNames.Candidates)
+ {
+ Assert.IsFalse(page.Contains("/azioni/strategie/" + candidate, StringComparison.Ordinal), "A candidate has no button.");
+ using var post = await server.PostFormAsync("/strategie", $"/azioni/strategie/{candidate}/simulazione");
+ Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(candidate, CancellationToken.None))!.Stage);
+ }
+
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs
index 95b2db1..f0e3049 100644
--- a/tests/Anubis.Tests/TradingServiceTests.cs
+++ b/tests/Anubis.Tests/TradingServiceTests.cs
@@ -36,16 +36,18 @@ public sealed class TradingServiceTests
// Every strategy starts in observation, crypto on OKX and stocks on Alpaca.
CollectionAssert.AreEqual(new[]
{
+ (StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca simulatore", StrategyNames.Observation),
+ (StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray());
// A second start finds what is there.
using var again = Service(rig, http);
await again.StartAsync(_none).ConfigureAwait(false);
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM accounts", r => r.Id("id")).ConfigureAwait(false));
- Assert.HasCount(3, await StrategiesAsync(rig).ConfigureAwait(false));
+ Assert.HasCount(5, await StrategiesAsync(rig).ConfigureAwait(false));
}
[TestMethod]
@@ -62,9 +64,11 @@ public sealed class TradingServiceTests
Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2).");
CollectionAssert.AreEqual(new[]
{
+ (StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca paper", StrategyNames.Observation),
+ (StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is.");
}
@@ -90,7 +94,7 @@ public sealed class TradingServiceTests
Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false));
Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call.");
- var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
+ var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state WHERE share > 0 ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { (StrategyNames.CryptoTrend, 1000m), (StrategyNames.EquityMeanrev, 550m), (StrategyNames.EquityMomentum, 1650m) }, shares.ToArray());
// The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate.