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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:28:08 +01:00
1 parent 98ee504dab
commit 41e067e7d1
13 files changed
+2073 -5

No files matched your search

+8 -2
View File
@@ -162,9 +162,12 @@ public static class BacktestEngine
/// <summary>
/// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs.
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs. The live engine
/// decides with this same call (SPEC 5.2): <paramref name="history"/> is the strategy's equity at each close up to
/// <paramref name="day"/>, which the risk stage walks as it does in a whole run.
/// </summary>
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<EquityMark>? 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<EquityMark> history) => _history.AddRange(history);
public void MarkThrough(DateOnly day)
{
foreach (var i in _data.Instruments)
+8 -2
View File
@@ -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).
/// </summary>
public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job.</summary>
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);
/// <summary>A run coming up, for "Prossime mosse" and the jobs list.</summary>
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; }
}
/// <summary>
/// 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<Schedu
return _jobs.Values.Where(j => 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();
}
}
+86 -1
View File
@@ -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
}
}
/// <summary>
/// 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 <see cref="StockStreamLimit"/> symbols as the free feed allows. Outside the session the
/// quotes come by REST when asked, and no stock is followed for freshness.
/// </summary>
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);
}
}
}
/// <summary>The free IEX feed follows at most 30 symbols.</summary>
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<IReadOnlyList<Instrument>> 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<IReadOnlyList<Instrument>> LiveInstrumentsAsync(CancellationToken cancellationToken)
{
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
+27
View File
@@ -117,8 +117,16 @@ public sealed class Database : IAsyncDisposable
return builder.ToString();
}
/// <summary>Fault tests only (issue #47): while true every new connection fails as if the server could not be reached.</summary>
internal bool Unreachable { get; set; }
public async Task<DbConnection> 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
}
/// <summary>One open transaction. Parameters are named <c>@name</c> on both engines.</summary>
/// <summary>The database could not be reached (fault tests).</summary>
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;
+65
View File
@@ -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);
+3
View File
@@ -11,6 +11,9 @@ public static class StrategyNames
public const string EquityMomentum = "equity_momentum";
public const string EquityMeanrev = "equity_meanrev";
/// <summary>The market filter of the stock strategies (SPEC 8.2): read, never traded unless it is in the universe.</summary>
public const string MarketSymbol = "SPY";
public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base =
[
(CryptoTrend, Venues.Okx, 1m),
+3
View File
@@ -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.";
File diff suppressed because it is too large. Load diff
+9
View File
@@ -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;
+33
View File
@@ -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;
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
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;
}
/// <summary>
@@ -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<ScheduledJob>() :
[
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) },
],
];
/// <summary>
/// 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).
/// </summary>
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);
}
}
}
/// <summary>The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file.</summary>
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();