From 41e067e7d17d0e43b0375f03d694cbacb733e6ac Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 18:28:08 +0100 Subject: [PATCH] Run the strategies live in simulation with the live engine (refs #47) The live engine makes each decision at its time of SPEC 5.5 through the same DecideOnce call the backtest uses, so live and backtest cannot drift: the crypto close at 00:05 UTC, the stock signals 20 minutes after the close, the meanrev exits 5 minutes before it, the stock orders and the daily stops at the open. Each decision has a run key written in the same transaction as its decision rows, planned orders and diary lines, and each planned order's id gives the order key, so a restart never decides or sends anything twice. Entries recovered late are dropped when the price has moved too far. The engine runs from the scheduler once the accounts are reconciled. The IEX stream follows held stocks, planned orders and SPY during the session, and the stock simulator's day orders now expire at the close. Tests: parity with the backtest for crypto_trend (40 days) and equity_meanrev (6 weeks), and a 14-day run with the network down, a lost answer, a restart mid-order and the database unreachable, ending reconciled with no duplicate orders, on SQLite and PostgreSQL. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/Engine.cs | 10 +- src/Anubis/Core/Scheduling.cs | 10 +- src/Anubis/Data/MarketDataService.cs | 87 +- src/Anubis/Db/Database.cs | 27 + src/Anubis/Db/Migrations/0006_live.sql | 65 ++ src/Anubis/Trading/Capital.cs | 3 + src/Anubis/Trading/DiaryText.cs | 3 + src/Anubis/Trading/LiveEngine.cs | 1171 ++++++++++++++++++++++++ src/Anubis/Trading/ReasonCatalog.cs | 9 + src/Anubis/Trading/TradingService.cs | 33 + tests/Anubis.Tests/LiveEngineTests.cs | 156 ++++ tests/Anubis.Tests/LiveStockSupport.cs | 217 +++++ tests/Anubis.Tests/LiveSupport.cs | 287 ++++++ 13 files changed, 2073 insertions(+), 5 deletions(-) create mode 100644 src/Anubis/Db/Migrations/0006_live.sql create mode 100644 src/Anubis/Trading/LiveEngine.cs create mode 100644 tests/Anubis.Tests/LiveEngineTests.cs create mode 100644 tests/Anubis.Tests/LiveStockSupport.cs create mode 100644 tests/Anubis.Tests/LiveSupport.cs diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index ad10bc4..bfffa01 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -162,9 +162,12 @@ public static class BacktestEngine /// /// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of - /// with the data known then and the book given, and nothing else runs. + /// with the data known then and the book given, and nothing else runs. The live engine + /// decides with this same call (SPEC 5.2): is the strategy's equity at each close up to + /// , which the risk stage walks as it does in a whole run. /// - public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null) + public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null, + IReadOnlyList? history = null) { ArgumentNullException.ThrowIfNull(strategy); ArgumentNullException.ThrowIfNull(data); @@ -172,6 +175,7 @@ public static class BacktestEngine CheckSchedule(strategy); var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state); simulation.MarkThrough(day); + simulation.SeedHistory(history ?? []); return simulation.Decide(day, data.SessionTimes(day).Closes); } @@ -263,6 +267,8 @@ public static class BacktestEngine } } + public void SeedHistory(IReadOnlyList history) => _history.AddRange(history); + public void MarkThrough(DateOnly day) { foreach (var i in _data.Instruments) diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index 6ca717e..40b371c 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -118,6 +118,9 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche /// skipped and reported instead of executed blindly (trap 21, SPEC 5.6). /// public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15); + + /// A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job. + public bool IsMove { get; init; } } public enum JobOutcome @@ -131,7 +134,10 @@ public enum JobOutcome public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error); /// A run coming up, for "Prossime mosse" and the jobs list. -public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc); +public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc) +{ + public bool IsMove { get; init; } +} /// /// Runs jobs at fixed times, at intervals, or relative to market open and close (SPEC 5.5). @@ -164,7 +170,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger j.Due is not null) .OrderBy(j => j.Due) .Take(count) - .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value)) + .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove }) .ToList(); } } diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index cace228..fb3b492 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -130,7 +130,8 @@ public sealed partial class MarketDataService : IDisposable { await UsCalendar.LoadAsync(cancellationToken).ConfigureAwait(false); _work.Release(); - await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), FreshnessAsync(cancellationToken)).ConfigureAwait(false); + await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), StockLiveAsync(cancellationToken), FreshnessAsync(cancellationToken)) + .ConfigureAwait(false); } public Task WakeWorker() @@ -491,6 +492,90 @@ public sealed partial class MarketDataService : IDisposable } } + /// + /// The stock feed (IEX, issue #47): during the US session only, the stocks held, those with an order planned and the + /// market index, at most symbols as the free feed allows. Outside the session the + /// quotes come by REST when asked, and no stock is followed for freshness. + /// + private async Task StockLiveAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + var now = _clock.UtcNow; + var today = DateOnly.FromDateTime(now.UtcDateTime); + var session = UsCalendar.Sessions(today.AddDays(-1), today.AddDays(10)).FirstOrDefault(s => s.CloseUtc + StockStreamMargin > now); + if (session is null || session.OpenUtc - StockStreamMargin > now) + { + var next = session is null ? now.AddHours(1) : Min(session.OpenUtc - StockStreamMargin, now.AddHours(1)); + await _clock.WaitUntilAsync(next, cancellationToken).ConfigureAwait(false); + continue; + } + + var alpaca = await AlpacaAsync(cancellationToken).ConfigureAwait(false); + var instruments = alpaca is null ? [] : await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false); + if (alpaca is null || instruments.Count == 0) + { + await _clock.WaitUntilAsync(now.AddMinutes(5), cancellationToken).ConfigureAwait(false); + continue; + } + + var end = session.CloseUtc + StockStreamMargin; + using var round = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var collector = new MarketCollector(alpaca, _db, _clock, _bus, Freshness, logger: _logger); + var run = collector.RunLiveAsync(instruments, round.Token); + var ids = instruments.Select(i => i.Id).ToHashSet(); + while (!run.IsCompleted) + { + using var nap = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var wait = _clock.WaitUntilAsync(Min(_clock.UtcNow.AddMinutes(5), end), nap.Token); + await Task.WhenAny(run, wait).ConfigureAwait(false); + await nap.CancelAsync().ConfigureAwait(false); + if (!run.IsCompleted && (_clock.UtcNow >= end + || !(await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false)).Select(i => i.Id).ToHashSet().SetEquals(ids))) + { + await round.CancelAsync().ConfigureAwait(false); + } + } + + await run.ConfigureAwait(false); + foreach (var id in ids) + { + Freshness.Unfollow(id); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogStepFailed(_logger, ex, "live azioni"); + await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false); + } + } + } + + /// The free IEX feed follows at most 30 symbols. + public const int StockStreamLimit = 30; + + private static readonly TimeSpan StockStreamMargin = TimeSpan.FromMinutes(5); + + private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a <= b ? a : b; + + private async Task> StockLiveInstrumentsAsync(CancellationToken cancellationToken) + { + var symbols = await _db.ReadAsync(s => s.QueryAsync( + "SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (i.symbol = @m" + + " OR i.id IN (SELECT instrument_id FROM positions WHERE quantity <> 0)" + + " OR i.id IN (SELECT instrument_id FROM planned_orders WHERE status = @p)) ORDER BY i.symbol", + r => r.Text("symbol"), ("v", Venues.Alpaca), ("m", Trading.StrategyNames.MarketSymbol), ("p", "pending")), cancellationToken).ConfigureAwait(false); + var wanted = symbols.OrderBy(s => s == Trading.StrategyNames.MarketSymbol ? 0 : 1).ThenBy(s => s, StringComparer.Ordinal).Take(StockStreamLimit).ToHashSet(StringComparer.Ordinal); + var all = await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false); + return all.Where(i => wanted.Contains(i.Symbol) && i.IsLive).ToList(); + } + private async Task> LiveInstrumentsAsync(CancellationToken cancellationToken) { var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); diff --git a/src/Anubis/Db/Database.cs b/src/Anubis/Db/Database.cs index 2da0f35..dc75d8b 100644 --- a/src/Anubis/Db/Database.cs +++ b/src/Anubis/Db/Database.cs @@ -117,8 +117,16 @@ public sealed class Database : IAsyncDisposable return builder.ToString(); } + /// Fault tests only (issue #47): while true every new connection fails as if the server could not be reached. + internal bool Unreachable { get; set; } + public async Task OpenConnectionAsync(CancellationToken cancellationToken) { + if (Unreachable) + { + throw new DatabaseUnreachableException(); + } + if (_postgres is not null) { return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); @@ -239,6 +247,25 @@ public sealed class Database : IAsyncDisposable } /// One open transaction. Parameters are named @name on both engines. +/// The database could not be reached (fault tests). +public sealed class DatabaseUnreachableException : DbException +{ + public DatabaseUnreachableException() + : base("Database non raggiungibile.") + { + } + + public DatabaseUnreachableException(string message) + : base(message) + { + } + + public DatabaseUnreachableException(string message, Exception innerException) + : base(message, innerException) + { + } +} + public sealed class DbSession(DbEngine engine, DbConnection connection, DbTransaction transaction) { public DbEngine Engine => engine; diff --git a/src/Anubis/Db/Migrations/0006_live.sql b/src/Anubis/Db/Migrations/0006_live.sql new file mode 100644 index 0000000..dc3cdea --- /dev/null +++ b/src/Anubis/Db/Migrations/0006_live.sql @@ -0,0 +1,65 @@ +-- Phase 6 schema (SPEC 5.5, 5.6, 9.3, 9.4, 14, ADR 0012): the live engine, recovery after an absence, Telegram. + +-- One row for each decision the live engine makes: run_key names the strategy and the close it decides on, so a +-- decision is made once even across restarts. The row is written in the same transaction as its planned orders, +-- its decision rows and its diary lines: either all of it exists or none. state is the book the strategy decided +-- from, for the one-step comparison of SPEC 12.3 the next day. +CREATE TABLE engine_runs ( + id {uuid} PRIMARY KEY, + strategy TEXT NOT NULL, + run_key TEXT NOT NULL UNIQUE, + decision_day TEXT NOT NULL, + decision_id {uuid} NOT NULL, + mode TEXT NOT NULL, + state {json}, + proposed {json}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX engine_runs_strategy ON engine_runs (strategy, decision_day); + +-- Orders decided and not yet handed to the order manager (SPEC 5.5: the stock orders decided after the close go at +-- the next open; SPEC 5.6: an entry has a deadline and a reference price it must not drift from). The planned +-- order's id is the decision id of the trade intent: the order key derives from it, so a restart that finds the +-- execution already there never sends it twice. +CREATE TABLE planned_orders ( + id {uuid} PRIMARY KEY, + decision_id {uuid} NOT NULL, + strategy TEXT NOT NULL, + account_id {uuid} NOT NULL REFERENCES accounts (id), + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + side TEXT NOT NULL, + purpose TEXT NOT NULL, + quantity {money} NOT NULL, + exit_all {bool} NOT NULL, + stop_level {money}, + stop_offset {money}, + reference_price {money} NOT NULL, + reason TEXT NOT NULL, + due_at {timestamp} NOT NULL, + valid_until {timestamp}, + status TEXT NOT NULL, + outcome TEXT, + execution_id {uuid}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX planned_orders_due ON planned_orders (status, due_at); + +-- Absences (SPEC 5.6): measured at the restart from the last heartbeat. One longer than 24 hours is declared on the +-- Panoramica until the user acknowledges it. +CREATE TABLE absences ( + id {uuid} PRIMARY KEY, + started_at {timestamp} NOT NULL, + ended_at {timestamp} NOT NULL, + acknowledged_at {timestamp}, + created_at {timestamp} NOT NULL +){strict}; + +-- Every notification has its state (SPEC 14): pending, sent or failed, with the attempts and the last error. +ALTER TABLE notifications ADD COLUMN attempts INTEGER; +ALTER TABLE notifications ADD COLUMN next_attempt_at {timestamp}; +ALTER TABLE notifications ADD COLUMN last_error TEXT; + +CREATE INDEX notifications_status ON notifications (status, created_at); diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 1aa5df5..21aa684 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -11,6 +11,9 @@ public static class StrategyNames public const string EquityMomentum = "equity_momentum"; public const string EquityMeanrev = "equity_meanrev"; + /// The market filter of the stock strategies (SPEC 8.2): read, never traded unless it is in the universe. + public const string MarketSymbol = "SPY"; + public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base = [ (CryptoTrend, Venues.Okx, 1m), diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs index eea8cbd..c1103e7 100644 --- a/src/Anubis/Trading/DiaryText.cs +++ b/src/Anubis/Trading/DiaryText.cs @@ -81,6 +81,9 @@ public static class DiaryText public static string StopRaised(string symbol, decimal from, decimal to, string currency) => $"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale."; + public static string StopLowered(string symbol, decimal from, decimal to, string currency) => + $"Spostato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}."; + public static string StopsReplaced(int count) => count == 1 ? "Rimesso 1 stop giornaliero sulle frazioni di azione." : $"Rimessi {count} stop giornalieri sulle frazioni di azione."; diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs new file mode 100644 index 0000000..27b2cdc --- /dev/null +++ b/src/Anubis/Trading/LiveEngine.cs @@ -0,0 +1,1171 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Risk; +using Anubis.Strategies; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Trading; + +/// Reason codes of the live engine (SPEC 5.5, 5.6). +public static class LiveReasons +{ + public const string LateExitsOnly = "late_exits_only"; + public const string EntryExpired = "entry_expired"; + public const string PriceMoved = "price_moved"; + public const string MissingBars = "missing_bars"; + public const string Superseded = "superseded"; + public const string OrderInProgress = "order_in_progress"; + public const string NothingHeld = "nothing_held"; + public const string Recovered = "recovered"; +} + +/// States of a planned order. +public static class PlannedStates +{ + public const string Pending = "pending"; + public const string Submitted = "submitted"; + public const string Refused = "refused"; + public const string Expired = "expired"; + public const string Dropped = "dropped"; + public const string Superseded = "superseded"; +} + +/// Modes of a live decision. +public static class DecisionModes +{ + public const string Full = "full"; + public const string ExitsOnly = "exits_only"; + public const string Observation = "observation"; + public const string NoData = "no_data"; +} + +/// The times of SPEC 5.5 and the limits of SPEC 5.6. +public sealed record LiveEngineOptions +{ + /// The daily crypto close: 00:05 UTC. + public TimeOnly CryptoDecision { get; init; } = new(0, 5); + + /// A crypto decision is valid until 12:00 UTC of the same day; later only exits and stops (SPEC 5.6). + public TimeOnly CryptoDeadline { get; init; } = new(12, 0); + + public TimeSpan OrdersAfterOpen { get; init; } = TimeSpan.FromMinutes(5); + + public TimeSpan ExitsBeforeClose { get; init; } = TimeSpan.FromMinutes(5); + + public TimeSpan SignalsAfterClose { get; init; } = TimeSpan.FromMinutes(20); + + /// An entry of equity_meanrev is valid until 60 minutes after the open (SPEC 5.6). + public TimeSpan MeanrevEntryWindow { get; init; } = TimeSpan.FromMinutes(60); + + /// An order released later than this after its time is a recovered one: the drift rule applies. + public TimeSpan Late { get; init; } = TimeSpan.FromMinutes(10); + + /// A crypto decision made this long after 00:05 is a recovered one: the bars come at 00:20, the absence is longer. + public TimeSpan RecoveredAfter { get; init; } = TimeSpan.FromHours(1); + + public decimal StockDrift { get; init; } = 0.01m; + + public decimal CryptoDrift { get; init; } = 0.02m; + + public int WarmupDays { get; init; } = TrialData.WarmupDays; +} + +/// +/// The live engine (SPEC 5.2, 5.5): at the time of each strategy it loads the bars from the database, rebuilds the +/// strategy's book from the ledger and decides with , the call the backtest +/// uses, with the same correctives and risk stage: live and backtest differ only in the data and the book they get. +/// Orders are planned in the same transaction as the decision and handed to the order manager when due, sales first; +/// every decision has a key, so a restart never makes it twice. A strategy in observation records its signals only. +/// Each pulse does what is due now, which is also how missed work is caught up after an absence (SPEC 5.6). +/// +public sealed partial class LiveEngine : IDisposable +{ + private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + private readonly Database _db; + private readonly IClock _clock; + private readonly Ledger _ledger; + private readonly StageBook _stages; + private readonly InstrumentCatalog _catalog; + private readonly BarStore _bars; + private readonly UniverseStore _universes; + private readonly CorporateActionStore _actions; + private readonly Func _managers; + private readonly Func> _quotes; + private readonly IMarketCalendar? _calendar; + private readonly ILogger _logger; + private readonly Dictionary _dataAsked = new(StringComparer.Ordinal); + private readonly SemaphoreSlim _gate = new(1, 1); + + public LiveEngine(Database db, IClock clock, Ledger ledger, StageBook stages, Func managers, Func> quotes, + IMarketCalendar? calendar = null, LiveEngineOptions? options = null, ILogger? logger = null) + { + _db = db ?? throw new ArgumentNullException(nameof(db)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + _stages = stages ?? throw new ArgumentNullException(nameof(stages)); + _managers = managers ?? throw new ArgumentNullException(nameof(managers)); + _quotes = quotes ?? throw new ArgumentNullException(nameof(quotes)); + _calendar = calendar; + Options = options ?? new LiveEngineOptions(); + _logger = logger ?? NullLogger.Instance; + _catalog = new InstrumentCatalog(db, clock); + _bars = new BarStore(db, clock); + _universes = new UniverseStore(db, clock); + _actions = new CorporateActionStore(db, clock); + } + + public LiveEngineOptions Options { get; } + + /// Asks the data service for the bars a decision is waiting for (the history step). Called at most every few minutes. + public Func? WantData { get; init; } + + /// The time zone of the diary's times: Italian time. + public TimeZoneInfo Zone { get; init; } = Zones.Rome; + + /// + /// False until the accounts are ready: the order managers exist, the simulator has caught up and every account is + /// reconciled (SPEC 9.4). Until then the pulse does nothing, so no decision is made on a book not yet checked. + /// + public Func Ready { get; init; } = () => true; + + /// + /// The jobs of SPEC 5.5. The pulse every minute does the work; the others are the same pulse at the times the + /// user reads in "Prossime mosse", so the work starts on time. + /// + public IReadOnlyList Jobs() + { + var jobs = new List + { + new("motore", "Lavori dovuti del motore", Schedule.Every(TimeSpan.FromMinutes(1)), PulseAsync) { MaxLateness = TimeSpan.FromMinutes(5) }, + new("crypto-chiusura", "Chiusura giornaliera crypto: ricalcolo i trend", Schedule.Daily(Options.CryptoDecision, TimeZoneInfo.Utc), PulseAsync) { IsMove = true }, + }; + if (_calendar is not null) + { + jobs.Add(new("azioni-apertura", "Rimetto gli stop del giorno e mando gli ordini decisi ieri", Schedule.Market(MarketAnchor.Open, Options.OrdersAfterOpen, _calendar), PulseAsync) + { IsMove = true }); + jobs.Add(new("azioni-uscite", "Uscite della mean reversion prima della chiusura", Schedule.Market(MarketAnchor.Close, -Options.ExitsBeforeClose, _calendar), PulseAsync) + { IsMove = true }); + jobs.Add(new("azioni-segnali", "Wall Street ha chiuso: calcolo i segnali sulle azioni", Schedule.Market(MarketAnchor.Close, Options.SignalsAfterClose, _calendar), PulseAsync) + { IsMove = true }); + } + + return jobs; + } + + /// Everything due now: decisions whose time has come, the stock open and close, planned orders. + public async Task PulseAsync(CancellationToken cancellationToken) + { + if (!Ready()) + { + return; + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var now = _clock.UtcNow; + await CryptoAsync(now, cancellationToken).ConfigureAwait(false); + if (_calendar is not null) + { + await StocksAsync(now, cancellationToken).ConfigureAwait(false); + } + + await ReleaseAsync(now, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + // ---- Crypto ------------------------------------------------------------------------------------------------- + + private async Task CryptoAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(now.UtcDateTime); + var due = At(today, Options.CryptoDecision); + if (now < due) + { + return; + } + + 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); + } + + private static DateTimeOffset At(DateOnly day, TimeOnly time) => new(day.ToDateTime(time), TimeSpan.Zero); + + private static string Key(string strategy, DateOnly day) => strategy + ":" + BarStore.DayText(day); + + // ---- Stocks ------------------------------------------------------------------------------------------------- + + private async Task StocksAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var local = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, NewYork).DateTime); + var today = _calendar!.SessionOn(local); + + // The open: the daily stops on fractions go back first, then the orders decided at the last close (SPEC 5.5). + if (today is not null && now >= today.OpenUtc + Options.OrdersAfterOpen && now < today.CloseUtc) + { + await OpenAsync(today, cancellationToken).ConfigureAwait(false); + } + + // Five minutes before the close: the exits of equity_meanrev. + if (today is not null && now >= today.CloseUtc - Options.ExitsBeforeClose && now < today.CloseUtc) + { + await MeanrevCloseAsync(today, now, cancellationToken).ConfigureAwait(false); + } + + // The signals of the last closed session, valid until the next open. + var last = LastClosed(local, now); + if (last is null || now < last.CloseUtc + Options.SignalsAfterClose) + { + return; + } + + var next = NextSession(last.Date); + if (next is null) + { + return; + } + + foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) + { + var ordersDue = next.OpenUtc + Options.OrdersAfterOpen; + var entriesUntil = strategy == StrategyNames.EquityMeanrev ? next.OpenUtc + Options.MeanrevEntryWindow : SecondSessionOfWeek(next).CloseUtc; + await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, false, next.OpenUtc, now, ordersDue, + entriesUntil), cancellationToken).ConfigureAwait(false); + } + } + + private MarketSession? LastClosed(DateOnly local, DateTimeOffset now) + { + for (var day = local; day >= local.AddDays(-10); day = day.AddDays(-1)) + { + if (_calendar!.SessionOn(day) is { } session && session.CloseUtc <= now) + { + return session; + } + } + + return null; + } + + private MarketSession? NextSession(DateOnly after) + { + for (var day = after.AddDays(1); day <= after.AddDays(10); day = day.AddDays(1)) + { + if (_calendar!.SessionOn(day) is { } session) + { + return session; + } + } + + return null; + } + + // equity_momentum's weekly entries are valid for the first two sessions of the week (SPEC 5.6). + private MarketSession SecondSessionOfWeek(MarketSession session) + { + var monday = session.Date.AddDays(-(((int)session.Date.DayOfWeek + 6) % 7)); + var sessions = Enumerable.Range(0, 7).Select(i => _calendar!.SessionOn(monday.AddDays(i))).OfType().ToList(); + var second = sessions.Count > 1 ? sessions[1] : session; + return second.Date < session.Date ? session : second; + } + + private async Task OpenAsync(MarketSession session, CancellationToken cancellationToken) + { + var key = "apertura:" + BarStore.DayText(session.Date); + if (await RunExistsAsync(key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var replaced = 0; + foreach (var manager in await AlpacaManagersAsync(cancellationToken).ConfigureAwait(false)) + { + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + var positions = await _ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false); + replaced += positions.Count(p => p.Quantity > 0m && p.Quantity != decimal.Truncate(p.Quantity)); + } + + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, "sistema", key, session.Date, Guid.Empty, "open", null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + if (replaced > 0) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "stops_replaced", DiaryText.StopsReplaced(replaced), null, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + private async Task> AlpacaManagersAsync(CancellationToken cancellationToken) + { + var accounts = await _db.ReadAsync(s => s.QueryAsync("SELECT id FROM accounts WHERE broker = @b", r => r.Id("id"), ("b", Venues.Alpaca)), cancellationToken) + .ConfigureAwait(false); + return [.. accounts.Select(_managers).OfType()]; + } + + /// + /// The exits of equity_meanrev five minutes before the close (SPEC 5.5): the strategy decides on today's bar as it + /// stands, with the last price as its close, and only its exits at the close are used. They leave at once as + /// aggressive limits: there are five minutes left. + /// + private async Task MeanrevCloseAsync(MarketSession session, DateTimeOffset now, CancellationToken cancellationToken) + { + var key = "chiusura:" + Key(StrategyNames.EquityMeanrev, session.Date); + if (await RunExistsAsync(key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var stage = await _stages.GetAsync(StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); + if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is not { } manager) + { + await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); + return; + } + + var book = await BookAsync(accountId, StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); + if (book.Holdings.Count == 0) + { + await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); + return; + } + + var data = await LoadAsync(StrategyNames.EquityMeanrev, session.Date, book, provisional: true, cancellationToken).ConfigureAwait(false); + if (data.Data is null) + { + return; + } + + var strategy = CreateStrategy(StrategyNames.EquityMeanrev, stage.Qualification?.Parameters); + var options = StrategyPipeline.For(StrategyNames.EquityMeanrev, data.Data, new BacktestOptions()); + var record = BacktestEngine.DecideOnce(strategy, data.Data, book.State, session.Date, options); + var decisionId = Ids.NewId(_clock); + var exits = record.Final.Where(i => i.AtClose && i.TargetWeight == 0m && book.Holdings.ContainsKey(i.Symbol)).ToList(); + var submitted = new List<(Intent Intent, Guid? Execution, string? Refusal)>(); + foreach (var exit in exits) + { + var held = book.Holdings[exit.Symbol]; + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(held.InstrumentId, StrategyNames.EquityMeanrev, OrderSide.Sell, held.Holding.Quantity, OrderPurpose.Exit, + decisionId) + { StartAggressive = true }, cancellationToken).ConfigureAwait(false); + submitted.Add((exit, execution, refusal)); + } + + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, StrategyNames.EquityMeanrev, key, session.Date, decisionId, DecisionModes.Full, null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + foreach (var (intent, execution, refusal) in submitted) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, + [intent.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Order, + refusal is null ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, refusal is null ? [] : [refusal], + new Dictionary { ["execution"] = execution }, now), cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + // ---- Decisions ---------------------------------------------------------------------------------------------- + + /// + /// A decision moment: the strategy, the close it decides on, its key, when it was due, whether it is late (only + /// exits and stops), until when it may wait for its bars, now, when its orders are due and until when its entries + /// stay valid. + /// + private sealed record Moment(string Strategy, DateOnly Day, string Key, DateTimeOffset Due, bool Late, DateTimeOffset WaitUntil, DateTimeOffset Now, + DateTimeOffset OrdersDue, DateTimeOffset EntriesUntil); + + private async Task DecideAsync(Moment m, CancellationToken cancellationToken) + { + if (await RunExistsAsync(m.Key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var stage = await _stages.GetAsync(m.Strategy, cancellationToken).ConfigureAwait(false); + if (stage is null) + { + return; + } + + var observation = stage.Stage == StrategyStages.Observation; + var accountId = observation ? stage.AccountId : stage.OrdersAccount; + if (accountId is not { } account) + { + return; + } + + var book = observation ? Book.Empty : await BookAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false); + var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false); + if (loaded.Data is null || loaded.Missing.Count > 0) + { + if (m.Now < m.WaitUntil && !m.Late) + { + // The bars of the close have not arrived yet: ask for them and try again at the next pulse (SPEC 5.5). + await AskForDataAsync(m.Key, m.Now, m.Due, cancellationToken).ConfigureAwait(false); + return; + } + + if (loaded.Data is null || loaded.MarketMissing) + { + await NoDataAsync(m, stage, cancellationToken).ConfigureAwait(false); + return; + } + } + + var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters); + var data = loaded.Data; + var options = StrategyPipeline.For(m.Strategy, data, new BacktestOptions()); + DecisionRecord record; + if (observation) + { + // Signals only (SPEC 12.3): the backtest run from the start of the observation, on the strategy's capital. + var from = DateOnly.FromDateTime((stage.StageSince ?? m.Now).UtcDateTime); + from = from > m.Day ? m.Day : from; + var run = BacktestEngine.Run(strategy, data, options with { From = from, To = m.Day, InitialCapital = stage.Capital > 0m ? stage.Capital : 10_000m }); + record = run.Decisions.LastOrDefault(d => d.Day == m.Day) ?? new DecisionRecord(m.Day, [], []); + book = Book.FromRun(run, data, m.Day); + } + else + { + var history = await HistoryAsync(account, m.Strategy, m.Day, book.EquityAt(data, m.Day), cancellationToken).ConfigureAwait(false); + record = BacktestEngine.DecideOnce(strategy, data, book.State, m.Day, options, history); + } + + var mode = observation ? DecisionModes.Observation : m.Late || stage.ExitOnly ? DecisionModes.ExitsOnly : DecisionModes.Full; + var plan = Plan(m, mode, record, book, data, loaded.Missing, account); + if (!observation) + { + plan = plan with { Working = await WorkingAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false) }; + } + + var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false); + var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false); + } + + private async Task AskForDataAsync(string key, DateTimeOffset now, DateTimeOffset due, CancellationToken cancellationToken) + { + // Every 5 minutes for the first 45, then every hour (SPEC 5.5). + var every = now - due < TimeSpan.FromMinutes(45) ? TimeSpan.FromMinutes(5) : TimeSpan.FromHours(1); + if (WantData is null || (_dataAsked.TryGetValue(key, out var last) && now - last < every)) + { + return; + } + + _dataAsked[key] = now; + try + { + await WantData(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogDataRequestFailed(_logger, ex); + } + } + + private async Task NoDataAsync(Moment m, StrategyStage stage, CancellationToken cancellationToken) + { + var observation = stage.Stage == StrategyStages.Observation; + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, Ids.NewId(_clock), DecisionModes.NoData, null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var what = m.Strategy == StrategyNames.CryptoTrend ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni"; + var text = DiaryText.NoData(m.Strategy, what); + if (observation) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.MissingBars, text, null, cancellationToken).ConfigureAwait(false); + } + else + { + // A strategy that trades and cannot decide is something the user must know (SPEC 5.5: "e avvisa"). + await Diary.NotifyAsync(s, _clock, LiveReasons.MissingBars, text, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + /// What one decision turns into: planned orders, stops to move, notes on what was left out. + private sealed record PlanResult(IReadOnlyList Orders, IReadOnlyList<(string Symbol, decimal From, decimal To)> Stops, IReadOnlyList<(string Symbol, string Reason)> Notes, + DecisionSummary Summary, decimal Equity) + { + public IReadOnlySet Working { get; init; } = new HashSet(); + } + + private sealed record PlannedOrder(Guid InstrumentId, string Symbol, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, decimal? StopLevel, decimal? StopOffset, + decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, bool Crypto); + + /// + /// The intents become orders as the backtest plans them (BacktestEngine.Plan): target quantity from the weight and + /// the equity at the close, the difference bought or sold, a full exit when the weight is zero, stops moved on what + /// is held. In exits-only mode entries and increases are left out. + /// + private PlanResult Plan(Moment m, string mode, DecisionRecord record, Book book, BacktestDataset data, IReadOnlySet missing, Guid account) + { + var equity = book.EquityAt(data, m.Day); + var orders = new List(); + var stops = new List<(string, decimal, decimal)>(); + var notes = new List<(string, string)>(); + List bought = [], increased = [], reduced = [], sold = []; + var changed = new HashSet(StringComparer.Ordinal); + foreach (var intent in record.Final.GroupBy(i => i.Symbol, StringComparer.Ordinal).Select(g => g.Last())) + { + var instrument = data[intent.Symbol]; + if (instrument is null || data.DataOnly.Contains(intent.Symbol)) + { + continue; + } + + if (missing.Contains(intent.Symbol)) + { + notes.Add((intent.Symbol, LiveReasons.MissingBars)); + continue; + } + + book.Holdings.TryGetValue(intent.Symbol, out var held); + var current = held?.Holding.Quantity ?? 0m; + var stop = intent.Stop is { } level ? OrderRules.StopPrice(level, OrderRules.TickOf(instrument.Spec, level)) : (decimal?)null; + if (held is not null && stop is { } newStop && newStop != held.Holding.Stop) + { + stops.Add((intent.Symbol, held.Holding.Stop ?? 0m, newStop)); + } + + if (intent.TargetWeight is not { } weight || weight < 0m) + { + continue; + } + + var close = Close(instrument, m.Day); + if (close is not > 0m) + { + notes.Add((intent.Symbol, BacktestReasons.NoPrice)); + continue; + } + + var crypto = instrument.Spec.AssetClass == AssetClasses.Crypto; + var due = m.OrdersDue; + if (weight == 0m) + { + if (current > 0m) + { + orders.Add(new PlannedOrder(held!.InstrumentId, intent.Symbol, OrderSide.Sell, OrderPurpose.Exit, current, true, null, null, close.Value, intent.Reason, due, null, crypto)); + sold.Add(intent.Symbol); + changed.Add(intent.Symbol); + } + + continue; + } + + var target = weight * equity / close.Value; + var difference = target - current; + if (difference > 0m) + { + if (mode == DecisionModes.ExitsOnly) + { + notes.Add((intent.Symbol, LiveReasons.LateExitsOnly)); + continue; + } + + var id = held?.InstrumentId ?? InstrumentIdOf(data, intent.Symbol); + orders.Add(new PlannedOrder(id, intent.Symbol, OrderSide.Buy, OrderPurpose.Entry, difference, false, stop, intent.StopOffset, close.Value, intent.Reason, due, + m.EntriesUntil, crypto)); + (current > 0m ? increased : bought).Add(intent.Symbol); + changed.Add(intent.Symbol); + } + else if (difference < 0m && current > 0m) + { + orders.Add(new PlannedOrder(held!.InstrumentId, intent.Symbol, OrderSide.Sell, OrderPurpose.Exit, -difference, false, null, null, close.Value, intent.Reason, due, null, crypto)); + reduced.Add(intent.Symbol); + changed.Add(intent.Symbol); + } + } + + var heldUnchanged = book.Holdings.Keys.Where(s => !changed.Contains(s)).Order(StringComparer.Ordinal).ToList(); + var universe = data.Tradable.Count(); + var outside = Math.Max(0, universe - heldUnchanged.Count - bought.Count - increased.Count - reduced.Count); + return new PlanResult(orders, stops, notes, new DecisionSummary(bought, increased, reduced, sold, heldUnchanged, outside), equity); + } + + private Guid InstrumentIdOf(BacktestDataset data, string symbol) => _instrumentIds.TryGetValue(symbol, out var id) ? id : Guid.Empty; + + private readonly Dictionary _instrumentIds = new(StringComparer.Ordinal); + + private static decimal? Close(BacktestInstrument instrument, DateOnly day) + { + var n = instrument.CountThrough(day); + return n > 0 ? DbValues.Money((decimal)instrument.Bars[n - 1].Close) : null; + } + + private async Task> WorkingAsync(Guid account, string strategy, CancellationToken cancellationToken) => + (await _db.ReadAsync(s => s.QueryAsync("SELECT instrument_id FROM executions WHERE account_id = @a AND strategy = @s AND status = @w", + r => r.Id("instrument_id"), ("a", account), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false)).ToHashSet(); + + private async Task WriteDecisionAsync(Moment m, StrategyStage stage, Guid account, string mode, DecisionRecord record, PlanResult plan, Book book, + IReadOnlyDictionary specs, (Guid DecisionId, bool Same, IReadOnlyList Different)? oneStep, CancellationToken cancellationToken) + { + var decisionId = Ids.NewId(_clock); + var now = m.Now; + var observation = mode == DecisionModes.Observation; + var state = observation ? null : JsonSerializer.Serialize(book.Snapshot(), Json); + var proposed = JsonSerializer.Serialize(record.Proposed.Select(i => new ProposedIntent(i.Symbol, i.TargetWeight, i.Stop)).ToList(), Json); + var currency = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(m.Strategy)); + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken).ConfigureAwait(false)) + { + return; + } + + // The older orders of the strategy not yet sent are replaced by this decision (the backtest keeps one per symbol). + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, outcome = @o, updated_at = @now WHERE strategy = @s AND status = @p", cancellationToken, + ("st", PlannedStates.Superseded), ("o", LiveReasons.Superseded), ("now", now), ("s", m.Strategy), ("p", PlannedStates.Pending)).ConfigureAwait(false); + + // The stages of the decision (SPEC 5.2): what the strategy proposed, what correctives and risk changed. + foreach (var intent in record.Proposed) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, [intent.Reason], + new Dictionary { ["weight"] = intent.TargetWeight, ["stop"] = intent.Stop, ["stop_offset"] = intent.StopOffset, ["day"] = BarStore.DayText(m.Day) }, now), + cancellationToken).ConfigureAwait(false); + } + + foreach (var intent in record.Final.Where(i => i.Adjustments.Count > 0)) + { + var asked = record.Proposed.LastOrDefault(p => p.Symbol == intent.Symbol)?.TargetWeight; + var corrective = intent.Adjustments.Where(IsCorrective).ToList(); + var risk = intent.Adjustments.Where(a => !IsCorrective(a)).ToList(); + var data = new Dictionary { ["asked"] = asked, ["allowed"] = intent.TargetWeight ?? 0m }; + if (corrective.Count > 0) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Correctives, + intent.TargetWeight is > 0m ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, corrective, data, now), cancellationToken).ConfigureAwait(false); + } + + if (risk.Count > 0) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Risk, + intent.TargetWeight is > 0m ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, risk, data, now), cancellationToken).ConfigureAwait(false); + } + } + + foreach (var (symbol, reason) in plan.Notes) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Order, DecisionOutcomes.Refused, [reason], null, now), + cancellationToken).ConfigureAwait(false); + } + + if (oneStep is { } check) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(check.DecisionId, m.Strategy, account, null, DecisionStages.OneStep, + check.Same ? DecisionOutcomes.Same : DecisionOutcomes.Different, [], new Dictionary { ["different"] = check.Different }, now), cancellationToken) + .ConfigureAwait(false); + } + + if (observation) + { + foreach (var order in plan.Orders) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Order, DecisionOutcomes.Refused, + [RiskReasons.Observation], new Dictionary { ["side"] = Wire.Text(order.Side), ["quantity"] = order.Quantity }, now), cancellationToken) + .ConfigureAwait(false); + } + + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary), + new { decision = decisionId }, cancellationToken).ConfigureAwait(false); + return; + } + + foreach (var order in plan.Orders) + { + if (order.InstrumentId == Guid.Empty) + { + continue; + } + + if (plan.Working.Contains(order.InstrumentId)) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Order, DecisionOutcomes.Refused, + [LiveReasons.OrderInProgress], null, now), cancellationToken).ConfigureAwait(false); + continue; + } + + var id = Ids.NewId(_clock); + await s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, @stop, @off, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken, + ("id", id), ("d", decisionId), ("s", m.Strategy), ("a", account), ("i", order.InstrumentId), ("side", Wire.Text(order.Side)), ("p", Wire.Text(order.Purpose)), + ("q", DbValues.Money(order.Quantity)), ("all", order.ExitAll), ("stop", order.StopLevel), ("off", order.StopOffset), ("ref", order.Reference), ("r", order.Reason), + ("due", order.Due), ("until", order.ValidUntil), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [], + new Dictionary { ["side"] = Wire.Text(order.Side), ["quantity"] = order.Quantity, ["equity"] = plan.Equity, ["close"] = order.Reference, ["planned"] = id }, + now), cancellationToken).ConfigureAwait(false); + } + + foreach (var (symbol, from, to) in plan.Stops) + { + if (!book.Holdings.TryGetValue(symbol, out var held)) + { + continue; + } + + await s.ExecuteAsync("UPDATE positions SET stop_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", cancellationToken, + ("p", to), ("now", now), ("a", account), ("i", held.InstrumentId), ("s", m.Strategy)).ConfigureAwait(false); + if (from > 0m) + { + var text = to > from ? DiaryText.StopRaised(symbol, from, to, currency) : DiaryText.StopLowered(symbol, from, to, currency); + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "stop_moved", text, new { decision = decisionId, symbol, from, to }, cancellationToken).ConfigureAwait(false); + } + } + + var summary = m.Strategy == StrategyNames.CryptoTrend ? 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); + } + + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "decision", summary, new { decision = decisionId }, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent; + + private sealed record ProposedIntent(string Symbol, decimal? Weight, decimal? Stop); + + // ---- One-step comparison (SPEC 12.3) ------------------------------------------------------------------------ + + /// + /// The previous decision of the strategy again, from the book recorded then and with the data as it is now: the + /// strategy's intents (before correctives and risk) must match. An intent differs when its action differs or its + /// size by more than 10%. + /// + private async Task<(Guid, bool, IReadOnlyList)?> OneStepAsync(string strategyName, IStrategy strategy, BacktestDataset data, CancellationToken cancellationToken) + { + var previous = await _db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT decision_day, decision_id, state, proposed FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1", + r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed")), ("s", strategyName)), + cancellationToken).ConfigureAwait(false); + if (previous.State is null || previous.Proposed is null || data.Instruments.All(i => i.IndexOf(previous.Day) < 0)) + { + return null; + } + + var snapshot = JsonSerializer.Deserialize(previous.State, Json); + var recorded = JsonSerializer.Deserialize>(previous.Proposed, Json) ?? []; + if (snapshot is null) + { + return null; + } + + var state = snapshot.ToState(); + var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day).Proposed; + var different = OneStep.Compare(state, recorded.Select(p => (p.Symbol, p.Weight)).ToList(), again.Select(i => (i.Symbol, i.TargetWeight)).ToList(), data, previous.Day); + return (previous.Id, different.Count == 0, different); + } + + // ---- Releasing planned orders ------------------------------------------------------------------------------- + + private sealed record Planned(Guid Id, Guid DecisionId, string Strategy, Guid AccountId, Guid InstrumentId, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, + decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil); + + /// + /// The planned orders whose time has come go to the order manager, sales first (SPEC 5.5). An entry past its + /// deadline is dropped, and one released late is dropped when the price moved more than 1% (stocks) or 2% + /// (crypto) from the planned one (SPEC 5.6). The order's key comes from the planned order: a restart that finds + /// the execution already there marks it sent and never sends it again. + /// + private async Task ReleaseAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var due = await _db.ReadAsync(s => s.QueryAsync( + "SELECT id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until " + + "FROM planned_orders WHERE status = @p AND due_at <= @now ORDER BY due_at, id", + r => new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), + r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"), + r.MomentOrNull("valid_until")), ("p", PlannedStates.Pending), ("now", now)), cancellationToken).ConfigureAwait(false); + foreach (var order in due.OrderBy(o => o.Side == OrderSide.Buy).ThenBy(o => o.Due)) + { + try + { + await ReleaseOneAsync(order, now, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // One order that fails stays pending for the next pulse: the others still go. + LogReleaseFailed(_logger, ex, order.Id); + } + } + } + + private async Task ReleaseOneAsync(Planned order, DateTimeOffset now, CancellationToken cancellationToken) + { + var instrument = await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false); + if (instrument is null) + { + await CloseAsync(order, PlannedStates.Dropped, BacktestReasons.UnknownSymbol, null, null, cancellationToken).ConfigureAwait(false); + return; + } + + var key = ClientOrderIds.Key(order.Id); + var existing = await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM executions WHERE account_id = @a AND order_key = @k", r => r.IdOrNull("id"), + ("a", order.AccountId), ("k", key)), cancellationToken).ConfigureAwait(false); + if (existing is { } already) + { + // Sent before a restart: the execution is there, nothing goes twice. + await CloseAsync(order, PlannedStates.Submitted, null, already, null, cancellationToken).ConfigureAwait(false); + return; + } + + if (order.Side == OrderSide.Buy && order.ValidUntil is { } until && now > until) + { + await CloseAsync(order, PlannedStates.Expired, LiveReasons.EntryExpired, null, + DiaryText.Skipped($"l'acquisto di {DiaryText.Shown(instrument.Symbol)}", ReasonCatalog.Text(LiveReasons.EntryExpired)), cancellationToken).ConfigureAwait(false); + return; + } + + if (_managers(order.AccountId) is not { } manager) + { + return; + } + + if (manager.MarketOpen is { } open && !await open(instrument, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var quantity = order.Quantity; + if (order.Side == OrderSide.Sell) + { + var position = (await _ledger.PositionsAsync(order.AccountId, cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(p => p.InstrumentId == order.InstrumentId && p.Strategy == order.Strategy); + var held = position?.Quantity ?? 0m; + quantity = order.ExitAll ? held : Math.Min(quantity, held); + if (quantity <= 0m) + { + await CloseAsync(order, PlannedStates.Dropped, LiveReasons.NothingHeld, null, null, cancellationToken).ConfigureAwait(false); + return; + } + } + + var late = now - order.Due > Options.Late; + decimal? stopLevel = order.StopLevel; + if (order.Side == OrderSide.Buy) + { + var quote = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (quote is not { Bid: > 0m, Ask: > 0m }) + { + return; + } + + var limit = instrument.IsCrypto ? Options.CryptoDrift : Options.StockDrift; + var moved = Math.Abs((quote.Mid / order.Reference) - 1m); + if (late && moved > limit) + { + await CloseAsync(order, PlannedStates.Dropped, LiveReasons.PriceMoved, null, + DiaryText.EntryDropped(instrument.Symbol, Math.Round(moved * 100m, 1), limit * 100m), cancellationToken).ConfigureAwait(false); + return; + } + + if (stopLevel is null && order.StopOffset is > 0m and var offset && quote.Ask - offset > 0m) + { + // A distance from the price: the stop of a new position goes that far below the price now (SPEC 8.2, 8.3). + stopLevel = OrderRules.StopPrice(quote.Ask - offset, OrderRules.TickOf(instrument.Spec, quote.Ask - offset)); + } + } + + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) { StopLevel = stopLevel }, + cancellationToken).ConfigureAwait(false); + var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null; + await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false); + } + + private static string OrderWords(Planned order, string symbol) => + (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); + + private Task CloseAsync(Planned order, string status, string? reason, Guid? execution, string? diary, CancellationToken cancellationToken) => + _db.WriteAsync(async s => + { + var now = _clock.UtcNow; + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, outcome = @o, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("st", status), ("o", reason), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, null, DecisionStages.Order, + status == PlannedStates.Submitted ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, reason is null ? [] : [reason], + new Dictionary { ["planned"] = order.Id, ["execution"] = execution, ["side"] = Wire.Text(order.Side) }, now), cancellationToken).ConfigureAwait(false); + if (diary is not null) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, reason ?? LiveReasons.Recovered, diary, new { planned = order.Id }, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken); + + // ---- Books, data and history ------------------------------------------------------------------------------ + + private sealed record Held(Guid InstrumentId, Holding Holding); + + /// The strategy's book from the ledger: its cash and what it holds, by symbol. + private sealed record Book(decimal Cash, IReadOnlyDictionary Holdings) + { + public static Book Empty { get; } = new(0m, new Dictionary(StringComparer.Ordinal)); + + public PortfolioState State => new(Cash, Holdings.ToDictionary(h => h.Key, h => h.Value.Holding, StringComparer.Ordinal)); + + public decimal EquityAt(BacktestDataset data, DateOnly day) => Cash + Holdings.Sum(h => + h.Value.Holding.Quantity * (data[h.Key] is { } i && Close(i, day) is { } close ? close : h.Value.Holding.AveragePrice)); + + public BookSnapshot Snapshot() => new(Cash, Holdings.ToDictionary(h => h.Key, h => new HoldingSnapshot(h.Value.Holding.Quantity, h.Value.Holding.AveragePrice, + h.Value.Holding.Stop, BarStore.DayText(h.Value.Holding.EnteredOn)), StringComparer.Ordinal)); + + // The observation book is the backtest's: what the run held after the decision's close, for the diary's summary. + public static Book FromRun(BacktestRun run, BacktestDataset data, DateOnly day) + { + var holdings = new Dictionary(StringComparer.Ordinal); + foreach (var group in run.Fills.Where(f => f.Day <= day).GroupBy(f => f.Symbol, StringComparer.Ordinal)) + { + var quantity = group.Sum(f => f.Side == OrderSide.Buy ? f.Quantity : -f.Quantity); + if (quantity > 0m) + { + holdings[group.Key] = new Held(Guid.Empty, new Holding(quantity, group.Last().Price, null, group.First().Day)); + } + } + + return new Book(run.Equity.LastOrDefault(e => e.Day <= day)?.Cash ?? 0m, holdings); + } + } + + private sealed record HoldingSnapshot(decimal Quantity, decimal Price, decimal? Stop, string Entered); + + private sealed record BookSnapshot(decimal Cash, Dictionary Holdings) + { + public PortfolioState ToState() => new(Cash, Holdings.ToDictionary(h => h.Key, h => new Holding(h.Value.Quantity, h.Value.Price, h.Value.Stop, BarStore.ParseDay(h.Value.Entered)), + StringComparer.Ordinal)); + } + + private async Task BookAsync(Guid account, string strategy, CancellationToken cancellationToken) + { + var equities = await _ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + var cash = equities.FirstOrDefault(e => e.AccountId == account && e.Strategy == strategy)?.Cash ?? 0m; + var holdings = new Dictionary(StringComparer.Ordinal); + foreach (var p in (await _ledger.PositionsAsync(account, cancellationToken).ConfigureAwait(false)).Where(p => p.Strategy == strategy && p.Quantity > 0m)) + { + if (await _catalog.GetAsync(p.InstrumentId, cancellationToken).ConfigureAwait(false) is { } instrument) + { + holdings[instrument.Symbol] = new Held(p.InstrumentId, new Holding(p.Quantity, p.AveragePrice, p.StopPrice, DateOnly.FromDateTime(p.OpenedAt.UtcDateTime))); + } + } + + return new Book(cash, holdings); + } + + /// The bars of a decision, its universe and what is missing on the day of the close. + private sealed record Loaded(BacktestDataset? Data, IReadOnlySet Missing, bool MarketMissing); + + private async Task LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken) + { + var crypto = strategy == StrategyNames.CryptoTrend; + 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); + if (crypto && symbols.Count == 0) + { + symbols.UnionWith(MarketDataService.CoreCrypto); + } + + symbols.UnionWith(book.Holdings.Keys); + var market = crypto ? NoBot.BitcoinSymbol : StrategyNames.MarketSymbol; + var dataOnly = new HashSet(StringComparer.Ordinal); + if (symbols.Add(market) && !crypto) + { + dataOnly.Add(market); + } + + // 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); + var instruments = new List(); + var missing = new HashSet(StringComparer.Ordinal); + var currency = crypto ? "EUR" : "USD"; + foreach (var symbol in symbols) + { + var instrument = await _catalog.FindAsync(venue, symbol, cancellationToken).ConfigureAwait(false); + if (instrument is null || (instrument.Spec.QuoteCurrency != currency && !dataOnly.Contains(symbol))) + { + missing.Add(symbol); + continue; + } + + _instrumentIds[symbol] = instrument.Id; + var bars = (await _bars.DailyAsync(instrument.Id, from, day, cancellationToken).ConfigureAwait(false)).ToList(); + if (provisional && bars.All(b => b.Day < day) && await _quotes(symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote) + { + // Before the close: today's bar as it stands, the last price as its close. + var mid = (double)quote.Mid; + bars.Add(new DailyBar(day, mid, mid, mid, mid, 0)); + } + + if (bars.Count == 0 || bars[^1].Day < day) + { + missing.Add(symbol); + } + + if (bars.Count == 0) + { + continue; + } + + var events = instrument.IsCrypto ? [] : (await _actions.ForSymbolAsync(symbol, cancellationToken).ConfigureAwait(false)).Where(a => a.ExDate > from && a.ExDate <= day).ToList(); + instruments.Add(new BacktestInstrument(instrument.Spec, bars, events, "barre raccolte")); + } + + if (instruments.Count == 0) + { + return new Loaded(null, missing, true); + } + + IEnumerable? calendar = null; + if (!crypto && _calendar is not null) + { + // The sessions ahead, so the strategy knows the next one (earnings before it, SPEC 8.3). + calendar = instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Concat(Enumerable.Range(1, 14).Select(i => day.AddDays(i)).Where(d => _calendar.SessionOn(d) is not null)) + .Distinct().Order(); + } + + var data = new BacktestDataset(instruments, currency, calendar, dataOnly); + return new Loaded(data, missing, missing.Contains(market)); + } + + /// The strategy's equity at each close before , from the photographs, and at from its closes. + private async Task> HistoryAsync(Guid account, string strategy, DateOnly day, decimal equityNow, CancellationToken cancellationToken) + { + var rows = await _db.ReadAsync(s => s.QueryAsync( + "SELECT taken_at, equity, invested FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s ORDER BY taken_at", + r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Invested: r.Money("invested")), ("a", account), ("s", strategy)), cancellationToken).ConfigureAwait(false); + var marks = rows.GroupBy(r => DateOnly.FromDateTime(r.At.UtcDateTime)).Where(g => g.Key < day) + .Select(g => new EquityMark(g.Key, g.Last().Equity, g.Last().Invested)).ToList(); + marks.Add(new EquityMark(day, equityNow, 0m)); + return marks; + } + + /// A strategy with its parameters: those of the backtest it qualified with, otherwise the defaults. + public static IStrategy CreateStrategy(string strategy, string? parameters) + { + var family = StrategyCatalog.Find(strategy) ?? throw new ArgumentException("Unknown strategy " + strategy, nameof(strategy)); + var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal); + var values = new Dictionary(defaults, StringComparer.Ordinal); + foreach (var part in (parameters ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var pair = part.Split('=', 2); + if (pair.Length == 2 && values.ContainsKey(pair[0]) && decimal.TryParse(pair[1], NumberStyles.Number, CultureInfo.InvariantCulture, out var value)) + { + values[pair[0]] = value; + } + } + + var chosen = new StrategyParameters(values); + return family.Accepts(chosen) ? family.Create(chosen) : family.Create(new StrategyParameters(defaults)); + } + + // ---- Runs --------------------------------------------------------------------------------------------------- + + private Task RunExistsAsync(string key, CancellationToken cancellationToken) => + _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM engine_runs WHERE run_key = @k", ("k", key)).ConfigureAwait(false) > 0, cancellationToken); + + private Task ClaimOnlyAsync(string strategy, string key, DateOnly day, CancellationToken cancellationToken) => + _db.WriteAsync(s => ClaimAsync(s, strategy, key, day, Guid.Empty, "none", null, null, cancellationToken), cancellationToken); + + private async Task ClaimAsync(DbSession s, string strategy, string key, DateOnly day, Guid decisionId, string mode, string? state, string? proposed, + CancellationToken cancellationToken) => + await s.ExecuteAsync( + "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, @st, @p, @now) " + + "ON CONFLICT (run_key) DO NOTHING", cancellationToken, + ("id", Ids.NewId(_clock)), ("s", strategy), ("k", key), ("d", BarStore.DayText(day)), ("dec", decisionId), ("m", mode), + ("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0; + + public void Dispose() => _gate.Dispose(); + + [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 = "Planned order {Id} could not be released")] + private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id); +} + +/// The comparison of two sets of intents (SPEC 12.3): same action and size within 10%, for what is held and what either version enters. +public static class OneStep +{ + public const decimal SizeTolerance = 0.10m; + + public static IReadOnlyList Compare(PortfolioState state, IReadOnlyList<(string Symbol, decimal? Weight)> live, IReadOnlyList<(string Symbol, decimal? Weight)> again, + BacktestDataset data, DateOnly day) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(live); + ArgumentNullException.ThrowIfNull(again); + ArgumentNullException.ThrowIfNull(data); + var equity = state.Cash + state.Holdings.Sum(h => h.Value.Quantity * Price(data, h.Key, day, h.Value.AveragePrice)); + decimal Current(string symbol) => equity <= 0m || !state.Holdings.TryGetValue(symbol, out var h) ? 0m : h.Quantity * Price(data, symbol, day, h.AveragePrice) / equity; + string Action(string symbol, decimal? weight) => weight switch + { + null => "keep", + 0m => Current(symbol) > 0m ? "exit" : "none", + { } w when w > Current(symbol) => "buy", + { } w when w < Current(symbol) => "reduce", + _ => "keep", + }; + + var a = live.GroupBy(i => i.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Weight, StringComparer.Ordinal); + var b = again.GroupBy(i => i.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Weight, StringComparer.Ordinal); + var symbols = new SortedSet(state.Holdings.Keys, StringComparer.Ordinal); + symbols.UnionWith(a.Where(x => Action(x.Key, x.Value) == "buy").Select(x => x.Key)); + symbols.UnionWith(b.Where(x => Action(x.Key, x.Value) == "buy").Select(x => x.Key)); + var different = new List(); + foreach (var symbol in symbols) + { + var wa = a.GetValueOrDefault(symbol); + var wb = b.GetValueOrDefault(symbol); + var actionA = Action(symbol, wa); + var actionB = Action(symbol, wb); + if (actionA != actionB) + { + different.Add(symbol); + continue; + } + + if (wa is { } x && wb is { } y && Math.Max(Math.Abs(x), Math.Abs(y)) > 0m && Math.Abs(x - y) / Math.Max(Math.Abs(x), Math.Abs(y)) > SizeTolerance) + { + different.Add(symbol); + } + } + + return different; + } + + private static decimal Price(BacktestDataset data, string symbol, DateOnly day, decimal fallback) + { + var i = data[symbol]; + var n = i?.CountThrough(day) ?? 0; + return n > 0 ? (decimal)i!.Bars[n - 1].Close : fallback; + } +} diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index d1227bd..7571e11 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -75,6 +75,15 @@ public static class ReasonCatalog ["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.", ["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", ["dividend"] = "Dividendo accreditato.", + // Live engine. + ["late_exits_only"] = "Decisione in ritardo: solo uscite e stop, gli ingressi aspettano la prossima chiusura.", + ["entry_expired"] = "Ingresso scaduto: oltre l'orario in cui era valido.", + ["price_moved"] = "Il prezzo si è mosso troppo dall'orario previsto: ingresso scartato.", + ["missing_bars"] = "Mancano le barre di chiusura: niente nuove posizioni.", + ["superseded"] = "Sostituito da una decisione più recente.", + ["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.", + ["nothing_held"] = "Niente da vendere: la posizione era già chiusa.", + ["recovered"] = "Recuperato dopo un'assenza.", }; public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index bd18c80..7948674 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -183,8 +183,18 @@ public sealed partial class TradingService : IDisposable Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false))); Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile }; _settings = settings; + Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger) + { + WantData = market is null ? null : _ => market.WakeWorker(), + Ready = () => _started, + }; } + private volatile bool _started; + + /// The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery. + public LiveEngine Engine { get; } + private readonly SettingsStore? _settings; public StageBook Stages { get; } @@ -271,6 +281,7 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + _started = true; } /// @@ -295,8 +306,29 @@ public sealed partial class TradingService : IDisposable new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync), new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync), + .. Engine.Jobs(), + .. _market is null ? Array.Empty() : + [ + new ScheduledJob("fine-seduta", "Scadenza degli ordini giornalieri del simulatore azioni", + Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(1), _market.UsCalendar), ExpireDayOrdersAsync) { MaxLateness = TimeSpan.FromHours(12) }, + ], ]; + /// + /// The day orders of the stock simulator end at the close, as on the broker: the daily stops on fractions go back + /// at the next open (SPEC 5.5, 7.2). + /// + public async Task ExpireDayOrdersAsync(CancellationToken cancellationToken) + { + foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca)) + { + if (manager.Broker is PaperBroker paper) + { + await paper.ExpireDayOrdersAsync(cancellationToken).ConfigureAwait(false); + } + } + } + /// The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file. public async Task CheckRiskAsync(CancellationToken cancellationToken) { @@ -707,6 +739,7 @@ public sealed partial class TradingService : IDisposable public void Dispose() { + Engine.Dispose(); foreach (var manager in _managers.Values) { manager.Dispose(); diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs new file mode 100644 index 0000000..a8ad544 --- /dev/null +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -0,0 +1,156 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The live engine in simulation (issue #47, SPEC 5.5, 5.6, 12.3, 17 phase 6). +[TestClass] +public sealed class LiveEngineTests +{ + private static readonly DateOnly LiveFrom = new(2026, 9, 1); + + [TestMethod] + public async Task TheLiveEngineMakesTheSameTradesAsTheBacktest() + { + var last = LiveFrom.AddDays(39); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + await live.DayAsync(day).ConfigureAwait(false); + } + + // The backtest decides on the close of the day before the first live morning and fills on the live days, with + // the same correctives (crypto regime) and the same risk stage. + var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom); + Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic path should make the backtest trade: " + expected.Count); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // Every decision was written once, with its run key. + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs); + Assert.HasCount(40, runs); + Assert.AreEqual(0, live.Failures); + } + + /// + /// The stock side (SPEC 5.5): equity_meanrev decides after the close, buys at the next open, leaves five minutes + /// before the close; the trades are the backtest's, which buys at the open and sells at the close. + /// + [TestMethod] + public async Task TheStockSideMakesTheSameTradesAsTheBacktest() + { + var last = LiveFrom.AddDays(41); + await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + await live.SessionAsync(day).ConfigureAwait(false); + } + + var run = live.Backtest(StrategyNames.EquityMeanrev, LiveFrom.AddDays(-1), last); + var expected = LiveRig.Grouped(run, LiveFrom); + Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic stocks should make the backtest trade: " + expected.Count); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // One decision per session, each written once: the close of the day before the first one included, made at the + // first start as a recovered decision. + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs); + var sessions = WeekdayCalendar.Sessions(LiveFrom.AddDays(-1), last).Count(); + Assert.HasCount(sessions, runs.Where(r => r.StartsWith(StrategyNames.EquityMeanrev + ":", StringComparison.Ordinal)).ToList()); + } + + /// + /// SPEC 17 phase 6: an accelerated run of at least 10 market days with faults injected (network, a restart + /// halfway through an order, the database unreachable) ends with ledger and account reconciled and no order sent + /// twice; the trades are still the backtest's. + /// + [TestMethod] + public async Task TenDaysWithFaultsEndReconciledWithoutDuplicateOrders() + { + var last = LiveFrom.AddDays(13); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + var restarted = false; + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + var index = day.DayNumber - LiveFrom.DayNumber; + Func? faults = index switch + { + // Network down for the first minutes of the decision: no quotes, no broker. When it comes back, the + // answer to the first order is lost on the way back. + 0 => minute => + { + live.Rig.QuotesDown = live.Broker.Down = minute < 4; + if (minute == 4) + { + live.Broker.LoseNextAnswer = true; + } + + return Task.CompletedTask; + } + , + + // The process dies with a purchase working at the broker and starts again. + 11 => async minute => + { + if (!restarted && await live.WorkingOrdersAsync().ConfigureAwait(false) > 0) + { + restarted = true; + await live.RestartAsync().ConfigureAwait(false); + } + } + , + + // The database cannot be reached around the decision. + 12 => minute => + { + live.DatabaseDown = minute < 6; + return Task.CompletedTask; + } + , + _ => null, + }; + await live.DayAsync(day, faults).ConfigureAwait(false); + if (index == 0) + { + Assert.IsFalse(live.Broker.LoseNextAnswer, "An answer must have been lost."); + } + } + + Assert.IsTrue(restarted, "The run must restart halfway through an order."); + Assert.AreEqual(1, live.Restarts); + Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work."); + + // The trades are the backtest's: the faults delayed them by minutes, never changed or repeated them. + var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // No order twice: one order per client id, one execution per order key, one decision per run key. + var orders = await live.Rig.QueryAsync("SELECT client_order_id FROM orders", r => r.Text("client_order_id")).ConfigureAwait(false); + Assert.HasCount(orders.Distinct(StringComparer.Ordinal).Count(), orders); + foreach (var id in live.Sent.Select(r => r.ClientOrderId).Distinct(StringComparer.Ordinal)) + { + Assert.Contains(id, orders, "Every order sent is in the ledger."); + } + + var keys = await live.Rig.QueryAsync("SELECT order_key FROM executions", r => r.Text("order_key")).ConfigureAwait(false); + Assert.HasCount(keys.Distinct(StringComparer.Ordinal).Count(), keys); + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(14, runs.Distinct(StringComparer.Ordinal)); + Assert.HasCount(14, runs); + + // Ledger and account agree; the account may keep dust below the lot that the ledger wrote off (SPEC 7.2). + var report = await live.Reconciler.ReconcileAsync(live.Manager, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences)); + var ledger = (await live.Rig.Ledger.PositionsAsync(live.Okx.AccountId, CancellationToken.None).ConfigureAwait(false)) + .Where(p => p.Quantity != 0m) + .GroupBy(p => p.InstrumentId).ToDictionary(g => live.Instruments.Values.Single(i => i.Id == g.Key).Symbol, g => g.Sum(p => p.Quantity), StringComparer.Ordinal); + var account = (await live.Paper.GetPositionsAsync(CancellationToken.None).ConfigureAwait(false)).Where(p => p.Quantity != 0m) + .ToDictionary(p => p.Symbol, p => p.Quantity, StringComparer.Ordinal); + CollectionAssert.AreEquivalent(account.Where(a => a.Value >= (live.Instruments[a.Key].Spec.LotSize ?? 0m)).Select(a => a.Key).ToList(), ledger.Keys.ToList()); + foreach (var (symbol, quantity) in account.Where(a => ledger.ContainsKey(a.Key))) + { + Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol); + } + } +} diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs new file mode 100644 index 0000000..98f2a2b --- /dev/null +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -0,0 +1,217 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// Every weekday is a session, 9:30–16:00 in New York (13:30–20:00 UTC in September and October). +internal sealed class WeekdayCalendar : IMarketCalendar +{ + public MarketSession? SessionOn(DateOnly day) => day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday + ? null + : new MarketSession(day, new DateTimeOffset(day.ToDateTime(new TimeOnly(13, 30)), TimeSpan.Zero), new DateTimeOffset(day.ToDateTime(new TimeOnly(20, 0)), TimeSpan.Zero)); + + public static IEnumerable Sessions(DateOnly from, DateOnly to) + { + for (var day = from; day <= to; day = day.AddDays(1)) + { + if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + yield return day; + } + } + } +} + +/// +/// The stock side of the live engine on the internal Alpaca simulator (issue #47, SPEC 5.5): signals after the close, +/// the orders at the next open, the exits of equity_meanrev five minutes before the close, with synthetic stocks that +/// dip for three sessions and recover. +/// +internal sealed class StockRig : IAsyncDisposable +{ + public static readonly string[] Stocks = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"]; + + /// Dollars for a euro: the capital is entrusted in euro (SPEC 7.1). + public const decimal Rate = 1.10m; + + private readonly Dictionary _instruments = new(StringComparer.Ordinal); + private readonly WeekdayCalendar _calendar = new(); + + private StockRig(TradingRig rig) => Rig = rig; + + public TradingRig Rig { get; } + + public AccountContext Alpaca { get; private set; } = null!; + + public PaperBroker Paper { get; private set; } = null!; + + public OrderManager Manager { get; private set; } = null!; + + public LiveEngine Engine { get; private set; } = null!; + + public EquityBook Equity { get; private set; } = null!; + + public Dictionary> Bars { get; } = new(StringComparer.Ordinal); + + public static async Task CreateAsync(DateOnly liveFrom, DateOnly last, string strategy = StrategyNames.EquityMeanrev, decimal capital = 10_000m) + { + var rig = new StockRig(await TradingRig.CreateAsync().ConfigureAwait(false)); + await rig.SetUpAsync(liveFrom, last, strategy, capital).ConfigureAwait(false); + return rig; + } + + private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, string strategy, decimal capital) + { + var none = CancellationToken.None; + Rig.Clock.Set(new DateTimeOffset(liveFrom.AddDays(-1).ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero)); + Alpaca = await Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); + var sessions = WeekdayCalendar.Sessions(last.AddDays(-700), last).ToList(); + var store = new BarStore(Rig.Db, Rig.Clock); + var members = new List(); + for (var i = 0; i < Stocks.Length; i++) + { + var symbol = Stocks[i]; + _instruments[symbol] = await Rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false); + Bars[symbol] = Path(sessions, 50 + (i * 20), phase: i * 3, seed: (uint)(i + 11)); + members.Add(new UniverseMember(_instruments[symbol].Id, symbol, i + 1, 1e9)); + } + + _instruments[StrategyNames.MarketSymbol] = await Rig.InstrumentAsync(TradingRig.Stock(StrategyNames.MarketSymbol) with { IsFund = true }).ConfigureAwait(false); + Bars[StrategyNames.MarketSymbol] = Path(sessions, 400, phase: 5, seed: 3, dips: false); + foreach (var (symbol, bars) in Bars) + { + await store.UpsertDailyAsync(_instruments[symbol].Id, bars.Where(b => b.Day < liveFrom), "test", none).ConfigureAwait(false); + } + + await new UniverseStore(Rig.Db, Rig.Clock).SaveAsync(Universes.Equity, liveFrom.AddDays(-30), members, none).ConfigureAwait(false); + await Rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)", + none, ("id", Ids.NewId(Rig.Clock)), ("s", strategy), ("a", Alpaca.AccountId), ("st", StrategyStages.Simulation), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none) + .ConfigureAwait(false); + var fx = new FxStore(Rig.Db, Rig.Clock); + await fx.UpsertAsync(WeekdayCalendar.Sessions(liveFrom.AddDays(-10), last).Select(d => new FxRate("EUR", "USD", d, Rate, "test")), none).ConfigureAwait(false); + await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Alpaca, capital, "test", none).ConfigureAwait(false); + Paper = Rig.Paper(PaperOptions.Alpaca(), Alpaca.AccountId); + await Paper.DepositAsync(capital * Rate, "USD", none).ConfigureAwait(false); + Manager = Rig.Manager(Paper, Alpaca); + var stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar); + Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx); + } + + /// + /// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the + /// close under its 5-session average, so equity_meanrev buys and sells a few sessions later. + /// + public static List Path(IReadOnlyList sessions, double start, int phase, uint seed, bool dips = true) + { + var bars = new List(sessions.Count); + var price = start; + var state = (seed * 2654435761u) + 1u; + double Next() + { + state = (state * 1664525u) + 1013904223u; + return (state >> 8) / (double)(1 << 24); + } + + for (var i = 0; i < sessions.Count; i++) + { + var cycle = (i + phase) % 17; + var change = dips && cycle >= 14 ? -0.025 : (dips ? 0.008 : 0.003) + ((Next() - 0.5) * 0.012); + var open = Math.Round(price * (1 + ((Next() - 0.5) * 0.004)), 2); + var close = Math.Round(open * (1 + change), 2); + var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.006)), 2); + var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.006)), 2); + bars.Add(new DailyBar(sessions[i], open, high, low, close, 5_000_000)); + price = close; + } + + return bars; + } + + private DailyBar? Bar(string symbol, DateOnly day) => Bars[symbol].SingleOrDefault(b => b.Day == day); + + private void Quotes(DateOnly day, Func pick) + { + foreach (var symbol in Bars.Keys) + { + if (Bar(symbol, day) is { } bar) + { + var price = (decimal)pick(bar); + Rig.Quote(symbol, price - 0.01m, price + 0.01m, 1000m); + } + } + } + + private async Task MinutesAsync(int count) + { + for (var i = 0; i < count; i++) + { + await Engine.PulseAsync(CancellationToken.None).ConfigureAwait(false); + await Rig.TurnsAsync(Manager, 1, TimeSpan.FromMinutes(1)).ConfigureAwait(false); + } + } + + /// + /// One session: the orders decided last night go at 9:35 with the open as price; at midday the quotes touch the + /// low (stops); at 15:55 the price is the close and the meanrev exits leave; at 16:16 the bar of the day arrives and + /// at 16:20 the signals are computed; the day orders expire and the equity is photographed. + /// + public async Task SessionAsync(DateOnly day) + { + if (_calendar.SessionOn(day) is not { } session) + { + return; + } + + var none = CancellationToken.None; + Rig.Clock.Set(session.OpenUtc.AddMinutes(5)); + Quotes(day, b => b.Open); + await MinutesAsync(15).ConfigureAwait(false); + Rig.Clock.Set(session.OpenUtc.AddHours(3)); + Quotes(day, b => b.Low); + await MinutesAsync(3).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(-5)); + Quotes(day, b => b.Close); + await MinutesAsync(4).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(1)); + await Paper.ExpireDayOrdersAsync(none).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(16)); + await Task.WhenAll(Bars.Select(b => new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[b.Key].Id, b.Value.Where(x => x.Day == day), "test", none))) + .ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(20)); + await MinutesAsync(3).ConfigureAwait(false); + foreach (var symbol in Stocks) + { + await Rig.Ledger.MarkAsync(_instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false); + } + + await Equity.TakeAsync(none).ConfigureAwait(false); + } + + public BacktestRun Backtest(string strategy, DateOnly from, DateOnly to, decimal capital = 10_000m * Rate) + { + var instruments = Bars.Select(b => new BacktestInstrument(_instruments[b.Key].Spec, b.Value.Where(x => x.Day <= to && x.Day >= to.AddDays(-700)).ToList())); + var calendar = Bars[Stocks[0]].Select(b => b.Day).Where(d => d <= to.AddDays(14)); + var data = new BacktestDataset(instruments, "USD", calendar, [StrategyNames.MarketSymbol]); + var options = StrategyPipeline.For(strategy, data, new BacktestOptions { InitialCapital = capital, From = from, To = to }); + return BacktestEngine.Run(LiveEngine.CreateStrategy(strategy, null), data, options); + } + + /// The live fills by New York day, symbol and side. + public async Task> LiveFillsAsync() + { + var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at", + r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false); + return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))]; + } + + public ValueTask DisposeAsync() + { + Engine.Dispose(); + return Rig.DisposeAsync(); + } +} diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs new file mode 100644 index 0000000..46a538b --- /dev/null +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -0,0 +1,287 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The live engine on the internal simulator, driven by a manual clock through synthetic days (issue #47): the bars +/// of each day arrive at its end, the quotes follow the open, the low and the close of the day, and the engine and +/// the order manager work minute by minute. The same bars run through the backtest for the parity test; the broker, +/// the quotes and the database can fail, and the process can restart, for the fault run. +/// +internal sealed class LiveRig : IAsyncDisposable +{ + public static readonly string[] Coins = ["BTC-EUR", "ETH-EUR", "SOL-EUR"]; + + private readonly Dictionary _instruments = new(StringComparer.Ordinal); + private readonly List _sent = []; + + private LiveRig(TradingRig rig) => Rig = rig; + + public TradingRig Rig { get; } + + public AccountContext Okx { get; private set; } = null!; + + public PaperBroker Paper { get; private set; } = null!; + + /// The simulator behind a broker that can lose answers or go down (network faults). + public FaultyBroker Broker { get; private set; } = null!; + + public OrderManager Manager { get; private set; } = null!; + + public StageBook Stages { get; private set; } = null!; + + public LiveEngine Engine { get; private set; } = null!; + + public EquityBook Equity { get; private set; } = null!; + + public Reconciler Reconciler { get; private set; } = null!; + + public Dictionary> Bars { get; } = new(StringComparer.Ordinal); + + public IReadOnlyDictionary Instruments => _instruments; + + /// Work that failed as the scheduler would see it: a pulse or a turn during a fault. + public int Failures { get; private set; } + + public int Restarts { get; private set; } + + /// Every order request that reached the broker, across restarts. + public IReadOnlyList Sent => [.. _sent, .. Broker.Sent]; + + /// Every new database connection fails while this is true. + public bool DatabaseDown + { + get => Rig.Db.Unreachable; + set => Rig.Db.Unreachable = value; + } + + /// + /// synthetic daily bars for each coin up to ; those before + /// are stored at once, the others arrive one per day. + /// + public static async Task CreateAsync(DateOnly liveFrom, DateOnly last, int days = 700, string stage = StrategyStages.Simulation, decimal capital = 10_000m) + { + var rig = new LiveRig(await TradingRig.CreateAsync().ConfigureAwait(false)); + await rig.SetUpAsync(liveFrom, last, days, stage, capital).ConfigureAwait(false); + return rig; + } + + private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, int days, string stage, decimal capital) + { + var none = CancellationToken.None; + Rig.Clock.Set(new DateTimeOffset(liveFrom.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero)); + Okx = await Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var store = new BarStore(Rig.Db, Rig.Clock); + var seed = 7u; + foreach (var (symbol, start) in new[] { ("BTC-EUR", 30000.0), ("ETH-EUR", 2000.0), ("SOL-EUR", 60.0) }) + { + var spec = MarketDataStoreTests.Okx(symbol) with { ListedAt = null }; + _instruments[symbol] = await Rig.InstrumentAsync(spec).ConfigureAwait(false); + Bars[symbol] = Synthetic(last.AddDays(1 - days), days, start, seed++); + await store.UpsertDailyAsync(_instruments[symbol].Id, Bars[symbol].Where(b => b.Day < liveFrom.AddDays(-1)), "test", none).ConfigureAwait(false); + } + + await Rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)", + none, ("id", Ids.NewId(Rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none) + .ConfigureAwait(false); + var fx = new FxStore(Rig.Db, Rig.Clock); + await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Okx, capital, "test", none).ConfigureAwait(false); + Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId); + await Paper.DepositAsync(capital, "EUR", none).ConfigureAwait(false); + Stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx); + Reconciler = new Reconciler(Rig.Db, Rig.Clock, Rig.Ledger); + Build(); + } + + private void Build() + { + Broker = new FaultyBroker(Paper); + Manager = Rig.Manager(Broker, Okx); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync); + } + + /// + /// The process dies and starts again: a new simulator on its saved book, a new order manager and engine on the same + /// database, the account reconciled before the first pulse as at a real start (SPEC 9.4). + /// + public async Task RestartAsync() + { + _sent.AddRange(Broker.Sent); + Engine.Dispose(); + Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId); + Build(); + Restarts++; + await Reconciler.ReconcileAsync(Manager, CancellationToken.None).ConfigureAwait(false); + } + + /// + /// A deterministic path with regimes: long rises, falls and flat stretches with noise, so the trend strategy enters, + /// moves its stops and leaves. The open of each day is the close of the day before; the volume makes the coin + /// liquid enough for the universe. + /// + public static List Synthetic(DateOnly first, int days, double start, uint seed) + { + var bars = new List(days); + var price = start; + var state = (seed * 2654435761u) + 1u; + double Next() + { + state = (state * 1664525u) + 1013904223u; + return (state >> 8) / (double)(1 << 24); + } + + for (var i = 0; i < days; i++) + { + var regime = ((i / 45) + (int)seed) % 4; + var drift = regime switch { 0 => 0.009, 1 => -0.008, 2 => 0.002, _ => 0.012 }; + var change = drift + ((Next() - 0.5) * 0.04); + var open = price; + var close = Math.Round(price * (1 + change), 2); + var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.01)), 2); + var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.01)), 2); + bars.Add(new DailyBar(first.AddDays(i), open, high, low, close, 50_000_000 / close)); + price = close; + } + + return bars; + } + + public DailyBar Bar(string symbol, DateOnly day) => Bars[symbol].Single(b => b.Day == day); + + /// The bar of a day reaches the database, as the history step stores it after midnight. + public Task StoreBarAsync(DateOnly day) => Task.WhenAll(Coins.Select(c => + new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[c].Id, Bars[c].Where(b => b.Day == day), "test", CancellationToken.None))); + + public void Quotes(DateOnly day, Func pick) + { + foreach (var coin in Coins) + { + var price = (decimal)pick(Bar(coin, day)); + Rig.Quote(coin, price * 0.9999m, price * 1.0001m, 1000m); + } + } + + /// + /// One UTC day, minute by minute where it matters: yesterday's bar arrives, from 00:05 the engine pulses every + /// minute with the open as price and the orders are worked; at noon the quotes go to the day's low (stops), at the + /// end of the day to the close, where positions are valued and the equity photographed. + /// runs before each morning minute with its index: the fault tests break and mend things there. + /// + public async Task DayAsync(DateOnly day, Func? minute = null, int morning = 20) + { + var none = CancellationToken.None; + var midnight = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + Rig.Clock.Set(midnight.AddMinutes(1)); + await StoreBarAsync(day.AddDays(-1)).ConfigureAwait(false); + Rig.Clock.Set(midnight.AddMinutes(5)); + Quotes(day, b => b.Open); + for (var i = 0; i < morning; i++) + { + if (minute is not null) + { + await minute(i).ConfigureAwait(false); + } + + await MinuteAsync().ConfigureAwait(false); + } + + Rig.Clock.Set(midnight.AddHours(12)); + Quotes(day, b => b.Low); + for (var i = 0; i < 3; i++) + { + await MinuteAsync().ConfigureAwait(false); + } + + Rig.Clock.Set(midnight.AddHours(23).AddMinutes(55)); + Quotes(day, b => b.Close); + for (var i = 0; i < 2; i++) + { + await MinuteAsync().ConfigureAwait(false); + } + + foreach (var coin in Coins) + { + await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false); + } + + await Equity.TakeAsync(none).ConfigureAwait(false); + } + + /// One minute of the process: the engine's pulse, then a turn of the simulator and of the order manager. + private async Task MinuteAsync() + { + await SafeAsync(() => Engine.PulseAsync(CancellationToken.None)).ConfigureAwait(false); + await SafeAsync(async () => + { + Rig.Refresh(); + await Paper.PumpAsync(CancellationToken.None).ConfigureAwait(false); + await Manager.TickAsync(CancellationToken.None).ConfigureAwait(false); + }).ConfigureAwait(false); + Rig.Clock.Advance(TimeSpan.FromMinutes(1)); + } + + /// A failure the scheduler would log and retry at the next run: counted, never thrown. + private async Task SafeAsync(Func work) + { + try + { + await work().ConfigureAwait(false); + } + catch (Exception ex) when (ex is System.Data.Common.DbException or BrokerException) + { + Failures++; + } + } + + /// Orders other than the protective stops still working at the simulator. + public async Task WorkingOrdersAsync() => + (await Paper.GetOpenOrdersAsync(CancellationToken.None).ConfigureAwait(false)).Count(o => o.StopPrice is null); + + /// The same bars through the backtest, with the same correctives and risk stage, from . + public BacktestRun Backtest(DateOnly from, DateOnly to, decimal capital = 10_000m) + { + var data = new BacktestDataset(Coins.Select(c => new BacktestInstrument(_instruments[c].Spec, Bars[c].Where(b => b.Day <= to).ToList())), "EUR"); + var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = capital, From = from, To = to }); + return BacktestEngine.Run(LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, options); + } + + /// The backtest fills from , by day, symbol and side. + public static List<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> Grouped(BacktestRun run, DateOnly from) => + [.. run.Fills.Where(f => f.Day >= from).GroupBy(f => (f.Day, f.Symbol, f.Side)).Select(g => (g.Key.Day, g.Key.Symbol, g.Key.Side, g.Sum(f => f.Quantity)))]; + + /// The live fills by UTC day, symbol and side. + public async Task> LiveFillsAsync() + { + var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at", + r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false); + return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))]; + } + + /// The live fills match the backtest's: the same days, symbols and sides, quantities within 1%. + public static void AssertSameTrades(IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> expected, + IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> actual) + { + var report = "backtest:\n" + string.Join("\n", expected.Select(e => " " + e)) + "\nlive:\n" + string.Join("\n", actual.Select(a => " " + a)); + Console.WriteLine(report); + Assert.HasCount(expected.Count, actual, report); + foreach (var e in expected) + { + var match = actual.SingleOrDefault(a => a.Day == e.Day && a.Symbol == e.Symbol && a.Side == e.Side); + Assert.AreNotEqual(default, match, "Missing live fill " + e + "\n" + report); + Assert.IsLessThanOrEqualTo(0.01m, Math.Abs(match.Quantity - e.Quantity) / e.Quantity, "Quantity apart: " + e + " vs " + match + "\n" + report); + } + } + + public ValueTask DisposeAsync() + { + DatabaseDown = false; + Engine.Dispose(); + return Rig.DisposeAsync(); + } +}