using System.Net.Http.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.News;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
///
/// Phase 11 (ADR 0023, 0027): news, calendar and earnings only measured. By default nothing they say changes a decision,
/// and each rule writes in the shadow what it would have done.
///
[TestClass]
public sealed class MeasuredRulesTests
{
private static readonly CancellationToken _none = CancellationToken.None;
// ---- The switch ---------------------------------------------------------------------------------------------
///
/// A new installation starts with the rules only measured; a part built without settings (only tests do that) lets them
/// act. A change writes its line once, in the same transaction, and the value of an earlier moment is read back.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSwitchStartsMeasuredAndRemembersWhatItWas()
{
await using var test = await TestDb.CreateAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
await Migrations.MigrateAsync(test.Db, clock, null, _none);
var settings = new SettingsStore(test.Db, clock, new EventBus());
Assert.AreEqual(ExternalRules.Measured, (await settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsFalse(await ExternalRules.MeasuredAsync(null, _none), "without settings the rules act, as the five rows are on");
var before = clock.UtcNow;
clock.Advance(TimeSpan.FromHours(1));
async Task SetAsync(string value) => await settings.SetAsync(ExternalRules.Setting.Key, value, "admin",
(s, old) => ExternalRules.WriteChangeAsync(s, clock, old, value, "admin", _none), _none);
Assert.IsTrue(await SetAsync(ExternalRules.Active));
Assert.IsFalse(await SetAsync(ExternalRules.Active), "nothing changed: no line");
var lines = await NewsRulesTests.DiaryAsync(test.Db);
Assert.HasCount(1, lines);
StringAssert.StartsWith(lines[0], "Notizie, calendario e trimestrali da «solo misurate» a «attive»");
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none), "no Telegram");
Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, before, _none), "an hour ago they were only measured");
Assert.IsFalse(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none));
}
/// The tests of Phase 7 run with the rules acting: the support of the tests sets «attive», without a change in the log.
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSupportOfTheTestsSetsTheRulesActing()
{
await using var test = await DatabaseTests.MigratedAsync();
var settings = new SettingsStore(test.Db, new ManualClock(DateTimeOffset.UnixEpoch), new EventBus());
Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsEmpty(await settings.HistoryAsync(ExternalRules.Setting.Key));
await DatabaseTests.MeasuredAsync(test.Db);
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
}
// ---- The decisions ------------------------------------------------------------------------------------------
///
/// The scene of NewsRulesTests: a confirmed serious event on ETH and a negative story on SOL before the crypto close. With
/// the rules measured both purchases go, nothing is held, nothing is said, and each rule leaves one case in the shadow.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AConfirmedSevereStoryChangesNothingAndIsMeasuredInTheShadow()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39));
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
live.UseMeasured();
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9,
"CoinDesk", trusted: true);
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero),
3, -0.8, "CoinDesk", trusted: true);
await live.DayAsync(day);
var fills = await live.LiveFillsAsync();
Assert.IsTrue(fills.Any(f => f is { Symbol: "ETH-EUR", Side: OrderSide.Buy }), string.Join(", ", fills));
Assert.IsTrue(fills.Any(f => f is { Symbol: "SOL-EUR", Side: OrderSide.Buy }), string.Join(", ", fills));
var held = (await live.Rig.QueryAsync("SELECT symbol, reasons FROM decisions WHERE outcome IN (@r, @p)", r => (Symbol: r.TextOrNull("symbol"), Reasons: r.Text("reasons")),
("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed))).Where(d => d.Reasons.Contains("news_", StringComparison.Ordinal) || d.Reasons.Contains("calendar", StringComparison.Ordinal));
Assert.IsFalse(held.Any(), "no row of a block");
var diary = await NewsRulesTests.DiaryAsync(live.Rig.Db);
Assert.IsFalse(diary.Any(l => l.Contains("Non compro", StringComparison.Ordinal) || l.Contains("Motivo: «", StringComparison.Ordinal)), string.Join(" | ", diary));
Assert.AreEqual(0L, await live.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind LIKE 'news%'"), _none), "no notice of the news");
var cases = await live.Rig.QueryAsync("SELECT improvement, symbol, decided_day, factor FROM shadow_cases WHERE improvement LIKE 'rule_%'",
r => (Rule: r.Text("improvement"), Symbol: r.Text("symbol"), Day: r.Text("decided_day"), Factor: r.Measure("factor")));
Assert.IsFalse(cases.GroupBy(c => (c.Rule, c.Symbol, c.Day)).Any(g => g.Count() > 1), "one case per rule, strategy, instrument and day");
// The crypto close of 31 August is decided just after midnight UTC: the case carries the day of the bar.
double Factor(string rule, string symbol) =>
cases.SingleOrDefault(c => c.Rule == rule && c.Symbol == symbol && c.Day == "2026-08-31") is { Rule: not null } found ? found.Factor
: throw new AssertFailedException($"No case {rule} on {symbol}: " + string.Join(", ", cases));
Assert.AreEqual(0, Factor(ShadowRules.NewsSevere, "ETH-EUR"), "the serious event would have left ETH out");
Assert.AreEqual(1, Factor(ShadowRules.NewsSevere, "SOL-EUR"));
Assert.AreEqual(0, Factor(ShadowRules.NewsNegative, "SOL-EUR"), "the negative story would have left SOL out");
Assert.AreEqual(1, Factor(ShadowRules.Macro, "ETH-EUR"), "no figure that morning");
}
/// The same scene with the rules acting writes no case in the shadow: the balance of the restrictions measures them.
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WithTheRulesActingNothingGoesToTheShadow()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39));
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9,
"CoinDesk", trusted: true);
await live.DayAsync(day);
Assert.IsEmpty(await live.Rig.QueryAsync("SELECT id FROM shadow_cases WHERE improvement LIKE 'rule_%'", r => r.Id("id")));
}
///
/// The scene of the earnings: the close of 1 September plans BBB, which reports on 3 September before the open. With the
/// rules measured the purchase goes, the strategy never leaves for the report, and both rules of the earnings are noted
/// at the entry. Once the operation has its label, the exit is measured against the label made with the report.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MeanReversionEntersBeforeEarningsAndNeverLeavesForThem()
{
var day = new DateOnly(2026, 9, 1);
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41));
await new CalendarEventStore(stocks.Rig.Db, stocks.Rig.Clock).UpsertAsync(
[new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale BBB", new DateTimeOffset(2026, 9, 3, 11, 0, 0, TimeSpan.Zero), false, "test", "earnings:BBB")
{ Symbol = "BBB", TimeHint = "bmo" }], _none);
var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock);
var learning = new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null };
stocks.UseMeasured(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct), true), learning);
await stocks.SessionAsync(day);
var planned = await stocks.Rig.QueryAsync("SELECT i.symbol FROM planned_orders p JOIN instruments i ON i.id = p.instrument_id WHERE p.side = 'buy'", r => r.Text("symbol"));
CollectionAssert.Contains(planned.ToList(), "BBB", "the report tomorrow keeps nothing out");
var example = (await learning.Store.LiveAsync(StrategyNames.EquityMeanrev, _none)).Single(e => e.Symbol == "BBB");
Assert.IsFalse(example.Features.ContainsKey(Clues.EarningsDays), "no earnings clue: the label never leaves before a report");
for (var d = day.AddDays(1); d <= day.AddDays(20); d = d.AddDays(1))
{
await stocks.SessionAsync(d);
}
Assert.IsFalse((await stocks.Rig.QueryAsync("SELECT reasons FROM decisions", r => r.Text("reasons"))).Any(r => r.Contains(EquityMeanrev.Reasons.ExitEarnings, StringComparison.Ordinal)),
"never the exit for the report");
var cases = await stocks.Rig.QueryAsync("SELECT improvement, factor, data FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement LIKE 'rule_earnings%'",
r => (Rule: r.Text("improvement"), Factor: r.Measure("factor"), Data: r.Json("data").Text));
Assert.AreEqual(0, cases.Single(c => c.Rule == ShadowRules.EarningsEntry).Factor, "the filter would have kept BBB out");
var exit = cases.Single(c => c.Rule == ShadowRules.EarningsExit);
StringAssert.Contains(exit.Data, "\"Report\":\"2026-09-03\"");
await new LearningCycle(stocks.Rig.Db, stocks.Rig.Clock, learning, stocks.Engine.LabelDataAsync).LabelAsync(_none);
await learning.Shadow.MeasureAsync(stocks.Engine.LabelDataAsync, null, null, _none);
var measured = await stocks.Rig.QueryAsync("SELECT factor, effect, measured_at FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement = @i",
r => (Factor: r.Measure("factor"), Effect: r.IsNull("effect") ? (double?)null : r.Measure("effect"), Done: !r.IsNull("measured_at")), ("i", ShadowRules.EarningsExit));
Assert.IsTrue(measured.Single().Done);
Assert.AreEqual(0, measured.Single().Factor, "with the report the label leaves on the close before it");
Assert.IsNotNull(measured.Single().Effect);
}
///
/// A purchase decided with the rules measured goes at the open as it was decided, even when they act again in the
/// evening: the gate at send time belongs to the decisions taken with «attive» (ADR 0027 point 2).
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task APurchaseDecidedWithTheRulesMeasuredGoesEvenIfTheyActBeforeItLeaves()
{
var day = new DateOnly(2026, 9, 1);
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41));
var switched = new DateTimeOffset(2026, 9, 1, 23, 0, 0, TimeSpan.Zero);
stocks.UseMeasured((_, _) => Task.FromResult(null), new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null },
new HoldingGate(new EntryHold(NewsReasons.Severe, new DateTimeOffset(2026, 9, 9, 0, 0, 0, TimeSpan.Zero), "fatto")), at => at < switched);
await stocks.SessionAsync(day);
await stocks.SessionAsync(day.AddDays(1));
var fills = await stocks.LiveFillsAsync();
Assert.IsTrue(fills.Any(f => f is { Symbol: "BBB", Side: OrderSide.Buy }), string.Join(", ", fills));
Assert.IsEmpty(await stocks.Rig.QueryAsync("SELECT id FROM decisions WHERE stage = @o AND outcome IN (@r, @p)", r => r.Id("id"),
("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed)), "nothing held at the open");
}
// A rule that would hold every purchase, asked only with the rules acting.
private sealed class HoldingGate(EntryHold hold) : IEntryGate
{
public Task HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(at < hold.Until ? hold : null);
public Task KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult(null);
}
///
/// The first start of this version writes the switch: on a new installation only the row; on one that already decided,
/// «attive» until now in the change log and one line in the diary, never twice.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstStartWritesTheSwitchAndRemembersTheRulesActedBefore()
{
foreach (var decided in new[] { false, true })
{
await using var test = await TestDb.CreateAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
await Migrations.MigrateAsync(test.Db, clock, null, _none);
var before = clock.UtcNow.AddDays(-1);
if (decided)
{
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) " +
"VALUES (@id, 'crypto_trend', 'k', '2026-12-02', @d, 'observation', NULL, NULL, @t)", _none, ("id", Ids.NewId(clock)), ("d", Guid.NewGuid()), ("t", before)), _none);
}
Assert.AreEqual(decided, await ExternalRules.SettleAsync(test.Db, clock, _none));
clock.Advance(TimeSpan.FromHours(1));
Assert.IsFalse(await ExternalRules.SettleAsync(test.Db, clock, _none), "once");
var settings = new SettingsStore(test.Db, clock, new EventBus());
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
Assert.AreEqual(!decided, await ExternalRules.MeasuredAtAsync(settings, before, _none), "before the upgrade the rules acted");
Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none));
var history = await settings.HistoryAsync(ExternalRules.Setting.Key);
Assert.HasCount(decided ? 1 : 0, history);
var lines = await NewsRulesTests.DiaryAsync(test.Db);
Assert.HasCount(decided ? 1 : 0, lines);
if (decided)
{
Assert.AreEqual(ExternalRules.Upgrade, history[0].ChangedBy);
StringAssert.StartsWith(lines[0], "Con questa versione notizie, calendario e trimestrali sono solo misurate");
}
}
}
/// With the rules measured the watcher of the news writes nothing: no note, no line, no notice.
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWatcherIsSilentWhileTheRulesAreMeasured()
{
await using var test = await DatabaseTests.MigratedAsync();
var (clock, settings, specs) = await NewsAnalystTests.SetUpAsync(test.Db);
await DatabaseTests.MeasuredAsync(test.Db);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana upgrade delayed by a week", clock.UtcNow.AddHours(-1), 3, -0.7, "CoinDesk", trusted: true);
Assert.AreEqual(0, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none));
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_notes"), _none), "no note");
Assert.IsEmpty(await NewsRulesTests.DiaryAsync(test.Db));
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none));
// The same story with the rules acting: the line of Phase 7.
await settings.SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin");
Assert.AreEqual(1, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none));
Assert.HasCount(1, await NewsRulesTests.DiaryAsync(test.Db));
}
// ---- The model ----------------------------------------------------------------------------------------------
/// The seven outside clues stay out of a training with the rules measured, however many live examples carry them; VIX goes in.
[TestMethod]
[TestCategory(Category.Unit)]
public void TheOutsideCluesStayOutOfTraining()
{
CollectionAssert.AreEquivalent(
new[] { Clues.Tone1, Clues.Tone3, Clues.Count1, Clues.Count3, Clues.WorstEvent, Clues.FearGreed, Clues.EarningsDays }, Clues.External.ToList());
Assert.IsFalse(Clues.IsExternal(Clues.Vix) || Clues.IsExternal(Clues.Funding) || Clues.IsExternal(Clues.OpenInterest), "market numbers stay");
Assert.IsFalse(Clues.HasExternal(FirstModel.Embedded!.Model!.Clues), "the first model uses none of them");
var history = LearningModelTests.Cases(300, _ => 0.5);
IReadOnlyList examples =
[
.. history, .. LearningModelTests.Cases(400, _ => 0.5, 8, source: CaseSources.Live).Select((c, i) => c with
{
Features = new Dictionary(c.Features) { [Clues.FearGreed] = i, [Clues.Tone3] = i % 5, [Clues.EarningsDays] = i % 31, [Clues.Vix] = 10 + (i % 20) },
}),
];
var with = Trainer.CluesOf(examples);
var without = Trainer.CluesOf(examples, external: false);
Assert.Contains(Clues.FearGreed, with);
Assert.Contains(Clues.Vix, without);
Assert.IsFalse(without.Any(Clues.IsExternal), string.Join(", ", without));
}
///
/// A model in charge that uses fear and greed counts with the rules acting; with them measured it is set aside at the very
/// next decision, for that reason, and goes on estimating.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AModelWithAnOutsideClueIsSetAsideAtOnce()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
var model = LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.FearGreed] };
await LearningCycleTests.AddModelAsync(test.Db, clock, model, ModelStatuses.Champion);
await test.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { ActivatedAt = clock.UtcNow }, _none), _none);
var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus()));
var acting = await desk.GateAsync(_none);
Assert.IsTrue(acting.Counts);
Assert.IsFalse(acting.OutsideClues);
await DatabaseTests.MeasuredAsync(test.Db);
var measured = await desk.GateAsync(_none);
Assert.IsFalse(measured.Counts);
Assert.IsTrue(measured.Aside);
Assert.IsTrue(measured.OutsideClues);
Assert.IsNotNull(measured.Champion, "it keeps estimating");
}
///
/// The first night with the rules measured writes the day of the change in the history of the models, once; a model in
/// charge with an outside clue is set aside with its own words and nothing goes to the phone.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstNightWritesTheDayOfTheChangeOnce()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 2, 0, 0, TimeSpan.Zero));
// The switch written with the first start of this version, the evening before: the event says that day, not the night of the check.
await DatabaseTests.MeasuredAsync(test.Db, new DateTimeOffset(2026, 12, 2, 18, 0, 0, TimeSpan.Zero));
await LearningCycleTests.AddModelAsync(test.Db, clock, LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.Tone3] }, ModelStatuses.Champion);
var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus())) { First = null };
var cycle = new LearningCycle(test.Db, clock, desk, (_, _, _) => Task.FromResult(null));
await cycle.CheckAsync(_none);
clock.Advance(TimeSpan.FromDays(1));
await cycle.CheckAsync(_none);
var events = await desk.Models.EventsAsync(_none);
Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesMeasured).ToList());
StringAssert.StartsWith(events.Single(e => e.Kind == ModelEvents.RulesMeasured).Text, "Dal mercoledì 2 dicembre notizie, calendario e trimestrali non cambiano le decisioni");
Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesAside).ToList());
Assert.IsFalse(events.Any(e => e.Kind == ModelEvents.SetAside), "not an alarm");
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none));
Assert.IsNull((await desk.CycleAsync(_none)).ActivatedAt, "a model that cannot count does not start counting");
StringAssert.Contains(events.Single(e => e.Kind == ModelEvents.RulesAside).Text, "La domenica ne addestro una senza, che entra in prova come sfidante.");
// The rules act again: the model is back for that reason, and the words say why.
await new SettingsStore(test.Db, clock, new EventBus()).SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin");
clock.Advance(TimeSpan.FromDays(1));
await cycle.CheckAsync(_none);
StringAssert.StartsWith((await desk.Models.EventsAsync(_none)).Single(e => e.Kind == ModelEvents.RulesBack).Text,
"Notizie, calendario e trimestrali sono di nuovo attive: la versione");
}
// ---- The shadow ---------------------------------------------------------------------------------------------
///
/// Under six months from the first case a rule says «troppo presto»; then the criterion of ADR 0023 at 99%: 30 entries
/// changed and the whole interval above zero. Postponed entries are counted, not valued.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheRulesSayTooEarlyUnderSixMonthsAndAreJudgedAt99()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
var desk = new LearningDesk(test.Db, clock);
async Task CaseAsync(string rule, string symbol, DateOnly day, double factor, double? effect, string? kind = null) =>
await test.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO shadow_cases (id, improvement, strategy, symbol, decided_day, decision_id, factor, data, effect, measured_at, created_at, updated_at) " +
"VALUES (@id, @i, @s, @sy, @d, @dec, @f, @data, @e, @now, @now, @now)", _none, ("id", Ids.NewId(clock)), ("i", rule), ("s", StrategyNames.CryptoTrend), ("sy", symbol),
("d", BarStore.DayText(day)), ("dec", Guid.NewGuid()), ("f", factor), ("data", new DbJson(kind is null ? "{}" : "{\"Kind\":\"" + kind + "\"}")), ("e", effect), ("now", clock.UtcNow)), _none);
// Eight months of a rule that avoids a loss of about 2% each time, five times a month; one entry only postponed.
var first = new DateOnly(2026, 4, 1);
for (var m = 0; m < 8; m++)
{
for (var i = 0; i < 5; i++)
{
await CaseAsync(ShadowRules.NewsNegative, "C" + i, first.AddMonths(m).AddDays(i), 0, 0.02 + (0.001 * ((m + i) % 3)));
}
}
await CaseAsync(ShadowRules.NewsNegative, "P", first.AddDays(20), 1, 0, ShadowKinds.Postponed);
await CaseAsync(ShadowRules.NewsNegative, "I", first.AddDays(21), 0, null, ShadowKinds.Increase);
await CaseAsync(ShadowRules.NewsSevere, "Q", new DateOnly(2026, 11, 2), 0, -0.01);
var rules = await desk.Shadow.LoadRulesAsync(alpacaKeys: false, finnhubKey: false, _none);
var negative = rules.Single(r => r.Rule.Key == ShadowRules.NewsNegative);
Assert.AreEqual(42, negative.Examined);
Assert.AreEqual(40, negative.Changed);
Assert.AreEqual(1, negative.Postponed);
Assert.AreEqual(1, negative.Increases, "an increase held back is counted, not valued");
Assert.AreEqual(0.99, negative.Line.Level);
Assert.IsGreaterThan(0, negative.Line.Interval!.Value.Low);
Assert.AreEqual("Criterio raggiunto", negative.State);
Assert.IsTrue(negative.Met);
var severe = rules.Single(r => r.Rule.Key == ShadowRules.NewsSevere);
Assert.AreEqual("Troppo presto", severe.State);
Assert.AreEqual(new DateOnly(2027, 5, 2), severe.JudgedFrom);
Assert.AreEqual("In attesa delle chiavi Alpaca", rules.Single(r => r.Rule.Key == ShadowRules.EarningsEntry).State);
Assert.AreEqual("Nessun caso finora", rules.Single(r => r.Rule.Key == ShadowRules.Macro).State);
// At 95% the same months would give a narrower interval: the rules ask for more.
var at95 = negative.Line with { Level = 0.95 };
Assert.IsLessThan(negative.Line.Interval!.Value.High - negative.Line.Interval.Value.Low, at95.Interval!.Value.High - at95.Interval.Value.Low);
}
/// The entry filter of the strategy as a pure rule: three sessions after the entry, the weekend skipped.
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEarningsRuleSkipsTheWeekend()
{
var thursday = new DateOnly(2026, 9, 3);
var friday = thursday.AddDays(1);
Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 9), 3), "Friday, Monday, Tuesday, Wednesday");
Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 10), 3));
Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, thursday.AddDays(-1), 3), "a report already out");
Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, thursday, 3), "out after today's close");
}
// ---- The page -----------------------------------------------------------------------------------------------
///
/// The switch changes only from the settings form: the programs' interface refuses it; with real money, only measuring
/// asks for the phrase and the password; acting again is free; each change writes one line in the diary.
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSwitchChangesOnlyFromTheSettingsWithTheProtectionsOfTheRows()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task Switch(string value, params (string, string)[] more)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + ExternalRules.Setting.Key, [("ritorno", "/impostazioni#notizie"), ("valore", value), .. more]);
return ServerHarness.Location(answer);
}
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Notizie, calendario e trimestrali");
StringAssert.Contains(page, "Le righe qui sotto valgono quando le regole sono attive.");
StringAssert.Contains(await server.TextAsync("/notizie"), "Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola.");
Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Active), "acting is always free");
Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.DoesNotContain("Archivio: le notizie", await server.TextAsync("/notizie"));
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'"));
StringAssert.Contains(await server.TextAsync("/impostazioni"), "per misurare soltanto le regole servono la frase e la password");
StringAssert.Contains(await Switch(ExternalRules.Measured), "errore=frase-rischio");
StringAssert.Contains(await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio");
Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", password)));
Assert.AreEqual(ExternalRules.Measured, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
var lines = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = @c ORDER BY occurred_at, id", r => r.Text("message"), ("c", ExternalRules.Changed)));
Assert.HasCount(2, lines);
StringAssert.Contains(lines[1], "da «attive» a «solo misurate»");
var csrf = await server.Http.GetFromJsonAsync>(new Uri("/api/antiforgery", UriKind.Relative));
using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + ExternalRules.Setting.Key, UriKind.Relative))
{ Content = JsonContent.Create(new { value = ExternalRules.Active }) };
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, put.StatusCode);
StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni");
}
}