Files
Alby96andClaude Opus 5.5 b087dd215b
ci / test (postgres) (push) Successful in 8m20s
ci / test (sqlite) (push) Successful in 4m25s
ci / test (postgres) (pull_request) Successful in 8m13s
ci / test (sqlite) (pull_request) Successful in 4m38s
ci / image (push) Successful in 2m5s
ci / image (pull_request) Successful in 2m6s
Apply the SPEC 10.5 news and calendar rules to new entries (refs #59)
Confirmed serious events hold new purchases of an instrument for 72 hours
and keep its stop where it is; confirmed negative news holds them for 24
hours; an unconfirmed rumour only gets a diary note and a check two hours
later. Coming earnings keep mean reversion out and macro figures hold
entries around their release, now in the live engine too. The strictest
row wins, every row can be switched off in the settings, and windows count
from the fact, so after an absence only effects still in force apply.

A held purchase moves to the end of its restriction while the order is
still valid and keeps its first due time, so the price drift check of
SPEC 5.6 still compares with the decision. Each restriction is written to
the diary once, with its motive. The per-instrument state keeps the tone
over one and three days, the story count against its norm and the active
restriction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:39:26 +01:00

336 lines
23 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.News;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The rules of SPEC 10.5 and the state of 10.2 point 6 (issue #59): which news restrict what and for how long, the
/// strictest of them, the switches, the diary lines, and the purchases the live engine holds back.
/// </summary>
[TestClass]
public sealed class NewsRulesTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
private static int _ids;
private static StoryFact Story(double hoursAgo, int importance, double? score = null, bool trusted = true, int sources = 1, double? seenHoursAgo = null) =>
new(new Guid(Interlocked.Increment(ref _ids), 0, 0, new byte[8]), "Titolo", "CoinDesk", Now.AddHours(-hoursAgo), Now.AddHours(-(seenHoursAgo ?? hoursAgo)), sources,
trusted, score, importance >= 4 ? SevereKinds.Cyberattack : null, importance);
[TestMethod]
public void OnlyConfirmedNegativeNewsRestrictAndOnlyForTheirWindow()
{
NewsRestriction? One(StoryFact story, NewsRuleSwitches? switches = null) => NewsRules.Active([story], Now, switches ?? NewsRuleSwitches.AllOn).SingleOrDefault();
var severe = One(Story(71, 4))!;
Assert.AreEqual(NewsReasons.Severe, severe.Code);
Assert.AreEqual(Now.AddHours(1), severe.Until, "72 hours from the fact, not from when the bot read it.");
Assert.IsNull(One(Story(73, 4)), "An effect already over is not applied (SPEC 5.6).");
var negative = One(Story(23, 3, -0.8))!;
Assert.AreEqual(NewsReasons.Negative, negative.Code);
Assert.AreEqual(Now.AddHours(1), negative.Until);
Assert.IsNull(One(Story(25, 3, -0.8)));
Assert.IsNull(One(Story(1, 2, -0.4)), "Slightly negative news create no restriction.");
Assert.IsNull(One(Story(1, 3, 0.5)), "An importance of 3 that is not negative restricts nothing.");
// One untrusted source: nothing happens until a second independent source confirms (third row).
var rumour = Story(1, 4, trusted: false);
Assert.IsNull(One(rumour));
Assert.IsTrue(NewsRules.Unconfirmed(rumour));
Assert.AreEqual(NewsReasons.Severe, One(rumour with { Sources = 2 })!.Code);
Assert.IsFalse(NewsRules.Unconfirmed(rumour with { Sources = 2 }));
Assert.IsFalse(NewsRules.Unconfirmed(Story(1, 2, -0.4, trusted: false)), "Only what would restrict is a rumour to check.");
Assert.IsNull(One(Story(1, 4, seenHoursAgo: -1)), "A story the bot has not read yet at that moment does nothing.");
var dated = One(Story(-5, 4, seenHoursAgo: 2))!;
Assert.AreEqual(Now.AddHours(70), dated.Until, "A feed dated in the future counts from when the bot read it.");
Assert.IsNull(One(Story(1, 4), new NewsRuleSwitches(Severe: false)), "Each row can be switched off.");
Assert.IsNull(One(Story(1, 3, -0.9), new NewsRuleSwitches(Negative: false)));
}
[TestMethod]
public void TheStrictestRestrictionWinsAndOnlyASeriousEventKeepsTheStop()
{
var severeEnding = Story(71, 4);
var negativeLonger = Story(4, 3, -0.7);
var active = NewsRules.Active([severeEnding, negativeLonger], Now, NewsRuleSwitches.AllOn);
Assert.HasCount(2, active);
var strictest = NewsRules.Strictest(active)!;
Assert.AreEqual(NewsReasons.Negative, strictest.Code, "The one that holds the purchases longer.");
Assert.AreEqual(Now.AddHours(20), strictest.Until);
Assert.AreEqual(severeEnding.Id, NewsRules.KeepsStop(active)!.Story.Id, "The stop stays while the serious event lasts.");
var tie = NewsRules.Active([Story(48, 4), Story(0, 3, -0.7)], Now, NewsRuleSwitches.AllOn);
Assert.AreEqual(NewsReasons.Severe, NewsRules.Strictest(tie)!.Code, "Ending together, the serious event is the stricter one.");
Assert.IsNull(NewsRules.KeepsStop(NewsRules.Active([negativeLonger], Now, NewsRuleSwitches.AllOn)));
Assert.IsNull(NewsRules.Strictest([]));
}
[TestMethod]
public void TheStateWeighsTheToneByAgeAndComparesTheCountWithTheNorm()
{
// With a half-life of 12 hours a story 13 hours old weighs half of one an hour old: (−0.8 + 0.4 / 2) / 1.5.
List<StoryFact> stories = [Story(1, 3, -0.8), Story(2, 1), Story(13, 1, 0.4), Story(40, 1, 0.6)];
for (var day = 3; day <= 10; day++)
{
stories.Add(Story((24 * day) - 12, 1));
}
var state = NewsRules.State(stories, Now, NewsRuleSwitches.AllOn, Now.AddDays(-10));
Assert.AreEqual(-0.4, state.Tone1Day!.Value, 1e-9);
Assert.IsTrue(state.Tone3Days > state.Tone1Day && state.Tone3Days < 0.6, $"{state.Tone3Days}");
Assert.AreEqual(3, state.Stories1Day, "A story without a score is counted, not in the tone.");
Assert.AreEqual(1.0, state.NormalPerDay!.Value, 1e-9, "Nine stories in the nine days before the last one.");
Assert.AreEqual(3.0, state.Busy!.Value, 1e-9);
Assert.AreEqual(NewsReasons.Negative, state.Active!.Code, "The most serious event in force.");
var young = NewsRules.State(stories, Now, NewsRuleSwitches.AllOn, Now.AddHours(-30));
Assert.IsNull(young.NormalPerDay, "No norm before two days of news.");
Assert.IsNull(young.Busy);
var quiet = NewsRules.State([Story(2, 1)], Now, NewsRuleSwitches.AllOn, null);
Assert.IsNull(quiet.Tone1Day, "No scored story, no tone.");
Assert.IsNull(quiet.Active);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheGateHoldsPurchasesForNewsAndFiguresAndEveryRowCanBeSwitchedOff()
{
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var clock = new ManualClock(Now);
var eth = MarketDataStoreTests.Okx("ETH-EUR");
var sol = MarketDataStoreTests.Okx("SOL-EUR");
var btc = MarketDataStoreTests.Okx("BTC-EUR");
await StoryAsync(test.Db, clock, eth, "Exchange hacked, ETH drained", Now.AddHours(-10), 4, -0.9, "CoinDesk", trusted: true).ConfigureAwait(false);
await StoryAsync(test.Db, clock, sol, "Solana validator exploited", Now.AddHours(-1), 4, -0.9, "The Block", trusted: false).ConfigureAwait(false);
await new CalendarEventStore(test.Db, clock).UpsertAsync(
[new CalendarEvent(CalendarEventKinds.Economic, "Inflazione USA", Now.AddMinutes(20), true, "test", "cpi") { Currency = "USD", Impact = "High" }], _none)
.ConfigureAwait(false);
var settings = new SettingsStore(test.Db, clock, new EventBus());
var gate = new EntryGate(test.Db, clock, settings);
var news = (await gate.HoldAsync(eth, Now, _none).ConfigureAwait(false))!;
Assert.AreEqual(NewsReasons.Severe, news.Code);
Assert.AreEqual(Now.AddHours(62), news.Until, "The news outlasts the figure: the strictest wins.");
Assert.AreEqual("«Exchange hacked, ETH drained» (CoinDesk)", news.Motive);
Assert.AreEqual(NewsReasons.KeepStop, (await gate.KeepStopAsync(eth, Now, _none).ConfigureAwait(false))!.Code);
var figure = (await gate.HoldAsync(sol, Now, _none).ConfigureAwait(false))!;
Assert.AreEqual(CorrectiveReasons.CalendarEvent, figure.Code, "The rumour on SOL does nothing; the figure still holds every purchase.");
Assert.AreEqual(Now.AddMinutes(50), figure.Until);
Assert.AreEqual("Inflazione USA", figure.Motive);
Assert.IsNull(await gate.KeepStopAsync(sol, Now, _none).ConfigureAwait(false));
Assert.IsNull(await gate.HoldAsync(btc, Now.AddMinutes(50), _none).ConfigureAwait(false), "At the end of the window the purchase goes.");
Assert.IsNull(await gate.HoldAsync(btc, Now.AddMinutes(-31), _none).ConfigureAwait(false));
var state = await new NewsDesk(test.Db, clock, settings).StateAsync(NewsDesk.Target(eth), _none).ConfigureAwait(false);
Assert.AreEqual(1, state.Stories1Day);
Assert.AreEqual(-0.9, state.Tone1Day!.Value, 1e-9);
Assert.AreEqual(NewsReasons.Severe, state.Active!.Code);
await settings.SetAsync(NewsRuleSettings.Severe.Key, NewsRuleSettings.Off, "test", _none).ConfigureAwait(false);
Assert.AreEqual(CorrectiveReasons.CalendarEvent, (await gate.HoldAsync(eth, Now, _none).ConfigureAwait(false))!.Code);
Assert.IsNull(await gate.KeepStopAsync(eth, Now, _none).ConfigureAwait(false));
await settings.SetAsync(NewsRuleSettings.Macro.Key, NewsRuleSettings.Off, "test", _none).ConfigureAwait(false);
Assert.IsNull(await gate.HoldAsync(eth, Now, _none).ConfigureAwait(false), "With both rows off nothing holds the purchase.");
Assert.IsFalse((await NewsRuleSettings.LoadAsync(settings, _none).ConfigureAwait(false)).Severe);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDiarySaysEachRestrictionOnceAndChecksARumourTwoHoursLater()
{
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var clock = new ManualClock(Now);
var eth = MarketDataStoreTests.Okx("ETH-EUR");
var sol = MarketDataStoreTests.Okx("SOL-EUR");
var ada = MarketDataStoreTests.Okx("ADA-EUR");
var jpm = new InstrumentSpec(Venues.Alpaca, "JPM", "JPMorgan Chase & Co. Common Stock", AssetClasses.Equity, "USD");
var catalog = new InstrumentCatalog(test.Db, clock);
await catalog.SyncAsync(Venues.Okx, [eth, sol, ada], complete: false, _none).ConfigureAwait(false);
await catalog.SyncAsync(Venues.Alpaca, [jpm], complete: false, _none).ConfigureAwait(false);
foreach (var (universe, spec) in new[] { (Universes.Crypto, eth), (Universes.Crypto, sol), (Universes.Equity, jpm) })
{
var id = (await catalog.ListAsync(spec.Venue, _none).ConfigureAwait(false)).Single(i => i.Symbol == spec.Symbol).Id;
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO universe_members (id, universe, as_of, instrument_id, rank, created_at) VALUES (@id, @u, '2026-11-16', @i, 1, @now)",
_none, ("id", Ids.NewId(clock)), ("u", universe), ("i", id), ("now", Now)), _none).ConfigureAwait(false);
}
await StoryAsync(test.Db, clock, eth, "Exchange hacked, ETH drained", Now.AddHours(-3), 4, -0.9, "CoinDesk", trusted: true).ConfigureAwait(false);
await StoryAsync(test.Db, clock, sol, "Solana validator exploited", Now.AddMinutes(-30), 4, -0.9, "The Block", trusted: false).ConfigureAwait(false);
await StoryAsync(test.Db, clock, ada, "Cardano exchange halts withdrawals", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true).ConfigureAwait(false);
await new CalendarEventStore(test.Db, clock).UpsertAsync(
[new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale JPM", new DateTimeOffset(2026, 11, 18, 11, 0, 0, TimeSpan.Zero), false, "test", "earnings:JPM") { Symbol = "JPM", TimeHint = "bmo" }],
_none).ConfigureAwait(false);
var watcher = new NewsWatcher(test.Db, clock);
Assert.AreEqual(3, await watcher.RunOnceAsync(_none).ConfigureAwait(false));
var diary = await DiaryAsync(test.Db).ConfigureAwait(false);
CollectionAssert.AreEquivalent(new[]
{
"Ho messo una restrizione per 72 ore: niente nuovi acquisti di ETH/EUR. Motivo: «Exchange hacked, ETH drained» (CoinDesk).",
"Voce non confermata su SOL/EUR: «Solana validator exploited» (The Block). Nessuna azione: ricontrollo tra 2 ore.",
"Ho messo una restrizione fino a mercoledì 18 novembre: niente mean reversion su JPM. Motivo: JPM pubblica i conti mercoledì 18 novembre prima dell'apertura.",
}, diary, "ADA is neither held nor a candidate: its restriction holds its purchases without a line in the diary.");
var queued = await test.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM notifications", r => r.Text("message")), _none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { diary.Single(d => d.Contains("ETH/EUR", StringComparison.Ordinal)) }, queued, "Only the serious event goes to Telegram.");
Assert.AreEqual(0, await watcher.RunOnceAsync(_none).ConfigureAwait(false), "Each line is written once.");
clock.Set(Now.AddHours(2));
Assert.AreEqual(1, await watcher.RunOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual("Ricontrollata la voce su SOL/EUR: nessun'altra fonte la conferma, nessuna azione.", (await DiaryAsync(test.Db).ConfigureAwait(false))[^1]);
// A position held: the diary says the stop stays where it is.
var account = Ids.NewId(clock);
var ethId = (await catalog.ListAsync(Venues.Okx, _none).ConfigureAwait(false)).Single(i => i.Symbol == "ETH-EUR").Id;
await test.Db.WriteAsync(async s =>
{
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'okx', 'okx', 'demo', 'EUR', @now)", _none,
("id", account), ("now", Now)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, opened_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, 'crypto_trend', @q, @p, @now, @now, @now)", _none, ("id", Ids.NewId(clock)), ("a", account), ("i", ethId), ("q", DbValues.Money(0.5m)),
("p", DbValues.Money(2000m)), ("now", Now)).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
await StoryAsync(test.Db, clock, eth, "Ethereum foundation under investigation", Now.AddHours(1), 4, -0.9, "CNBC", trusted: true).ConfigureAwait(false);
Assert.AreEqual(1, await watcher.RunOnceAsync(_none).ConfigureAwait(false));
Assert.AreEqual("Ho messo una restrizione per 72 ore: niente nuovi acquisti di ETH/EUR. Lo stop resta dov'è. Motivo: «Ethereum foundation under investigation» (CNBC).",
(await DiaryAsync(test.Db).ConfigureAwait(false))[^1]);
}
/// <summary>
/// The crypto close of the first live day buys ETH and SOL (AbsenceTests). A serious event on ETH and a negative
/// story on SOL, both confirmed, hold the purchases past 12:00 UTC: they are left out, the decision keeps what the
/// strategy proposed, and the diary says which rule and which story.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ARestrictionLeavesOutThePurchaseAndTheDiarySaysWhy()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)).ConfigureAwait(false);
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
await 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).ConfigureAwait(false);
await 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).ConfigureAwait(false);
await live.DayAsync(day).ConfigureAwait(false);
var fills = await live.LiveFillsAsync().ConfigureAwait(false);
Assert.IsFalse(fills.Any(f => f.Symbol is "ETH-EUR" or "SOL-EUR"), string.Join(", ", fills));
var diary = await DiaryAsync(live.Rig.Db).ConfigureAwait(false);
Assert.Contains("Non compro ETH/EUR. " + ReasonCatalog.Text(NewsReasons.Severe) + " Motivo: «Ethereum exchange hacked» (CoinDesk).", diary);
Assert.Contains("Non compro SOL/EUR. " + ReasonCatalog.Text(NewsReasons.Negative) + " Motivo: «Solana upgrade delayed by a week» (CoinDesk).", diary);
var rows = await live.Rig.QueryAsync("SELECT symbol, stage, outcome, reasons FROM decisions WHERE stage IN (@c, @st)",
r => (Symbol: r.TextOrNull("symbol"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons")), ("c", DecisionStages.Correctives),
("st", DecisionStages.Strategy)).ConfigureAwait(false);
Assert.IsTrue(rows.Any(r => r is { Symbol: "ETH-EUR", Stage: DecisionStages.Strategy }), "The proposal stays: it is an example of 11.2.");
Assert.IsTrue(rows.Any(r => r is { Symbol: "ETH-EUR", Stage: DecisionStages.Correctives, Outcome: DecisionOutcomes.Refused } && r.Reasons.Contains(NewsReasons.Severe,
StringComparison.Ordinal)));
Assert.IsTrue(rows.Any(r => r is { Symbol: "SOL-EUR", Stage: DecisionStages.Correctives, Outcome: DecisionOutcomes.Refused } && r.Reasons.Contains(NewsReasons.Negative,
StringComparison.Ordinal)));
Assert.IsEmpty(await live.Rig.QueryAsync("SELECT id FROM planned_orders WHERE side = 'buy'", r => r.Id("id")).ConfigureAwait(false), "Nothing left to send.");
}
/// <summary>
/// A high-impact US figure at 00:10 UTC blocks entries from 23:40 to 00:40: the purchases decided at 00:05 wait
/// and go at 00:40, still within the crypto deadline, with the price check of a recovered entry.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AFigureDelaysThePurchasesToTheEndOfItsWindow()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)).ConfigureAwait(false);
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
await new CalendarEventStore(live.Rig.Db, live.Rig.Clock).UpsertAsync(
[new CalendarEvent(CalendarEventKinds.Economic, "Inflazione USA", new DateTimeOffset(2026, 9, 1, 0, 10, 0, TimeSpan.Zero), true, "test", "cpi") { Currency = "USD", Impact = "High" }],
_none).ConfigureAwait(false);
var bought = new List<string>();
await live.DayAsync(day, async minute =>
{
if (minute == 30)
{
bought.AddRange((await live.LiveFillsAsync().ConfigureAwait(false)).Where(f => f.Side == OrderSide.Buy).Select(f => f.Symbol));
}
}, morning: 60).ConfigureAwait(false);
Assert.IsEmpty(bought, "Nothing goes inside the window.");
var fills = await live.LiveFillsAsync().ConfigureAwait(false);
Assert.IsTrue(fills.Any(f => f is { Symbol: "ETH-EUR", Side: OrderSide.Buy }), string.Join(", ", fills));
var diary = await DiaryAsync(live.Rig.Db).ConfigureAwait(false);
Assert.Contains("Ho rimandato l'acquisto di ETH/EUR alle 02:40. " + ReasonCatalog.Text(CorrectiveReasons.CalendarEvent) + " Motivo: Inflazione USA.", diary);
Assert.IsFalse(diary.Any(d => d.StartsWith("Recuperato un lavoro saltato: l'acquisto", StringComparison.Ordinal)), "A purchase put off is not a missed job.");
var first = await live.Rig.QueryAsync("SELECT first_due_at FROM planned_orders WHERE side = 'buy'", r => r.MomentOrNull("first_due_at")).ConfigureAwait(false);
Assert.IsTrue(first.Count > 0 && first.All(f => f == new DateTimeOffset(2026, 9, 1, 0, 5, 0, TimeSpan.Zero)), "The time it was first due is kept for the price check.");
}
/// <summary>
/// The close of 1 September plans a mean reversion purchase of BBB (AbsenceTests). With its earnings on 3 September,
/// before the open, the strategy stays out; with the fourth row of 10.5 switched off it buys as before.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ComingEarningsKeepMeanReversionOutUnlessTheRowIsOff()
{
var day = new DateOnly(2026, 9, 1);
foreach (var on in new[] { true, false })
{
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41)).ConfigureAwait(false);
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).ConfigureAwait(false);
var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock);
stocks.UseEarnings(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct).ConfigureAwait(false), on));
await stocks.SessionAsync(day).ConfigureAwait(false);
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' AND p.status = @s", r => r.Text("symbol"),
("s", PlannedStates.Pending)).ConfigureAwait(false);
if (on)
{
Assert.IsEmpty(planned, "Earnings within three sessions of the entry: no mean reversion.");
}
else
{
CollectionAssert.AreEqual(new[] { "BBB" }, planned.ToList(), "With the row off the purchase is planned as before.");
}
}
}
/// <summary>A story linked to one instrument, with one article from the named publisher.</summary>
internal static async Task<Guid> StoryAsync(Database db, IClock clock, InstrumentSpec spec, string title, DateTimeOffset published, int importance, double? score,
string publisher, bool trusted, int sources = 1, DateTimeOffset? seen = null)
{
var store = new NewsStore(db, clock);
await store.EnsureDefaultsAsync(_none).ConfigureAwait(false);
var source = (await store.ListSourcesAsync(_none).ConfigureAwait(false))[0];
var id = Ids.NewId(clock);
var at = seen ?? clock.UtcNow;
var severe = importance >= 4 ? SevereKinds.Cyberattack : null;
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, severe, importance, created_at, updated_at) " +
"VALUES (@id, @t, @k, @p, @seen, @seen, @n, @tr, @sc, @sv, @imp, @seen, @seen)", _none, ("id", id), ("t", title), ("k", title.ToLowerInvariant()), ("p", published),
("seen", at), ("n", sources), ("tr", trusted), ("sc", score), ("sv", severe), ("imp", importance)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, score, severe, importance, created_at) " +
"VALUES (@id, @st, @src, @u, @u, @pub, @t, NULL, 'en', @p, @sc, @sv, @imp, @seen)", _none, ("id", Ids.NewId(clock)), ("st", id), ("src", source.Id),
("u", "https://example.test/" + id), ("pub", publisher), ("t", title), ("p", published), ("sc", score), ("sv", severe), ("imp", importance), ("seen", at)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, @sc, @t, @v, @seen)", _none, ("id", Ids.NewId(clock)),
("st", id), ("sc", LinkScopes.Instrument), ("t", NewsDesk.Target(spec)), ("v", LinkVia.Name), ("seen", at)).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
return id;
}
internal static async Task<List<string>> DiaryAsync(Database db) =>
await db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal ORDER BY occurred_at, created_at, id", r => r.Text("message")), _none).ConfigureAwait(false);
}