Files
Anubis/src/Anubis/Demo/DemoMode.cs
T
Alby96andClaude Opus 5.5 959fe6ccba
ci / test (postgres) (pull_request) Successful in 9m38s
ci / test (sqlite) (pull_request) Successful in 5m26s
ci / image (pull_request) Successful in 2m23s
ci / test (postgres) (push) Successful in 9m28s
ci / test (sqlite) (push) Successful in 5m3s
ci / image (push) Successful in 1m56s
Show the news and the market, and set news and calendar from the settings (refs #60)
The news screen of SPEC 13 lists what the bot read in the last 24 hours and
what it did about each story, with the three filters of the mockup, the mood
of the market, the calendar with the effect of each event, the sources and
the spending of the day. Each note of the bot now keeps its action sentence
and the end of its restriction, so the screen shows the decision as it was.

Settings gain a news section: the rows of SPEC 10.5, the sources (enable and
trust), the key and daily cap of the language model, the Finnhub and FRED
keys and the central bank meetings. The demo seeds the F.9 data and matches
the mockup; the overview tile now shows the real news that matter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:43:09 +01:00

521 lines
33 KiB
C#
Raw 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 System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Demo;
/// <summary>
/// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured
/// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian
/// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads.
/// Rows of tables that later phases create (news, models) are loaded by those phases.
/// </summary>
public static class DemoMode
{
public const string AggregatesFile = "demo-aggregates.json";
/// <summary>The ECB rate of the demo's morning (F.2): one euro, 1,1601 dollars.</summary>
public const decimal UsdRate = 1.1601m;
/// <summary>"Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome.</summary>
public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2));
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
/// <summary>Demo folders older than this are removed when a new demo starts.</summary>
public static readonly TimeSpan KeepFolders = TimeSpan.FromDays(7);
/// <summary>
/// A brand-new folder under the system temporary directory; it never reuses another folder. <paramref name="wallClock"/>
/// is the real clock (the demo's own clock stands still): it names the folder and clears demos older than a week.
/// </summary>
public static DataDirectory CreateFolder(IClock wallClock)
{
ArgumentNullException.ThrowIfNull(wallClock);
var now = wallClock.UtcNow;
var parent = Path.Combine(Path.GetTempPath(), "anubis-demo");
RemoveOldFolders(parent, now);
var root = Path.Combine(parent, now.ToString("yyyyMMdd-HHmmss", _it) + "-" + Guid.NewGuid().ToString("N")[..8]);
if (Directory.Exists(root))
{
throw new IOException("Demo folder already exists: " + root);
}
var data = new DataDirectory(root);
data.Ensure();
return data;
}
// Only folders named the way CreateFolder names them, and only by the date in the name: nothing else is touched.
private static void RemoveOldFolders(string parent, DateTimeOffset now)
{
if (!Directory.Exists(parent))
{
return;
}
foreach (var folder in Directory.EnumerateDirectories(parent))
{
var name = Path.GetFileName(folder);
if (name.Length != 24 || name[15] != '-' ||
!DateTimeOffset.TryParseExact(name[..15], "yyyyMMdd-HHmmss", _it, DateTimeStyles.AssumeUniversal, out var created) ||
now - created < KeepFolders)
{
continue;
}
try
{
Directory.Delete(folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Still in use by another demo, or protected: left for next time.
}
}
}
public static StartupConfig Config(DataDirectory data) => new()
{
Platform = PlatformKind.Desktop,
Data = data,
Db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile },
TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"),
SecretKey = new ProtectedSecretKey(new RestrictedFileStore(Path.Combine(data.Root, "keys"))),
AllowLive = false,
};
/// <summary>Loads appendix F into an empty, migrated database and writes the aggregates file next to it.</summary>
public static async Task SeedAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(clock);
if (db.SqlitePath is null || !db.SqlitePath.StartsWith(Path.GetFullPath(data.Root), StringComparison.Ordinal))
{
throw new InvalidOperationException("Demo data go only into the demo's own SQLite database.");
}
File.WriteAllText(Path.Combine(data.Root, AggregatesFile), Resource("aggregates.json"));
var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
var now = clock.UtcNow;
var ids = new IdSource(now);
await db.WriteAsync(async s =>
{
var okx = ids.Next();
var alpaca = ids.Next();
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)",
cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false);
// F.2, F.3: capital in each account's currency, euro on OKX and dollars on Alpaca at the day's rate.
var strategies = new Dictionary<string, (string Name, Guid Account, decimal Capital, decimal Cash, decimal Share)>
{
["Trend crypto"] = ("crypto_trend", okx, 4000m, 1905.10m, 1m),
["Momentum"] = ("equity_momentum", alpaca, 5220.44m, 893.50m, 0.75m),
["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m),
};
var currencyOf = new Dictionary<Guid, string> { [okx] = "EUR", [alpaca] = "USD" };
// F.4: 58 days of 60 in simulation, after a passed backtest (an example: the real outcomes are in docs/backtests).
foreach (var (name, account, capital, _, share) in strategies.Values)
{
var example = new Trading.Qualification
{
Passed = true,
Verdict = "Superato (dato di esempio).",
Report = "docs/backtests/" + name + ".md",
MaxDrawdown = 0.18m,
ExpectedSlippageBp = 8m,
RoundTripCost = 0.0056m,
ExpectedPathP5 = [.. Enumerable.Range(1, 365).Select(d => Math.Round(-0.012 * Math.Sqrt(d), 4))],
};
await s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, stage_reason, qualification, capital, share, state, created_at, updated_at) " +
"VALUES (@id, @n, @a, 'simulation', @since, 'user', @q, @c, @sh, @st, @t, @t)",
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-58)),
("q", new DbJson(JsonSerializer.Serialize(example, Trading.Qualification.Json))), ("c", capital), ("sh", share),
("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now))
.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)))
.ConfigureAwait(false);
foreach (var (broker, eur, currency, rate, amount) in new[] { ("okx", 4000m, "EUR", 1m, 4000m), ("alpaca", 6000m, "USD", UsdRate, 6960.59m) })
{
await s.ExecuteAsync("INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, 'demo', @t)",
cancellationToken, ("id", ids.Next()), ("b", broker), ("e", eur), ("c", currency), ("r", rate), ("a", amount), ("t", started)).ConfigureAwait(false);
}
// F.4: the ten open positions.
var held = new List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)>();
foreach (var row in Csv("positions.csv").Skip(1))
{
var symbol = row[0];
var crypto = symbol.Contains('/', StringComparison.Ordinal);
var instrument = ids.Next();
var (strategy, account, _, _, _) = strategies[row[3]];
var opened = now.AddDays(-int.Parse(row[11], _it));
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"),
("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])),
("st", Number(row[10])), ("o", opened), ("t", now)).ConfigureAwait(false);
held.Add((symbol, instrument, account, strategy, Number(row[4]), Number(row[5]), Number(row[10]), opened));
}
// Each strategy's cash: the capital given at the start, less what its positions and past trades took.
foreach (var (name, account, capital, cash, _) in strategies.Values)
{
foreach (var (kind, amount, note) in new[] { ("capital", capital, "Capitale affidato"), ("buy", cash - capital, "Saldo di acquisti, vendite e commissioni") })
{
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, strategy, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, @s, @c, @m, @k, @n, @at, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("s", name), ("c", currencyOf[account]), ("m", amount), ("k", kind), ("n", note),
("at", kind == "capital" ? started : now), ("t", now)).ConfigureAwait(false);
}
}
await SeedTradesAsync(s, ids, strategies.Values.ToDictionary(v => v.Name, v => v.Account), currencyOf, held, now, cancellationToken).ConfigureAwait(false);
await SeedStopsAndChecksAsync(s, ids, alpaca, held, rome, now, cancellationToken).ConfigureAwait(false);
// F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results.
var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList();
var total = daily[^1].Equity - 10000m;
(string Scope, Guid? Account, string? Strategy, decimal Start, decimal Result)[] series =
[
("account", okx, null, 4000m, 231.60m),
("account", alpaca, null, 6000m, 180.86m),
("strategy", okx, "crypto_trend", 4000m, 231.60m),
("strategy", alpaca, "equity_momentum", 4500m, 169.50m),
("strategy", alpaca, "equity_meanrev", 1500m, 11.36m),
];
foreach (var (day, equity, benchmark, drawdown) in daily)
{
var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0))));
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, twr_index, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @x, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("x", Math.Round(equity / 10000m, 6)), ("t", now)).ConfigureAwait(false);
foreach (var (scope, account, strategy, start, result) in series)
{
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
// Without deposits along the way the index is the value over the start.
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, twr_index, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @x, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("x", Math.Round(value / start, 6)), ("t", now))
.ConfigureAwait(false);
}
}
// F.10: the diary, newest first in the appendix.
var today = DateOnly.FromDateTime(Now.DateTime);
foreach (var row in Csv("journal.csv").Skip(1))
{
var day = row[0] == "Oggi" ? today : today.AddDays(-1);
var local = day.ToDateTime(TimeOnly.ParseExact(row[1], "HH:mm", _it));
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, created_at) VALUES (@id, @at, @k, 'demo', @m, @t)",
cancellationToken, ("id", ids.Next()), ("at", new DateTimeOffset(local, rome.GetUtcOffset(local))), ("k", row[3]), ("m", row[2]), ("t", now)).ConfigureAwait(false);
}
await SeedNewsAsync(s, ids, rome, now, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, 'bot.state', @v, @t, @t)",
cancellationToken, ("id", ids.Next()), ("v", new DbJson(JsonSerializer.Serialize("active"))), ("t", now)).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
// F.5: the 41 closed trades. Their net results add up to the "guadagni già incassati" of F.2; the commissions of
// each account go on its first trade. Trades without a symbol in the appendix take one of the strategy's.
private static async Task SeedTradesAsync(DbSession s, IdSource ids, Dictionary<string, Guid> accountOf, Dictionary<Guid, string> currencyOf,
List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held,
DateTimeOffset now, CancellationToken cancellationToken)
{
var prices = held.ToDictionary(h => h.Symbol, h => h.Average);
var names = new Dictionary<string, string>();
foreach (var (symbol, name, price) in new[]
{
("TSLA", "Tesla", 250m), ("PG", "Procter & Gamble", 160m), ("LINK/EUR", "Chainlink", 15m), ("V", "Visa", 290m), ("ADA/EUR", "Cardano", 0.6m),
("AMD", "AMD", 160m), ("UNH", "UnitedHealth", 520m), ("KO", "Coca-Cola", 68m), ("MSFT", "Microsoft", 420m),
})
{
prices[symbol] = price;
names[symbol] = name;
}
var instruments = held.ToDictionary(h => h.Symbol, h => h.Instrument);
var fallback = new Dictionary<string, string[]>
{
["crypto_trend"] = ["BTC/EUR", "ETH/EUR", "SOL/EUR"],
["equity_momentum"] = ["AVGO", "NVDA", "LLY", "JPM", "XOM", "COST"],
["equity_meanrev"] = ["AAPL", "PG", "V", "KO", "MSFT"],
};
var fees = new Dictionary<Guid, decimal> { [accountOf["crypto_trend"]] = 14.49m, [accountOf["equity_momentum"]] = Math.Round(0.33m * UsdRate, 2) };
var rows = Csv("trades.csv").Skip(1).ToList();
// In dollars each trade is rounded to the cent; the last one of the account takes the rounding, so the total
// converts back to the euro of F.2 exactly.
var left = rows.GroupBy(r => accountOf[r[1]]).ToDictionary(g => g.Key, g => (Count: g.Count(), Total: Math.Round(g.Sum(r => Number(r[2])) * (currencyOf[g.Key] == "EUR" ? 1m : UsdRate), 2,
MidpointRounding.AwayFromZero)));
for (var i = 0; i < rows.Count; i++)
{
var (strategy, eur) = (rows[i][1], Number(rows[i][2]));
var symbol = rows[i].Length > 3 && rows[i][3].Length > 0 ? rows[i][3] : fallback[strategy][i % fallback[strategy].Length];
var account = accountOf[strategy];
if (!instruments.TryGetValue(symbol, out var instrument))
{
var crypto = symbol.Contains('/', StringComparison.Ordinal);
instrument = ids.Next();
instruments[symbol] = instrument;
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", names[symbol]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now))
.ConfigureAwait(false);
}
var currency = currencyOf[account];
var (count, total) = left[account];
var realized = count == 1 ? total : currency == "EUR" ? eur : Math.Round(eur * UsdRate, 2, MidpointRounding.AwayFromZero);
left[account] = (count - 1, total - realized);
var fee = fees.Remove(account, out var first) ? first : 0m;
var bought = 600m;
var quantity = Math.Round(bought / prices[symbol], 6);
var closed = now.AddDays(-(rows.Count - i)).AddHours(-3);
await s.ExecuteAsync(
"INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, exit_reason, created_at, updated_at) " +
"VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought),
("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false);
await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken)
.ConfigureAwait(false);
}
}
// F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on
// the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss.
private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought,
decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken)
{
var (entry, exit) = strategy switch
{
"crypto_trend" => ("trend_entry", "trend_exit"),
"equity_momentum" => ("momentum_entry", "momentum_exit_rank"),
_ => ("meanrev_entry", "meanrev_exit_average"),
};
async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) =>
await s.ExecuteAsync(
"INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, NULL, @t)",
cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome),
("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false);
async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) =>
await s.ExecuteAsync(
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, @s, @side, @p, @q, @q, @k, 1, 0, @r, @st, @at, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("side", side), ("p", purpose), ("q", quantity),
("k", Trading.ClientOrderIds.Key(decision)), ("r", Math.Round(reference, 6)), ("st", Trading.ExecutionStates.Done), ("at", at), ("t", now)).ConfigureAwait(false);
var buy = ids.Next();
await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false);
await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false);
if (stopped)
{
await ExecuteAsync("sell", "protective", ids.Next(), sold / quantity * 1.0003m, closed).ConfigureAwait(false);
}
else
{
var sale = ids.Next();
await DecideAsync(sale, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [exit], closed.AddMinutes(-1)).ConfigureAwait(false);
await ExecuteAsync("sell", "exit", sale, sold / quantity * 1.0001m, closed).ConfigureAwait(false);
}
}
// F.7: the protective stops. On OKX one stop for each coin; on Alpaca a permanent stop on the whole shares, while
// the day stops on the fractions wait for the opening (the market is closed at 08:21). Both accounts were checked
// at 08:20 and agree with the ledger; the keys may trade but not withdraw.
private static async Task SeedStopsAndChecksAsync(DbSession s, IdSource ids, Guid alpaca,
List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held,
TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken)
{
DateTimeOffset Local(int daysAgo, int hour, int minute)
{
var local = DateOnly.FromDateTime(Now.DateTime).AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute));
return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime();
}
var okxSince = new Dictionary<string, (DateTimeOffset Created, DateTimeOffset Updated)>
{
["BTC/EUR"] = (Local(4, 2, 6), Local(0, 2, 6)),
["ETH/EUR"] = (Local(2, 9, 14), Local(2, 9, 14)),
["SOL/EUR"] = (Local(6, 11, 40), Local(6, 11, 40)),
};
var n = 0;
foreach (var h in held)
{
var whole = decimal.Truncate(h.Quantity);
var onAlpaca = h.Account == alpaca;
if (onAlpaca && whole == 0m)
{
continue;
}
var (created, updated) = onAlpaca ? (h.Opened, h.Opened) : okxSince[h.Symbol];
await s.ExecuteAsync(
"INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, broker_order_id, side, order_type, quantity, stop_price, status, purpose, time_in_force, " +
"filled_quantity, submitted_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @c, @b, 'sell', 'stop', @q, @st, 'submitted', 'stop', 'gtc', 0, @cr, @cr, @up)",
cancellationToken, ("id", ids.Next()), ("a", h.Account), ("i", h.Instrument), ("s", h.Strategy), ("c", $"ANU-DEMO-STOP-{++n:00}"), ("b", $"demo-{n:00}"),
("q", onAlpaca ? whole : h.Quantity), ("st", h.Stop), ("cr", created), ("up", updated)).ConfigureAwait(false);
}
var checkedAt = Local(0, 8, 20);
foreach (var account in held.Select(h => h.Account).Distinct())
{
await s.ExecuteAsync(
"INSERT INTO account_status (id, account_id, mode, last_reconciled_at, last_outcome, key_can_trade, key_can_withdraw, key_checked_at, created_at, updated_at) " +
"VALUES (@id, @a, 'normal', @at, 'clean', @yes, @no, @at, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("at", checkedAt), ("yes", true), ("no", false), ("t", now)).ConfigureAwait(false);
}
}
// F.9: the six stories shown with the filter "sulle tue posizioni", what the bot did about each, the mood of the
// market and the four events of the calendar. The counts (312, 9, 2), the sources and the spending are aggregates.
private static async Task SeedNewsAsync(DbSession s, IdSource ids, TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken)
{
var today = DateOnly.FromDateTime(Now.DateTime);
DateTimeOffset At(int daysAgo, int hour, int minute)
{
var local = today.AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute));
return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime();
}
var sources = new Dictionary<string, (Guid Id, bool Trusted)>(StringComparer.Ordinal);
foreach (var (name, url, trusted) in new[]
{
("Alpaca News", "https://data.alpaca.markets/v1beta1/news", true),
("CoinDesk", "https://www.coindesk.com/arc/outboundfeeds/rss/", true),
("MarketWatch", "https://feeds.content.dowjones.io/public/rss/mw_topstories", true),
("The Block", "https://www.theblock.co/rss.xml", false),
})
{
var id = ids.Next();
sources[name] = (id, trusted);
await s.ExecuteAsync(
"INSERT INTO news_sources (id, url, name, kind, trusted, enabled, failures, last_checked_at, last_ok_at, created_at, updated_at) " +
"VALUES (@id, @u, @n, 'rss', @tr, @on, 0, @t, @t, @t, @t)",
cancellationToken, ("id", id), ("u", url), ("n", name), ("tr", trusted), ("on", true), ("t", now)).ConfigureAwait(false);
}
var jpmUntil = new DateTimeOffset(2026, 10, 13, 20, 0, 0, TimeSpan.Zero);
var stories = new (DateTimeOffset At, string Source, string Scope, string Target, string Title, double Score, int Importance, string Kind, string Action, DateTimeOffset? Until)[]
{
(At(0, 6, 10), "CoinDesk", "instrument", "okx:SOL/EUR", "Rinviato di una settimana l'aggiornamento della rete Solana", -0.7, 3,
"news_negative", "Per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.", At(0, 6, 10).AddHours(24)),
(At(1, 22, 41), "Alpaca News", "instrument", "alpaca:JPM", "JPMorgan pubblica i conti martedì prima dell'apertura", 0.0, 3,
"calendar_earnings", "Niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.", jpmUntil),
(At(0, 7, 52), "MarketWatch", "market", "us", "I verbali della banca centrale USA non cambiano le attese sui tassi", 0.05, 2,
"news_noted", "Niente. Confermano quello che il mercato sapeva già.", null),
(At(1, 19, 5), "Alpaca News", "instrument", "alpaca:NVDA", "Un analista alza il prezzo obiettivo di Nvidia", 0.4, 2,
"news_noted", "Niente. I giudizi degli analisti non entrano nelle decisioni.", null),
(At(1, 16, 20), "The Block", "class", "crypto", "Un exchange segnala prelievi rallentati per manutenzione", -0.7, 3,
"news_rechecked", "Niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", null),
(At(1, 14, 31), "Alpaca News", "market", "us", "Richieste di sussidi di disoccupazione USA sotto le attese", 0.35, 3,
"news_noted", "Niente. Dato di impatto medio: nessun blocco degli ingressi.", null),
};
foreach (var n in stories)
{
var story = ids.Next();
var (source, trusted) = sources[n.Source];
await s.ExecuteAsync(
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " +
"VALUES (@id, @ti, @k, @at, @at, @at, 1, @tr, @sc, @im, @t, @t)",
cancellationToken, ("id", story), ("ti", n.Title), ("k", n.Title.ToLowerInvariant()), ("at", n.At), ("tr", trusted), ("sc", n.Score), ("im", n.Importance),
("t", now)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, language, published_at, score, importance, created_at) " +
"VALUES (@id, @st, @so, @u, @u, @p, @ti, 'it', @at, @sc, @im, @t)",
cancellationToken, ("id", ids.Next()), ("st", story), ("so", source), ("u", "https://esempio.invalid/notizie/" + story.ToString("N")), ("p", n.Source),
("ti", n.Title), ("at", n.At), ("sc", n.Score), ("im", n.Importance), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, @sc, @tg, 'source', @t)",
cancellationToken, ("id", ids.Next()), ("st", story), ("sc", n.Scope), ("tg", n.Target), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO news_notes (id, subject, target, kind, action, until, created_at) VALUES (@id, @su, @tg, @k, @a, @u, @t)",
cancellationToken, ("id", ids.Next()), ("su", "story:" + story), ("tg", n.Target), ("k", n.Kind), ("a", n.Action), ("u", n.Until), ("t", n.At)).ConfigureAwait(false);
}
foreach (var (indicator, asOf, value, label, source) in new[]
{
("fear_greed", At(0, 2, 0), 41.0, "paura", "alternative.me"),
("vix", At(1, 22, 15), 17.8, "calmo", "cboe"),
("btc_funding", At(0, 8, 0), 0.00006, "nella norma", "okx_derivatives"),
})
{
await s.ExecuteAsync("INSERT INTO market_mood (id, indicator, as_of, value, label, source, created_at) VALUES (@id, @i, @a, @v, @l, @s, @t)",
cancellationToken, ("id", ids.Next()), ("i", indicator), ("a", asOf), ("v", value), ("l", label), ("s", source), ("t", now)).ConfigureAwait(false);
}
foreach (var (kind, title, at, known, symbol, hint, impact, key) in new (string, string, DateTimeOffset, bool, string?, string?, string?, string)[]
{
("economic", "Fiducia dei consumatori USA", At(0, 16, 0), true, null, null, "Medium", "demo:confidence"),
("earnings", "Conti trimestrali di JPMorgan", new DateTimeOffset(2026, 10, 13, 4, 0, 0, TimeSpan.Zero), false, "JPM", "bmo", null, "demo:jpm"),
("economic", "Inflazione USA", At(-5, 14, 30), true, null, null, "High", "demo:cpi"),
("central_bank", "Decisione sui tassi della banca centrale USA", At(-19, 19, 0), true, null, null, "High", "demo:fomc"),
})
{
await s.ExecuteAsync(
"INSERT INTO calendar_events (id, kind, title, currency, symbol, occurs_at, time_known, time_hint, impact, source, source_key, created_at, updated_at) " +
"VALUES (@id, @k, @ti, 'USD', @sy, @at, @kn, @h, @im, 'demo', @key, @t, @t)",
cancellationToken, ("id", ids.Next()), ("k", kind), ("ti", title), ("sy", symbol), ("at", at), ("kn", known), ("h", hint), ("im", impact),
("key", key), ("t", now)).ConfigureAwait(false);
}
}
/// <summary>Reads the aggregates file of a demo folder.</summary>
public static JsonDocument? ReadAggregates(DataDirectory data)
{
ArgumentNullException.ThrowIfNull(data);
var path = Path.Combine(data.Root, AggregatesFile);
return File.Exists(path) ? JsonDocument.Parse(File.ReadAllText(path)) : null;
}
// "68.950,00 €", "+3,58", "66.180 €", "0,0182" → decimal.
private static decimal Number(string text)
{
var clean = new StringBuilder();
foreach (var c in text)
{
if (char.IsAsciiDigit(c) || c == ',')
{
clean.Append(c == ',' ? '.' : c);
}
else if (c is '-' or '−')
{
clean.Append('-');
}
}
return decimal.Parse(clean.ToString(), NumberStyles.Number, _it);
}
private static IEnumerable<string[]> Csv(string name) =>
Resource(name).Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r').Split(';'));
private static string Resource(string name)
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Anubis.Demo.Data." + name)
?? throw new InvalidOperationException("Missing demo resource " + name);
using var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
/// <summary>UUIDv7 in insertion order, all at the demo's frozen time.</summary>
private sealed class IdSource(DateTimeOffset at)
{
private int _n;
public Guid Next() => Guid.CreateVersion7(at.AddMilliseconds(_n++));
}
}