IsLeftoverAsync()
+ {
+ try
+ {
+ await using var db = Database.Open(Config.Db!, allowCreate: false);
+ if ((await Migrations.StatusAsync(db, CancellationToken.None).ConfigureAwait(false)).IsEmpty)
+ {
+ return true;
+ }
+
+ var row = await Installation.ReadRowAsync(db, CancellationToken.None).ConfigureAwait(false);
+ return row is null ? !await Installation.HasDataAsync(db, CancellationToken.None).ConfigureAwait(false)
+ : row.ProtectedRestart && row.Fingerprint != Installation.ReadFile(Config.Data)?.Fingerprint;
+ }
+ catch (Exception ex) when (ex is System.Data.Common.DbException or IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException)
+ {
+ LogStepFailed(logger, ex);
+ return false;
+ }
+ }
+
/// The choice is done: the database it opened is the one in use.
internal void KeepChoice() => _createdByChoice = false;
diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css
index 956a967..0eea896 100644
--- a/src/Anubis.Server/Assets/app.css
+++ b/src/Anubis.Server/Assets/app.css
@@ -310,6 +310,9 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.chart-axis { position: relative; }
.chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; }
.chart-plot { position: relative; }
+.chart-days { position: relative; height: 18px; margin: 8px 84px 0 64px; }
+.chart-days span { position: absolute; transform: translateX(-50%); color: var(--text-3); font-size: 13px; white-space: nowrap; }
+.chart-days span:first-child { transform: none; }
.chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
.chart .grid { stroke: var(--rule-inner); stroke-width: 1; }
.chart .area { fill: var(--text); opacity: .05; }
@@ -796,7 +799,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; }
.half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; }
.half + .half { border-left: 1px solid var(--rule); }
- .segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; }
+ .segmented, .cell-change, .cell-extra, .long, .chart-axis, .chart-days { display: none; }
.lead { margin-top: 12px; }
.big-result { gap: 12px; }
.big-number { font-size: 46px; line-height: 48px; }
diff --git a/src/Anubis.Server/Components/EquityChart.razor b/src/Anubis.Server/Components/EquityChart.razor
index 3039dcb..1206889 100644
--- a/src/Anubis.Server/Components/EquityChart.razor
+++ b/src/Anubis.Server/Components/EquityChart.razor
@@ -48,6 +48,12 @@
@Text(Points[^1].Equity, 0)
+
+ @foreach (var i in Days())
+ {
+ @Format.AxisDay(Points[i].Day, Points[^1].Day.DayNumber - Points[0].Day.DayNumber)
+ }
+
@EquityLabel
@if (benchLine.Length > 0)
@@ -102,6 +108,9 @@
private string Text(decimal amount, int decimals = 2) => Native ? Format.Money(amount, Currency, decimals: decimals) : Shell.Money(amount, Currency, decimals: decimals);
+ // Five dates at even distances, first and last included; fewer when there are not enough days.
+ private IEnumerable Days() => Enumerable.Range(0, 5).Select(i => i * (Points.Count - 1) / 4).Distinct();
+
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
diff --git a/src/Anubis/Core/Format.cs b/src/Anubis/Core/Format.cs
index a3ab409..ca1106b 100644
--- a/src/Anubis/Core/Format.cs
+++ b/src/Anubis/Core/Format.cs
@@ -166,6 +166,11 @@ public static class Format
public static string LongDate(DateOnly date) =>
string.Create(CultureInfo.InvariantCulture, $"{date.Day} {_monthsLong[date.Month - 1]} {date.Year}");
+ /// A day under a chart that covers days: 12 ago, or ago 2024 over more than a year.
+ public static string AxisDay(DateOnly day, int span) => span > 370
+ ? string.Create(CultureInfo.InvariantCulture, $"{_months[day.Month - 1]} {day.Year}")
+ : string.Create(CultureInfo.InvariantCulture, $"{day.Day} {_months[day.Month - 1]}");
+
/// How long ago, in words: 4 secondi fa, 3 minuti fa.
public static string Ago(TimeSpan elapsed)
{
diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs
index afdfff4..2a06bcb 100644
--- a/src/Anubis/Data/MarketDataService.cs
+++ b/src/Anubis/Data/MarketDataService.cs
@@ -561,8 +561,11 @@ public sealed partial class MarketDataService : IDisposable
await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false);
}
- /// Splits and dividends of the stock universe from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10).
- public async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken)
+ /// Splits and dividends of the stocks the bot follows or still owes for, from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10).
+ public Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) => RefreshCorporateActionsAsync([], null, cancellationToken);
+
+ /// The same with more symbols, at least back to : what a rebuild of an account is about to write.
+ public async Task RefreshCorporateActionsAsync(IReadOnlyCollection more, DateOnly? since, CancellationToken cancellationToken)
{
if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca)
{
@@ -570,8 +573,15 @@ public sealed partial class MarketDataService : IDisposable
}
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
- var universe = await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false);
- if (universe.Count == 0)
+ var symbols = (await _universes.AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false)).Select(m => m.Symbol).Concat(more)
+ .ToHashSet(StringComparer.Ordinal);
+
+ // Also what is held or was sold lately and left the universe: its splits and dividends are still owed.
+ symbols.UnionWith(await _db.ReadAsync(s => s.QueryAsync(
+ "SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (EXISTS (SELECT 1 FROM positions p WHERE p.instrument_id = i.id) " +
+ "OR EXISTS (SELECT 1 FROM fills f WHERE f.instrument_id = i.id AND f.executed_at >= @at))", r => r.Text("symbol"),
+ ("v", Venues.Alpaca), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false));
+ if (symbols.Count == 0)
{
return;
}
@@ -580,11 +590,18 @@ public sealed partial class MarketDataService : IDisposable
var last = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT created_at FROM corporate_actions ORDER BY created_at DESC LIMIT 1", r => r.Moment("created_at"))
.ConfigureAwait(false)).Select(m => (DateTimeOffset?)m).FirstOrDefault(), cancellationToken).ConfigureAwait(false);
var from = last is { } known && DateOnly.FromDateTime(known.UtcDateTime) < today ? DateOnly.FromDateTime(known.UtcDateTime) : today;
- var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken)
- .ConfigureAwait(false);
+ if (since is { } far && far < from)
+ {
+ from = far;
+ }
+
+ var actions = await alpaca.FetchCorporateActionsAsync(symbols.Order(StringComparer.Ordinal).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken).ConfigureAwait(false);
await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false);
}
+ /// How long a stock sold still owes the dividends of when it was held: a rebuild or a long stop brings them late.
+ public static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90);
+
private async Task PruneAsync(CancellationToken cancellationToken)
{
await new BarStore(_db, _clock).PruneMinutesAsync(cancellationToken).ConfigureAwait(false);
diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs
index 19b9d3b..4254f8d 100644
--- a/src/Anubis/Platform/Installation.cs
+++ b/src/Anubis/Platform/Installation.cs
@@ -108,7 +108,7 @@ public static class Installation
private static readonly string[] _dataTables = ["users", "accounts", "orders", "fills", "cash_ledger"];
- private static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s =>
+ public static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s =>
{
foreach (var table in _dataTables)
{
@@ -179,7 +179,7 @@ public static class Installation
// Sessions of the old database do not survive: everyone signs in again.
await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false);
- await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false);
+ await DisarmAsync(s, clock, null, cancellationToken).ConfigureAwait(false);
await Trading.Diary.NotifyAsync(s, clock, "protected_restart",
$"{reason}: il database ha una nuova impronta e il bot riparte protetto, con \"Ferma tutto\" acceso. Guarda cosa ho ricostruito e riparti dalla pagina Rischio.",
cancellationToken).ConfigureAwait(false);
@@ -191,24 +191,27 @@ public static class Installation
///
/// Switches the protected restart on without changing the fingerprint: the accounts hold orders this database never
- /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says.
+ /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. What was asked or
+ /// begun from on is of today, not of the copy, and stays.
///
- public static Task ProtectAsync(Database db, IClock clock, CancellationToken cancellationToken = default)
+ public static Task ProtectAsync(Database db, IClock clock, DateTimeOffset before, string message, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(clock);
return db.WriteAsync(async s =>
{
await s.ExecuteAsync("UPDATE installation SET protected_restart = @p, renewed_at = @r", cancellationToken, ("p", true), ("r", clock.UtcNow)).ConfigureAwait(false);
- await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false);
+ await DisarmAsync(s, clock, before, cancellationToken).ConfigureAwait(false);
+ await Trading.Diary.NotifyAsync(s, clock, "protected_restart", message, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
}
///
/// SPEC 15.1: "Ferma tutto" on, every strategy with real money in exit only until it is confirmed again, and no
- /// order planned before the restore still waiting to leave (it may already have left, after the archive).
+ /// order planned before the restore still waiting to leave (it may already have left, after the archive). The same
+ /// for the protective sales of the archive: what still needs one is decided again on the rebuilt position.
///
- private static async Task DisarmAsync(DbSession s, IClock clock, CancellationToken cancellationToken)
+ private static async Task DisarmAsync(DbSession s, IClock clock, DateTimeOffset? before, CancellationToken cancellationToken)
{
var now = clock.UtcNow;
var key = Core.SettingsStore.BotState.Key;
@@ -237,9 +240,18 @@ public static class Installation
await s.ExecuteAsync("UPDATE planned_orders SET status = @d, outcome = @o, updated_at = @t WHERE status = @p", cancellationToken,
("d", Trading.PlannedStates.Dropped), ("o", ProtectedRestartReason), ("t", now), ("p", Trading.PlannedStates.Pending)).ConfigureAwait(false);
+ var until = before ?? DateTimeOffset.MaxValue;
+ foreach (var sale in (await s.QueryAsync("SELECT e.id, e.started_at FROM executions e JOIN accounts a ON a.id = e.account_id WHERE e.status = @w AND e.purpose = 'protective' AND a.environment <> @sim",
+ r => (Id: r.Id("id"), Started: r.Moment("started_at")), ("w", Trading.ExecutionStates.Working), ("sim", Trading.TradingEnvironments.Simulation)).ConfigureAwait(false))
+ .Where(e => e.Started < until))
+ {
+ await s.ExecuteAsync("UPDATE executions SET status = @c, reason = @r, finished_at = @t, updated_at = @t WHERE id = @id", cancellationToken,
+ ("c", Trading.ExecutionStates.Canceled), ("r", ProtectedRestartReason), ("t", now), ("id", sale.Id)).ConfigureAwait(false);
+ }
+
// A "close all positions" of before the restore may be done already: going on with it would sell what came after.
var bot = await s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Json("state").Text, ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false);
- if (bot is not null && JsonSerializer.Deserialize(bot, Trading.RiskEngine.Json) is { CloseAll: true })
+ if (bot is not null && JsonSerializer.Deserialize(bot, Trading.RiskEngine.Json) is { CloseAll: true } pending && !(pending.CloseAllSince >= until))
{
await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken,
("j", new DbJson(JsonSerializer.Serialize(new Trading.BotRiskState(), Trading.RiskEngine.Json))), ("t", now), ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false);
diff --git a/src/Anubis/Supervision/GuardRepair.cs b/src/Anubis/Supervision/GuardRepair.cs
index c0ed4f6..41676ea 100644
--- a/src/Anubis/Supervision/GuardRepair.cs
+++ b/src/Anubis/Supervision/GuardRepair.cs
@@ -49,8 +49,9 @@ public static class GuardRepair
}
// 2. What the bot holds now: the state's quantity plus the fills of its own orders since then, never more than the account has.
- var fills = (await broker.GetFillsAsync(state.WrittenAt, cancellationToken).ConfigureAwait(false))
- .Where(f => f.ExecutedAt > state.WrittenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList();
+ var writtenAt = account.WrittenAt ?? state.WrittenAt;
+ var fills = (await broker.GetFillsAsync(writtenAt, cancellationToken).ConfigureAwait(false))
+ .Where(f => f.ExecutedAt > writtenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList();
var positions = await broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false);
var stops = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false))
.Where(o => o.IsOpen && o.Side == OrderSide.Sell && ClientOrderIds.Parse(o.ClientOrderId) is { Purpose: OrderPurpose.Stop } parts && parts.Installation == state.Installation)
diff --git a/src/Anubis/Supervision/GuardState.cs b/src/Anubis/Supervision/GuardState.cs
index 6ecf457..50daab1 100644
--- a/src/Anubis/Supervision/GuardState.cs
+++ b/src/Anubis/Supervision/GuardState.cs
@@ -11,7 +11,11 @@ namespace Anubis.Supervision;
public sealed record GuardState(DateTimeOffset WrittenAt, string Installation, IReadOnlyList Accounts);
public sealed record GuardAccount(Guid AccountId, string Name, string Broker, string Environment, bool FractionalStopsAreDayOnly,
- IReadOnlyList Positions, IReadOnlyList Orders);
+ IReadOnlyList Positions, IReadOnlyList Orders)
+{
+ /// When these figures were read, if earlier than the file: an account whose ledger is not up to date yet keeps those of before.
+ public DateTimeOffset? WrittenAt { get; init; }
+}
///
/// A position of a strategy: quantity, stop level already on the tick, lot, and what the guard needs to name a stop
diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs
index 8422c58..a21ea31 100644
--- a/src/Anubis/Trading/Ledger.cs
+++ b/src/Anubis/Trading/Ledger.cs
@@ -428,9 +428,9 @@ public sealed class Ledger(Database db, IClock clock)
}, cancellationToken);
/// Writes the latest price of an instrument on the positions that hold it, for their value.
- public Task MarkAsync(Guid instrumentId, decimal price, CancellationToken cancellationToken) =>
- db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE instrument_id = @i", cancellationToken,
- ("p", price), ("now", clock.UtcNow), ("i", instrumentId)), cancellationToken);
+ public Task MarkAsync(Guid accountId, Guid instrumentId, decimal price, CancellationToken cancellationToken) =>
+ db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i", cancellationToken,
+ ("p", price), ("now", clock.UtcNow), ("a", accountId), ("i", instrumentId)), cancellationToken);
/// Sets the protective level shown with a position.
public Task SetStopAsync(Guid accountId, Guid instrumentId, string strategy, decimal? stop, CancellationToken cancellationToken) =>
diff --git a/src/Anubis/Trading/OrderManager.Rebuild.cs b/src/Anubis/Trading/OrderManager.Rebuild.cs
index c566db1..4e3d3a2 100644
--- a/src/Anubis/Trading/OrderManager.Rebuild.cs
+++ b/src/Anubis/Trading/OrderManager.Rebuild.cs
@@ -86,12 +86,30 @@ public sealed partial class OrderManager
}
}
- var onlyStops = written == 0 && unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0);
- if (protect is not null && (unclear.Count > 0 || (unknown.Count > 0 && !onlyStops)))
+ var recordedBefore = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT execution_id FROM fills WHERE account_id = @a", r => r.Text("execution_id"),
+ ("a", _account.AccountId)).ConfigureAwait(false)).ToHashSet(StringComparer.Ordinal), cancellationToken).ConfigureAwait(false);
+ if (RefreshSplits is not null && (begun is not null || unknown.Count > 0 || fills.Any(f => !recordedBefore.Contains(f.ExecutionId))))
+ {
+ var symbols = fills.Select(f => f.Symbol).Concat(open.Select(o => o.Symbol)).ToHashSet(StringComparer.Ordinal);
+ await RefreshSplits(symbols, DateOnly.FromDateTime(since.UtcDateTime), cancellationToken).ConfigureAwait(false);
+ }
+
+ // What an interrupted attempt wrote does not count here: if it had to, it protected before its first row.
+ var onlyStops = unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0);
+ if (protect is not null && (unclear.Count > 0 || !onlyStops))
{
await protect(cancellationToken).ConfigureAwait(false);
}
+ foreach (var row in await HalfWrittenAsync(cancellationToken).ConfigureAwait(false))
+ {
+ // Cut between the row and its state: the broker is asked again.
+ var symbol = (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!.Symbol;
+ var own = fills.Where(f => f.ClientOrderId == row.ClientOrderId).ToList();
+ var remote = open.FirstOrDefault(o => o.ClientOrderId == row.ClientOrderId) ?? await _broker.GetOrderAsync(row.ClientOrderId, symbol, cancellationToken).ConfigureAwait(false);
+ await SettleRebuiltAsync(row, symbol, remote, own, cancellationToken).ConfigureAwait(false);
+ }
+
foreach (var (clientId, parts, instrumentId, own, resting) in unknown)
{
var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol;
@@ -107,42 +125,89 @@ public sealed partial class OrderManager
written++;
}
- if (written > 0)
+ // The same for one the database knows of an execution that is over: the restore ended the archive's protective sales.
+ foreach (var resting in open.Where(o => ClientOrderIds.Parse(o.ClientOrderId)!.Purpose != OrderPurpose.Stop))
{
- var recorded = await SyncFillsFromAsync(since, cancellationToken, replay: true).ConfigureAwait(false);
- var positions = await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false);
- foreach (var instrumentId in positions.Select(p => p.InstrumentId).Distinct())
+ if (await OrderByClientIdAsync(resting.ClientOrderId, cancellationToken).ConfigureAwait(false) is { ExecutionId: { } execution } row
+ && await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE id = @id AND status = @w", ("id", execution), ("w", ExecutionStates.Working)), cancellationToken)
+ .ConfigureAwait(false) == 0)
{
- await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false);
+ await CancelAndReadAsync(row, (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))!, "execution_over", cancellationToken).ConfigureAwait(false);
}
-
- await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false);
- foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null))
- {
- var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?";
- unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire.");
- }
-
- var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." +
- (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since);
- await _db.WriteAsync(async s =>
- {
- await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken,
- ("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false);
- await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false);
- }, cancellationToken).ConfigureAwait(false);
- return new RebuildReport(written, recorded, unclear, onlyStops);
}
- if (unclear.Count > 0)
+ // Also when every order was known: the executions of while the bot was off meet the splits of their time, and
+ // only then a split or a dividend of today finds the quantities it needs.
+ var replay = new Replay(Quiet: written > 0);
+ var recorded = await SyncFillsFromAsync(since, cancellationToken, replay).ConfigureAwait(false);
+ if (written == 0)
{
- await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken)
- .ConfigureAwait(false);
+ await SellRestOfStopsAsync(replay, cancellationToken).ConfigureAwait(false);
+ if (recorded > 0 && AfterFills is not null)
+ {
+ await AfterFills(cancellationToken).ConfigureAwait(false);
+ }
+
+ if (unclear.Count > 0)
+ {
+ await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ return new RebuildReport(0, recorded, unclear);
}
- return new RebuildReport(0, 0, unclear);
+ foreach (var instrumentId in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct())
+ {
+ await ReplaySplitsAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false);
+ }
+
+ await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false);
+ foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null))
+ {
+ var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?";
+ unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire.");
+ }
+
+ unclear.AddRange(replay.Refused.DistinctBy(f => f.ExecutionId).Select(f =>
+ $"{f.Symbol}: {(f.Side == OrderSide.Buy ? "un acquisto" : "una vendita")} di {Format.Quantity(f.Quantity)} non torna con il registro, controlla la posizione prima di ripartire."));
+ if (AfterFills is not null)
+ {
+ await AfterFills(cancellationToken).ConfigureAwait(false);
+ }
+
+ var message = $"Conto {_account.Name}: sul conto c'erano {written} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." +
+ (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since);
+ await _db.WriteAsync(async s =>
+ {
+ await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken,
+ ("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false);
+ await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false);
+ }, cancellationToken).ConfigureAwait(false);
+ return new RebuildReport(written, recorded, unclear, onlyStops && written == unknown.Count);
}
+ ///
+ /// A stop of while the bot was off that fired only in part, or one of Alpaca's two: the rest is sold at once (SPEC 7.2).
+ /// Only where the stop is the last thing that happened to the position.
+ ///
+ private async Task SellRestOfStopsAsync(Replay replay, CancellationToken cancellationToken)
+ {
+ foreach (var ((instrumentId, strategy), _) in replay.Last.Where(l => l.Value == OrderPurpose.Stop))
+ {
+ if (await _ledger.PositionAsync(_account.AccountId, instrumentId, strategy, cancellationToken).ConfigureAwait(false) is { Quantity: > 0m } rest)
+ {
+ await ProtectiveSaleAsync(instrumentId, strategy, rest.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private Task> HalfWrittenAsync(CancellationToken cancellationToken) =>
+ _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status = 'created' AND reason = @r", ReadOrder, ("a", _account.AccountId), ("r", RebuiltReason)),
+ cancellationToken);
+
+ private const string RebuiltReason = "rebuilt from the broker";
+
/// The splits with an ex-date up to , in the ledger only: each is applied once.
private async Task ReplaySplitsAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken)
{
@@ -157,7 +222,7 @@ public sealed partial class OrderManager
? []
: [.. (await Splits(instrument, cancellationToken).ConfigureAwait(false)).Where(s => s.ChangesShares && ExDate(s) <= until).OrderBy(s => s.ExDate).Select(s => (instrument, s))];
- private static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
+ internal static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
private string Beyond(DateTimeOffset since) => _broker.FillHistory is { } reach && since < _clock.UtcNow - reach
? $" Il broker racconta solo gli ultimi {reach.Days} giorni: quello che è successo prima va confrontato a mano."
@@ -207,8 +272,8 @@ public sealed partial class OrderManager
await s.ExecuteAsync("UPDATE account_status SET rebuild_since = @since, rebuild_orders = COALESCE(rebuild_orders, 0) + 1, updated_at = @now WHERE account_id = @a",
cancellationToken, ("since", since), ("now", now), ("a", _account.AccountId)).ConfigureAwait(false);
await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false);
- await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = 'rebuilt from the broker' WHERE id = @id", cancellationToken,
- ("b", remote?.BrokerOrderId), ("at", created), ("id", row.Id)).ConfigureAwait(false);
+ await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = @r WHERE id = @id", cancellationToken,
+ ("b", remote?.BrokerOrderId), ("at", created), ("r", RebuiltReason), ("id", row.Id)).ConfigureAwait(false);
if (_account.Environment == TradingEnvironments.Live)
{
// The archive may be older than the promotion: what the bot holds on the real account gets its stops and
@@ -217,11 +282,18 @@ public sealed partial class OrderManager
("a", _account.AccountId), ("x", true), ("now", now), ("s", parts.Strategy)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
- remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt)
+ await SettleRebuiltAsync(row, remote?.Symbol ?? own[0].Symbol, remote, own, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The state of a rebuilt order: the broker's, or what its executions say when the broker forgot it.
+ private Task SettleRebuiltAsync(OrderRow row, string symbol, BrokerOrder? remote, List own, CancellationToken cancellationToken)
+ {
+ var filled = own.Sum(f => f.Quantity);
+ return ApplyRemoteAsync(row, remote ?? new BrokerOrder(row.ClientOrderId, null, symbol, row.Side, row.Kind, row.Quantity,
+ filled > 0m ? OrderStatus.Filled : OrderStatus.Canceled, filled, own.Count > 0 ? own[^1].ExecutedAt : _clock.UtcNow)
{
- AverageFillPrice = DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled),
- };
- await ApplyRemoteAsync(row, remote, "rebuilt from the broker", cancellationToken).ConfigureAwait(false);
+ AverageFillPrice = filled > 0m ? DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled) : null,
+ }, RebuiltReason, cancellationToken);
}
///
diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs
index d1e9b23..b3d3afc 100644
--- a/src/Anubis/Trading/OrderManager.cs
+++ b/src/Anubis/Trading/OrderManager.cs
@@ -141,6 +141,12 @@ public sealed partial class OrderManager : IDisposable
///
public bool AwaitingRebuild { get; set; }
+ ///
+ /// Asks the splits of these symbols since a day again, before executions of the past are written: without them a
+ /// sale of new shares would be refused. A failure leaves the account waiting (SPEC 15.1).
+ ///
+ public Func, DateOnly, CancellationToken, Task>? RefreshSplits { get; init; }
+
/// Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5).
public Func? AfterFills { get; init; }
@@ -408,6 +414,12 @@ public sealed partial class OrderManager : IDisposable
await CancelAndReadAsync(current, instrument, reason, cancellationToken).ConfigureAwait(false);
}
+ if (AwaitingRebuild)
+ {
+ // Its executions cannot be read yet: the startup ends it after the rebuild, with the stop of what was bought.
+ continue;
+ }
+
await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false);
await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false);
canceled.Add(exec.Id);
@@ -752,7 +764,7 @@ public sealed partial class OrderManager : IDisposable
/// With the executions are history (SPEC 15.1): they are written with the splits of their
/// time, and nothing is done about them. What to do today is decided afterwards, on the position that results.
///
- private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, bool replay = false)
+ private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, Replay? replay = null)
{
var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false);
var recorded = 0;
@@ -769,7 +781,7 @@ public sealed partial class OrderManager : IDisposable
continue;
}
- if (replay)
+ if (replay is not null)
{
await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false);
}
@@ -789,6 +801,7 @@ public sealed partial class OrderManager : IDisposable
{
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_refused_fill",
$"Un'esecuzione su {_account.Name} non torna con il mio registro: la controllo nella riconciliazione. ({ex.Message})", cancellationToken), cancellationToken).ConfigureAwait(false);
+ replay?.Refused.Add(fill);
continue;
}
@@ -798,6 +811,11 @@ public sealed partial class OrderManager : IDisposable
}
recorded++;
+ if (replay is not null)
+ {
+ replay.Last[(row.InstrumentId, row.Strategy)] = row.Purpose;
+ }
+
var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(async s =>
{
@@ -818,20 +836,20 @@ public sealed partial class OrderManager : IDisposable
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false);
- if (!replay)
+ if (replay is null or { Quiet: false })
{
// Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14).
await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
- if (!replay && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
+ if (replay is null && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
{
// A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2).
await ProtectiveSaleAsync(row.InstrumentId, row.Strategy, outcome.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false);
}
}
- if (recorded > 0 && AfterFills is not null)
+ if (replay is null && recorded > 0 && AfterFills is not null)
{
await AfterFills(cancellationToken).ConfigureAwait(false);
}
@@ -839,6 +857,17 @@ public sealed partial class OrderManager : IDisposable
return recorded;
}
+ ///
+ /// A reading of the past: what the ledger refused, and the purpose of the last execution recorded of each position.
+ /// Quiet when the executions are those of after an archive, days old: they do not reach the phone as new.
+ ///
+ private sealed record Replay(bool Quiet)
+ {
+ public List Refused { get; } = [];
+
+ public Dictionary<(Guid Instrument, string Strategy), OrderPurpose> Last { get; } = [];
+ }
+
private async Task RefreshOpenOrdersAsync(CancellationToken cancellationToken)
{
var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)),
diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs
index 22f175c..dfc7aed 100644
--- a/src/Anubis/Trading/PaperBroker.cs
+++ b/src/Anubis/Trading/PaperBroker.cs
@@ -446,13 +446,20 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
///
/// After an absence (SPEC 7.3): waiting purchases are cancelled; stops and sales that would have triggered are
/// filled at their level, or at the open of the bar that already passed it. Bars come from the one-minute store.
+ /// With only the stretch before it, the rest at the next call.
///
- public async Task CatchUpAsync(Func>> minuteBars, CancellationToken cancellationToken)
+ public async Task CatchUpAsync(Func>> minuteBars, CancellationToken cancellationToken,
+ DateTimeOffset? to = null)
{
ArgumentNullException.ThrowIfNull(minuteBars);
var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false);
var from = book.SeenUntil;
- var until = _clock.UtcNow;
+ var until = to ?? _clock.UtcNow;
+ if (until < from)
+ {
+ return 0;
+ }
+
var bars = new Dictionary>(StringComparer.Ordinal);
foreach (var symbol in book.Orders.Where(o => IsOpen(o) && o.Request.Side == OrderSide.Sell).Select(o => o.Request.Symbol).Distinct(StringComparer.Ordinal))
{
diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs
index b640d39..4bda061 100644
--- a/src/Anubis/Trading/TradingService.cs
+++ b/src/Anubis/Trading/TradingService.cs
@@ -172,6 +172,7 @@ public sealed partial class TradingService : IDisposable
{
_db = db ?? throw new ArgumentNullException(nameof(db));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ _since = clock.UtcNow;
_bus = bus ?? throw new ArgumentNullException(nameof(bus));
_secrets = secrets ?? throw new ArgumentNullException(nameof(secrets));
_market = market;
@@ -362,6 +363,7 @@ public sealed partial class TradingService : IDisposable
MarketOpen = MarketOpenAsync,
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
Splits = SplitsAsync,
+ RefreshSplits = _market is null || account.Broker != Venues.Alpaca ? null : (symbols, since, ct) => _market.RefreshCorporateActionsAsync(symbols, since, ct),
AwaitingRebuild = account.Environment != TradingEnvironments.Simulation,
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
Gate = Risk is null ? null : Risk.GateAsync,
@@ -411,9 +413,20 @@ public sealed partial class TradingService : IDisposable
}
var accounts = new List();
+ GuardState? before = null;
foreach (var manager in _managers.Values)
{
- accounts.Add(await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false));
+ var account = await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false);
+ if (manager.AwaitingRebuild)
+ {
+ // Its ledger may be older than the account: the guard keeps what the last state said, at its time, or nothing.
+ before ??= Supervision.GuardFiles.ReadState(GuardFiles);
+ account = before is not null && before.Installation == InstallationCode && before.Accounts.FirstOrDefault(a => a.AccountId == account.AccountId) is { } known
+ ? known with { WrittenAt = known.WrittenAt ?? before.WrittenAt }
+ : account with { Positions = [] };
+ }
+
+ accounts.Add(account);
}
Supervision.GuardFiles.WriteState(GuardFiles, new GuardState(_clock.UtcNow, InstallationCode, accounts));
@@ -443,19 +456,18 @@ public sealed partial class TradingService : IDisposable
{
if (manager.Broker is PaperBroker paper)
{
- await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
- await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
+ await CatchUpAsync(manager, paper, cancellationToken).ConfigureAwait(false);
}
else
{
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("esecuzioni dal broker " + name);
await RebuildAsync(manager, cancellationToken).ConfigureAwait(false);
-
- // After the rebuild: a split or a dividend needs the quantities held at its date (SPEC 15.1).
- await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
}
+ // After the executions of meanwhile: a split or a dividend needs the quantities held at its date (SPEC 15.1).
+ await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
+
Guard?.Step("riconciliazione " + name);
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("ordini rimasti aperti " + name);
@@ -469,33 +481,84 @@ public sealed partial class TradingService : IDisposable
}
}
+ /// The simulator's absence (SPEC 7.3), one stretch per split: the orders of before it meet the prices of before it.
+ internal async Task CatchUpAsync(OrderManager manager, PaperBroker paper, CancellationToken cancellationToken)
+ {
+ var splits = new List<(Instrument Instrument, CorporateAction Split)>();
+ foreach (var id in (await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct())
+ {
+ if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { IsCrypto: false } instrument)
+ {
+ continue;
+ }
+
+ foreach (var split in await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false))
+ {
+ if (!await AppliedAsync(manager.Account.AccountId, split.SourceKey, cancellationToken).ConfigureAwait(false))
+ {
+ splits.Add((instrument, split));
+ }
+ }
+ }
+
+ foreach (var (instrument, split) in splits.OrderBy(s => s.Split.ExDate))
+ {
+ await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken, OrderManager.ExDate(split)).ConfigureAwait(false);
+ await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false);
+ await manager.ApplySplitAsync(instrument, split, cancellationToken).ConfigureAwait(false);
+ }
+
+ await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
+ await manager.SyncFillsAsync(cancellationToken).ConfigureAwait(false);
+ }
+
///
/// SPEC 15.1: what the account did after the archive is written back before anything compares ledger and account.
/// Finding something on a database nobody declared restored means it is an old copy put back by hand, or a dump:
/// the protected restart starts here, as it would have after an import.
///
- internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) =>
- manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct));
+ internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken)
+ {
+ var protectedNow = false;
+ try
+ {
+ await manager.RebuildAsync(cancellationToken, async ct =>
+ {
+ await ProtectAsync(manager, ct).ConfigureAwait(false);
+ protectedNow = true;
+ }).ConfigureAwait(false);
+ }
+ finally
+ {
+ // "Ferma tutto" also where the other accounts are already at work.
+ foreach (var other in _managers.Values.Where(m => protectedNow && m != manager && AccountReady(m.Account.AccountId)))
+ {
+ await GuardAsync("ordini " + other.Account.Name, () => other.CancelWorkingAsync(Platform.Installation.ProtectedRestartReason, cancellationToken: cancellationToken),
+ cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ // What was asked or begun before this moment may be of an old copy of the database; what comes after is of now.
+ private readonly DateTimeOffset _since;
private async Task ProtectAsync(OrderManager manager, CancellationToken cancellationToken)
{
- if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true }
- && await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken)
- .ConfigureAwait(false) == "\"stopped\"")
+ if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true }
+ || await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken)
+ .ConfigureAwait(false) != "\"stopped\"")
{
- return;
+ await Platform.Installation.ProtectAsync(_db, _clock, _since,
+ $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.",
+ cancellationToken).ConfigureAwait(false);
}
- await Platform.Installation.ProtectAsync(_db, _clock, cancellationToken).ConfigureAwait(false);
+ // Also when an attempt cut right after the write had already protected: the names of the stops depend on it.
var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false);
- foreach (var each in _managers.Values)
+ foreach (var each in _managers.Values.Append(manager))
{
each.StopGeneration = generation;
}
-
- await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "protected_restart",
- $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.",
- cancellationToken), cancellationToken).ConfigureAwait(false);
}
/// Zero until the first restore, then the moment of the last one.
@@ -807,21 +870,32 @@ public sealed partial class TradingService : IDisposable
///
public async Task MarkPositionsAsync(CancellationToken cancellationToken)
{
- var held = (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct().ToList();
- foreach (var id in held)
+ foreach (var held in (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).GroupBy(p => p.InstrumentId))
{
- if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } instrument)
+ if (await _catalog.GetAsync(held.Key, cancellationToken).ConfigureAwait(false) is not { } instrument
+ || await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is not { Bid: > 0m, Ask: > 0m } quote || quote.Ask < quote.Bid)
{
continue;
}
- if (await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote && quote.Ask >= quote.Bid)
+ foreach (var account in held.GroupBy(p => p.AccountId))
{
- await Ledger.MarkAsync(id, quote.Mid, cancellationToken).ConfigureAwait(false);
+ if (!await SharesOfAnotherTimeAsync(account.Key, instrument, account.Min(p => p.OpenedAt), cancellationToken).ConfigureAwait(false))
+ {
+ await Ledger.MarkAsync(account.Key, held.Key, quote.Mid, cancellationToken).ConfigureAwait(false);
+ }
}
}
}
+ ///
+ /// The quantity in the ledger is not the one today's price is about: an account not rebuilt yet, or a split still to be
+ /// applied. Valued all the same it would show a loss that is not there, and the limits of SPEC 9.2 would act on it.
+ ///
+ private async Task SharesOfAnotherTimeAsync(Guid accountId, Instrument instrument, DateTimeOffset openedAt, CancellationToken cancellationToken) =>
+ _managers.TryGetValue(accountId, out var manager) && (manager.AwaitingRebuild || (!instrument.IsCrypto
+ && await PendingSplitAsync(accountId, instrument, cancellationToken).ConfigureAwait(false) is { } split && openedAt < OrderManager.ExDate(split)));
+
public async Task TickAllAsync(CancellationToken cancellationToken)
{
await RetryAccountsAsync(cancellationToken).ConfigureAwait(false);
@@ -891,7 +965,7 @@ public sealed partial class TradingService : IDisposable
}
}
- private async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken)
+ internal async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken)
{
if (manager.Account.Broker != Venues.Alpaca)
{
@@ -912,21 +986,28 @@ public sealed partial class TradingService : IDisposable
// What was sold since still owes the dividends of when it was held: a rebuild or a long stop brings them late.
var traded = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT instrument_id FROM fills WHERE account_id = @a AND executed_at >= @at", r => r.Id("instrument_id"),
- ("a", manager.Account.AccountId), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false);
- var held = new Dictionary(StringComparer.Ordinal);
+ ("a", manager.Account.AccountId), ("at", _clock.UtcNow - MarketDataService.SoldStillOwed)), cancellationToken).ConfigureAwait(false);
+ var owed = new Dictionary(StringComparer.Ordinal);
foreach (var id in positions.Select(p => p.InstrumentId).Concat(traded).Distinct())
{
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument)
{
- held[instrument.Symbol] = instrument;
+ owed[instrument.Symbol] = instrument;
}
}
- foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol)))
+ var held = positions.Select(p => p.InstrumentId).ToHashSet();
+ foreach (var action in actions.Where(a => owed.ContainsKey(a.Symbol)))
{
- var instrument = held[action.Symbol];
+ var instrument = owed[action.Symbol];
if (action.ChangesShares)
{
+ // Only where something is held: a purchase not read yet must still find its split.
+ if (!held.Contains(instrument.Id))
+ {
+ continue;
+ }
+
// The ledger and, on the simulator, the broker's book, together and once.
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false);
}
@@ -937,8 +1018,6 @@ public sealed partial class TradingService : IDisposable
}
}
- private static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90);
-
private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken)
{
var key = "div:" + action.SourceKey;
diff --git a/tests/Anubis.Tests/FormatTests.cs b/tests/Anubis.Tests/FormatTests.cs
index 2ae347c..acb3c02 100644
--- a/tests/Anubis.Tests/FormatTests.cs
+++ b/tests/Anubis.Tests/FormatTests.cs
@@ -92,6 +92,8 @@ public sealed class FormatTests
Assert.AreEqual("mer 31 dic 2025", Format.ShortDate(new DateTimeOffset(2025, 12, 31, 10, 0, 0, TimeSpan.Zero), now, _rome));
Assert.AreEqual("Venerdì 9 ottobre 2026, ore 08:21", Format.LongDateTime(now, _rome));
Assert.AreEqual("12 agosto 2026", Format.LongDate(new DateOnly(2026, 8, 12)));
+ Assert.AreEqual("12 ago", Format.AxisDay(new DateOnly(2026, 8, 12), 58));
+ Assert.AreEqual("ago 2026", Format.AxisDay(new DateOnly(2026, 8, 12), 900));
Assert.AreEqual("4 secondi fa", Format.Ago(TimeSpan.FromSeconds(4)));
Assert.AreEqual("1 minuto fa", Format.Ago(TimeSpan.FromSeconds(65)));
}
diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs
index 975543c..874fe1f 100644
--- a/tests/Anubis.Tests/LedgerTests.cs
+++ b/tests/Anubis.Tests/LedgerTests.cs
@@ -180,7 +180,7 @@ public sealed class LedgerTests
.ConfigureAwait(false);
}
- await rig.Ledger.MarkAsync(instrument.Id, price, _none).ConfigureAwait(false);
+ await rig.Ledger.MarkAsync(account.AccountId, instrument.Id, price, _none).ConfigureAwait(false);
await AssertBooksAsync(rig, account, strategy, step).ConfigureAwait(false);
}
}
@@ -363,7 +363,7 @@ public sealed class LedgerTests
// A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain.
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, StrategyNames.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false);
- await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false);
+ await rig.Ledger.MarkAsync(okx.AccountId, btc.Id, 68000m, _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMinutes(5));
await book.TakeAsync(_none).ConfigureAwait(false);
await capital.SetAsync(Venues.Okx, 8000m, "test", _none).ConfigureAwait(false);
diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs
index a8de6d2..e42be0c 100644
--- a/tests/Anubis.Tests/LiveStockSupport.cs
+++ b/tests/Anubis.Tests/LiveStockSupport.cs
@@ -209,7 +209,7 @@ internal sealed class StockRig : IAsyncDisposable
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 Rig.Ledger.MarkAsync(Alpaca.AccountId, _instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false);
}
await Equity.TakeAsync(none).ConfigureAwait(false);
diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs
index 054c295..6bac5df 100644
--- a/tests/Anubis.Tests/LiveSupport.cs
+++ b/tests/Anubis.Tests/LiveSupport.cs
@@ -239,7 +239,7 @@ internal sealed class LiveRig : IAsyncDisposable
foreach (var coin in Coins)
{
- await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false);
+ await Rig.Ledger.MarkAsync(Okx.AccountId, _instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false);
}
await Equity.TakeAsync(none).ConfigureAwait(false);
diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs
index 9849940..c850e1e 100644
--- a/tests/Anubis.Tests/RestoreServerTests.cs
+++ b/tests/Anubis.Tests/RestoreServerTests.cs
@@ -113,6 +113,28 @@ public sealed class RestoreServerTests
}
Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself.");
+
+ // The true file comes back while a choice is at work, and the choice fails: it is not taken away.
+ using (await server.Host.ExclusiveAsync(CancellationToken.None))
+ {
+ var db = server.Host.OpenForChoice();
+ File.Copy(away, file);
+ Assert.IsFalse((await Migrations.StatusAsync(db, CancellationToken.None)).IsEmpty);
+ await server.Host.AbandonChoiceAsync();
+ Assert.IsTrue(File.Exists(file), "The file that came back stays in its place.");
+ Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
+ foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
+ {
+ File.Delete(f);
+ }
+
+ // What a choice began to write is another thing: it steps aside.
+ await Migrations.MigrateAsync(server.Host.OpenForChoice(), SystemClock.Instance, null, CancellationToken.None);
+ await server.Host.AbandonChoiceAsync();
+ Assert.IsFalse(File.Exists(file));
+ Assert.HasCount(1, Directory.GetFiles(Path.GetDirectoryName(file)!, "*.incompleto-*").Where(f => !f.EndsWith("-wal", StringComparison.Ordinal) && !f.EndsWith("-shm", StringComparison.Ordinal)).ToList());
+ }
+
File.Copy(away, file);
await server.WaitForAsync(HostMode.Ready);
}
diff --git a/tests/Anubis.Tests/RestoreTests.cs b/tests/Anubis.Tests/RestoreTests.cs
index a447fdb..e14b003 100644
--- a/tests/Anubis.Tests/RestoreTests.cs
+++ b/tests/Anubis.Tests/RestoreTests.cs
@@ -325,6 +325,9 @@ public sealed class RestoreTests
Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE reason = 'rebuilt from the broker'", r => r.Id("id")), "Interrupted after the orders.");
Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value, "The protection comes before the first row.");
+ // One of them was cut right after its row: it still has no state.
+ await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET status = 'created', filled_quantity = 0 WHERE reason = 'rebuilt from the broker' AND purpose <> 'stop'", _none), _none);
+
// The last execution made it into the ledger: what comes before it is still to be read.
var last = (await a.Paper.GetFillsAsync(DateTimeOffset.MinValue, _none)).MaxBy(f => f.ExecutedAt)!;
await rig.Ledger.RecordFillAsync(new LedgerFill(a.Context.AccountId, a.Eth.Id, StrategyNames.CryptoTrend, last.ExecutionId, last.Side, last.Quantity, last.Price, last.Fee,
@@ -333,6 +336,7 @@ public sealed class RestoreTests
// The next attempt knows every order already, and finishes all the same.
await service.RebuildAsync(manager, _none);
await a.SameLedgerAsync(rig, "The ledger is the one that was lost, stops included.");
+ Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE status = 'created'", r => r.Id("id")), "Every rebuilt order has the state the broker says.");
await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none);
await manager.AlignStopsAsync(_none);
CollectionAssert.AreEqual(stops, (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList(), "No stop was touched.");
@@ -474,14 +478,31 @@ public sealed class RestoreTests
await using var restored = await rig.RestoreAsync(archive);
await Installation.RenewAsync(restored.Db, new DataDirectory(Path.Combine(folder, "data")), restored.Clock, "Salvataggio ripristinato", _none);
- var again = restored.Manager(broker, context, splits: SplitsAsync);
+ var asked = new List<(string Symbols, DateOnly Since)>();
+ var photographs = new List();
+ var down = true;
+ var again = restored.Manager(broker, context, splits: async (i, ct) => down ? [] : await SplitsAsync(i, ct), refreshSplits: (symbols, since, _) =>
+ {
+ asked.Add((string.Join(',', symbols), since));
+ return down ? throw new MarketDataException("rete giù") : Task.CompletedTask;
+ }, afterFills: async ct => photographs.Add((await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, ct))!.Quantity));
+ again.AwaitingRebuild = true;
again.StopGeneration = restored.Clock.UtcNow.UtcTicks;
+ var known = await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id"));
+ await Assert.ThrowsExactlyAsync(() => again.RebuildAsync(_none));
+ Assert.IsTrue(again.AwaitingRebuild, "Without the splits nothing is replayed.");
+ Assert.HasCount(known.Count, await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id")));
+ down = false;
var report = await again.RebuildAsync(_none);
+ Assert.AreEqual(2, asked.Count(a => a == ("MSFT", new DateOnly(2026, 11, 9))), "Back to a day before the last execution of the archive.");
+ CollectionAssert.AreEqual(new[] { 22m }, photographs, "One photograph, when every split is in its place.");
Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear));
var position = (await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!;
Assert.AreEqual((22m, 180m), (position.Quantity, position.StopPrice));
Assert.IsEmpty(await restored.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_refused_fill'", r => r.Text("message")));
Assert.HasCount(1, await restored.QueryAsync("SELECT id FROM applied_actions WHERE source_key = 'split-msft'", r => r.Id("id")));
+ await again.RebuildAsync(_none);
+ Assert.HasCount(2, asked, "Nothing new to write: no need to ask.");
var reconciled = await new Reconciler(restored.Db, restored.Clock, restored.Ledger).ReconcileAsync(again, _none);
Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message)));
}
@@ -491,12 +512,261 @@ public sealed class RestoreTests
}
}
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task StoppingAnAccountNotRebuiltYetKeepsTheStopOfAPurchase()
+ {
+ // The purchase filled and the engine died before reading it; "Ferma tutto" comes while the account waits.
+ await using var a = await Account.OpenAsync();
+ a.Rig.Refresh();
+ await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 57_000m, StartAggressive = true }, _none);
+ a.Broker.FailFillsAt = 2;
+ await Assert.ThrowsExactlyAsync(() => a.Manager.TickAsync(_none));
+ a.Rig.Refresh();
+ await a.Paper.PumpAsync(_none);
+
+ var manager = a.Rig.Manager(a.Broker, a.Context);
+ manager.AwaitingRebuild = true;
+ Assert.IsEmpty(await manager.CancelWorkingAsync("manual_stop"));
+ await manager.RebuildAsync(_none);
+ Assert.HasCount(1, await manager.CancelWorkingAsync(LiveReasons.Restart));
+ Assert.AreEqual(57_000m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice);
+ Assert.AreEqual(57_000m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task ExecutionsOfWhileTheBotWasOffComeBeforeTheSplitsAndTheDividends()
+ {
+ await using var rig = await TradingRig.CreateAsync();
+ var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo);
+ var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT"));
+ var nvda = await rig.InstrumentAsync(TradingRig.Stock("NVDA"));
+ var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false);
+ await paper.DepositAsync(100_000m, "USD", _none);
+ await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none);
+ var broker = new FaultyBroker(paper, TradingEnvironments.Demo);
+ using var service = Service(rig);
+ Task> SplitsAsync(Instrument i, CancellationToken ct) => rig.Db.ReadAsync>(async s =>
+ [.. await s.QueryAsync("SELECT source_key FROM corporate_actions WHERE symbol = @s AND kind = 'split'", r => new CorporateAction(i.Symbol, "split", new DateOnly(2026, 11, 12), "test", r.Text("source_key")) { Ratio = 10m }, ("s", i.Symbol))], ct);
+ OrderManager Manager() => rig.Manager(broker, context, splits: SplitsAsync);
+ async Task TurnsAsync(OrderManager manager)
+ {
+ for (var i = 0; i < 3; i++)
+ {
+ rig.Refresh();
+ await paper.PumpAsync(_none);
+ await manager.TickAsync(_none);
+ rig.Clock.Advance(_minute);
+ }
+ }
+
+ Task<(Guid?, string?)> BuyAsync(OrderManager manager, Instrument instrument, decimal quantity) => manager.SubmitAsync(
+ new TradeIntent(instrument.Id, StrategyNames.EquityMomentum, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none);
+
+ // 10 MSFT with their stop; NVDA bought and sold before, then bought again: filled, and the engine dies before reading it.
+ rig.Quote("MSFT", 399.9m, 400m);
+ rig.Quote("NVDA", 399.9m, 400m);
+ var first = Manager();
+ await BuyAsync(first, msft, 10m);
+ await TurnsAsync(first);
+ await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD"), _none);
+ await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD"), _none);
+ rig.Clock.Advance(_minute);
+ await BuyAsync(first, nvda, 10m);
+ broker.FailFillsAt = 2;
+ await Assert.ThrowsExactlyAsync(() => first.TickAsync(_none));
+ rig.Refresh();
+ await paper.PumpAsync(_none);
+
+ // Off: the stop of MSFT fires on Wednesday; Thursday, 10-for-1 for both and a dividend of MSFT.
+ rig.Clock.Advance(TimeSpan.FromDays(1));
+ rig.Quote("MSFT", 350m, 350.1m);
+ await paper.PumpAsync(_none);
+ rig.Clock.Advance(TimeSpan.FromDays(1));
+ rig.Quote("MSFT", 35m, 35.01m);
+ rig.Quote("NVDA", 40m, 40.01m);
+ await rig.Db.WriteAsync(async s =>
+ {
+ foreach (var (symbol, kind, ratio, cash) in new[] { ("MSFT", "split", (decimal?)10m, (decimal?)null), ("NVDA", "split", 10m, null), ("MSFT", "cash_dividend", null, 1m) })
+ {
+ await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, @s, @k, '2026-11-12', @r, @c, 'USD', 'test', @key, @now)",
+ _none, ("id", Ids.NewId(rig.Clock)), ("s", symbol), ("k", kind), ("r", ratio), ("c", cash), ("key", kind + symbol), ("now", rig.Clock.UtcNow));
+ }
+ }, _none);
+
+ var second = Manager();
+ second.AwaitingRebuild = true;
+
+ var report = await second.RebuildAsync(_none);
+ Assert.AreEqual(0, report.Orders);
+ await service.CorporateActionsAsync(second, _none);
+ Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))?.Quantity ?? 0m, "The stop sold the 10 old shares.");
+ Assert.AreEqual(100m, (await rig.Ledger.PositionAsync(context.AccountId, nvda.Id, StrategyNames.EquityMomentum, _none))!.Quantity, "The purchase finds its split.");
+ Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")), "Sold before the ex-date: nothing is owed.");
+ Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id")));
+ Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill' AND message LIKE '%Vend%MSFT%'", r => r.Id("id")), "The sale of the stop reaches the phone.");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task TheRestOfAStopThatFiredInPartWhileOffIsSold()
+ {
+ await using var rig = await TradingRig.CreateAsync();
+ var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo);
+ var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT"));
+ var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false);
+ await paper.DepositAsync(100_000m, "USD", _none);
+ await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none);
+ var broker = new FaultyBroker(paper, TradingEnvironments.Demo);
+ var first = rig.Manager(broker, context);
+ rig.Quote("MSFT", 399.9m, 400m);
+ await first.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 1.5m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none);
+ for (var i = 0; i < 3; i++)
+ {
+ rig.Refresh();
+ await paper.PumpAsync(_none);
+ await first.TickAsync(_none);
+ rig.Clock.Advance(_minute);
+ }
+
+ // The stop of the fraction is a day order and is over; that of the whole share fires while the bot is off.
+ var stops = await paper.GetOpenOrdersAsync(_none);
+ Assert.HasCount(2, stops);
+ await paper.CancelOrderAsync(stops.Single(o => o.Quantity == 0.5m).ClientOrderId, "MSFT", _none);
+ rig.Clock.Advance(TimeSpan.FromHours(1));
+ rig.Quote("MSFT", 350m, 350.1m);
+ await paper.PumpAsync(_none);
+
+ var second = rig.Manager(broker, context);
+ second.AwaitingRebuild = true;
+ await second.RebuildAsync(_none);
+ Assert.AreEqual(0.5m, (await rig.QueryAsync("SELECT quantity FROM executions WHERE purpose = 'protective' AND status = 'working'", r => r.Money("quantity"))).Single());
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task TheProtectiveSalesOfTheArchiveAreNotContinued()
+ {
+ await using var a = await Account.OpenAsync();
+ await a.BuyAsync(a.Btc, 0.01m, 57_000m);
+ await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none);
+ var simulated = await a.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation);
+ await a.Rig.Manager(a.Rig.Paper(PaperOptions.Okx(), simulated.AccountId, persist: false), simulated)
+ .SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none);
+ var (rig, _) = await a.RestoreAsync(await a.ArchiveAsync());
+ async Task StatusAsync(Guid account) => (await rig.QueryAsync("SELECT status FROM executions WHERE account_id = @a AND purpose = 'protective'", r => r.Text("status"), ("a", account))).Single();
+ Assert.AreEqual(ExecutionStates.Canceled, await StatusAsync(a.Context.AccountId));
+ Assert.AreEqual(ExecutionStates.Working, await StatusAsync(simulated.AccountId), "The simulator went back in time with its sales.");
+
+ // One of an execution that is over, still open on the account, is canceled there too.
+ a.Rig.Refresh();
+ await a.Manager.CancelWorkingAsync("prova");
+ await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none);
+ await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.004m, OrderPurpose.Exit, Ids.NewId(a.Rig.Clock)), _none);
+ await a.Manager.TickAsync(_none);
+ Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList());
+ await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none);
+ await a.Rig.Manager(a.Broker, a.Context).RebuildAsync(_none);
+ Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList());
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task ProtectionFromTheLoopStopsTheOtherAccountsAndKeepsWhatIsOfToday()
+ {
+ await using var a = await Account.OpenAsync();
+ await a.BuyAsync(a.Btc, 0.01m, 57_000m);
+ var archive = await a.ArchiveAsync();
+ await a.SellAsync(a.Btc, 0.003m);
+
+ foreach (var (asked, kept) in new[] { ("2026-11-07T10:00:00+00:00", false), ("2026-12-31T10:00:00+00:00", true) })
+ {
+ var rig = await a.Rig.RestoreAsync(archive);
+ a.Restored.Add(rig);
+ await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none);
+ using var service = Service(rig);
+ await service.StartAsync(_none);
+ var simulator = service.Managers.Single(m => m.Account.Broker == Venues.Okx);
+ rig.Clock.Advance(_minute);
+ var (buy, _) = await simulator.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(rig.Clock)), _none);
+ await AskCloseAllAsync(rig, asked);
+ var manager = rig.Manager(a.Broker, a.Context);
+ await service.RebuildAsync(manager, _none);
+ Assert.AreEqual(ExecutionStates.Canceled, (await rig.QueryAsync("SELECT status FROM executions WHERE id = @id", r => r.Text("status"), ("id", buy))).Single());
+ var state = (await rig.QueryAsync("SELECT state FROM risk_state WHERE world = 'bot'", r => r.Json("state").Text)).Single();
+ Assert.AreEqual(kept, System.Text.Json.JsonDocument.Parse(state).RootElement.GetProperty("close_all").GetBoolean(), asked);
+ Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message")));
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task AnAttemptCutRightAfterTheProtectionStillNamesTheStopsAnew()
+ {
+ await using var a = await Account.OpenAsync();
+ await a.BuyAsync(a.Btc, 0.01m, 57_000m);
+ var archive = await a.ArchiveAsync();
+ await a.SellAsync(a.Btc, 0.003m);
+ var rig = await a.Rig.RestoreAsync(archive);
+ a.Restored.Add(rig);
+ await Installation.ProtectAsync(rig.Db, rig.Clock, rig.Clock.UtcNow, "prova", _none);
+ using var service = Service(rig);
+ var manager = rig.Manager(a.Broker, a.Context);
+ await service.RebuildAsync(manager, _none);
+ Assert.AreEqual((await Installation.ReadRowAsync(rig.Db, _none))!.RenewedAt.UtcTicks, manager.StopGeneration);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task AResumedRebuildOfTheGuardsStopsDoesNotStopTheBot()
+ {
+ await using var a = await Account.OpenAsync();
+ await a.BuyAsync(a.Btc, 0.01m, 57_000m);
+ var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single();
+ await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none);
+ Task PlaceAsync(int sequence) => a.Paper.SubmitOrderAsync(new OrderRequest(ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend,
+ OrderPurpose.Stop, "GGGGGGGG", sequence), a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity / 2m, TimeInForce.Gtc)
+ { StopPrice = 57_000m }, _none);
+ using var service = Service(a.Rig);
+ await PlaceAsync(1);
+ a.Broker.FailFillsAt = 2;
+ await Assert.ThrowsExactlyAsync(() => service.RebuildAsync(a.Manager, _none));
+ await PlaceAsync(2);
+ await service.RebuildAsync(a.Manager, _none);
+ Assert.IsFalse((await Installation.ReadRowAsync(a.Rig.Db, _none))!.ProtectedRestart);
+ Assert.IsEmpty(await a.Rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message")));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Simulation)]
+ public async Task TheGuardCountsFromTheMomentTheFiguresOfTheAccountWereRead()
+ {
+ await using var a = await Account.OpenAsync();
+ await a.BuyAsync(a.Btc, 0.01m, 57_000m);
+ var known = await a.Manager.GuardAccountAsync(_none);
+ var read = a.Rig.Clock.UtcNow;
+ a.Rig.Clock.Advance(_minute);
+ await a.SellAsync(a.Btc, 0.004m);
+ var held = (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
+ await a.Paper.SubmitOrderAsync(new OrderRequest("a-mano", a.Btc.Symbol, OrderSide.Buy, OrderKind.Market, 0.5m, TimeInForce.Gtc), _none);
+ await a.TurnsAsync(a.Manager, 2);
+ foreach (var stop in await a.Paper.GetOpenOrdersAsync(_none))
+ {
+ await a.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none);
+ }
+
+ var state = new Anubis.Supervision.GuardState(a.Rig.Clock.UtcNow, TradingRig.Installation, [known with { WrittenAt = read }]);
+ var outcome = await Anubis.Supervision.GuardRepair.RunAsync(state, state.Accounts[0], a.Broker, a.Rig.Clock, _none);
+ Assert.AreEqual(held, outcome.Placed.Single().Quantity, "What was sold after the figures, not what the user holds.");
+ }
+
private static TradingService Service(TradingRig rig) => new(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock),
TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp());
- private static Task AskCloseAllAsync(TradingRig rig) => rig.Db.WriteAsync(s => s.ExecuteAsync(
+ private static Task AskCloseAllAsync(TradingRig rig, string since = "2026-11-07T10:00:00+00:00") => rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'bot', @j, @t, @t)", _none,
- ("id", Ids.NewId(rig.Clock)), ("j", new DbJson("{\"close_all\":true,\"close_all_since\":\"2026-11-07T10:00:00+00:00\"}")), ("t", rig.Clock.UtcNow)), _none);
+ ("id", Ids.NewId(rig.Clock)), ("j", new DbJson($"{{\"close_all\":true,\"close_all_since\":\"{since}\"}}")), ("t", rig.Clock.UtcNow)), _none);
private static async Task CloseAllAsync(TradingRig rig, OrderManager manager)
{
diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs
index 681ec81..ea16025 100644
--- a/tests/Anubis.Tests/RiskEngineTests.cs
+++ b/tests/Anubis.Tests/RiskEngineTests.cs
@@ -503,7 +503,7 @@ public sealed class RiskEngineTests
("id", planned), ("a", live.Account.AccountId), ("i", s.Btc.Id), ("no", false), ("t", s.Rig.Clock.UtcNow)), _none);
await Installation.CheckAsync(s.Rig.Db, new DataDirectory(TempFolder.Create("reconfirm")), s.Rig.Clock, _none);
- await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, _none);
+ await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, s.Rig.Clock.UtcNow, "prova", _none);
// Stopped, exit only, with its counts untouched; what was planned does not leave; the stop stays.
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs
index 5c58158..4cb6901 100644
--- a/tests/Anubis.Tests/TradingServiceTests.cs
+++ b/tests/Anubis.Tests/TradingServiceTests.cs
@@ -92,6 +92,10 @@ public sealed class TradingServiceTests
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, source, source_key, created_at) VALUES (@id, 'MSFT', 'split', '2026-11-11', @r, 'test', 'k', @now)",
_none, ("id", Ids.NewId(rig.Clock)), ("r", 2m), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromDays(2));
+ service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
+ await service.PhotographAsync(_none).ConfigureAwait(false);
+ Assert.AreEqual(400m, (await service.Ledger.PositionAsync(paper.Account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice,
+ "Old shares at the price of the new ones would be a loss that is not there.");
var before = http.Requests.Count;
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.ReconcileAllAsync(_none).ConfigureAwait(false);
@@ -170,6 +174,10 @@ public sealed class TradingServiceTests
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
rig.Clock.Advance(TimeSpan.FromDays(1));
+ service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
+ await service.PhotographAsync(_none).ConfigureAwait(false);
+ Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice,
+ "The split is not applied yet: the photograph waits for it.");
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!;
@@ -189,4 +197,139 @@ public sealed class TradingServiceTests
await service.PhotographAsync(_none).ConfigureAwait(false);
Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
}
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task TheSimulatorsAbsenceMeetsASplitAtItsDate()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ using var service = Service(rig, new FakeHttp());
+ var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
+ await service.StartAsync(_none).ConfigureAwait(false);
+ var manager = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca);
+ var paper = (PaperBroker)manager.Broker;
+ await paper.DepositAsync(10_000m, "USD", _none).ConfigureAwait(false);
+ await service.Ledger.RecordCapitalAsync(manager.Account.AccountId, StrategyNames.EquityMomentum, 10_000m, "USD", "test", _none).ConfigureAwait(false);
+ await manager.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none)
+ .ConfigureAwait(false);
+ for (var i = 0; i < 6; i++)
+ {
+ service.Quotes.Put(new Quote("MSFT", 399.9m, 400m, rig.Clock.UtcNow));
+ await paper.PumpAsync(_none).ConfigureAwait(false);
+ await manager.TickAsync(_none).ConfigureAwait(false);
+ rig.Clock.Advance(TimeSpan.FromSeconds(20));
+ }
+
+ Assert.HasCount(1, await paper.GetOpenOrdersAsync(_none).ConfigureAwait(false));
+
+ // Off. Wednesday it falls through the stop and comes back; Thursday 2-for-1 and a dividend.
+ var day = new DateTimeOffset(2026, 11, 11, 16, 0, 0, TimeSpan.Zero);
+ await new BarStore(rig.Db, rig.Clock).UpsertMinuteAsync(msft.Id, [new Bar(day, 365, 366, 350, 364, 1000), new Bar(day.AddDays(1), 199, 201, 198, 200, 1000)], "test", BarQuality.Ok, _none)
+ .ConfigureAwait(false);
+ await rig.Db.WriteAsync(async s =>
+ {
+ foreach (var (kind, ratio, cash) in new[] { ("split", (decimal?)2m, (decimal?)null), ("cash_dividend", null, 1m) })
+ {
+ await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, 'MSFT', @k, '2026-11-12', @r, @c, 'USD', 'test', @k, @now)",
+ _none, ("id", Ids.NewId(rig.Clock)), ("k", kind), ("r", ratio), ("c", cash), ("now", rig.Clock.UtcNow)).ConfigureAwait(false);
+ }
+ }, _none).ConfigureAwait(false);
+ rig.Clock.Advance(TimeSpan.FromDays(3));
+ await service.CatchUpAsync(manager, paper, _none).ConfigureAwait(false);
+ await service.CorporateActionsAsync(_none).ConfigureAwait(false);
+
+ Assert.IsEmpty(await service.Ledger.PositionsAsync(manager.Account.AccountId, _none).ConfigureAwait(false), "The stop of before the split met the prices of before it.");
+ Assert.IsEmpty(await paper.GetPositionsAsync(_none).ConfigureAwait(false));
+ Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task UntilItIsRebuiltTheGuardKeepsWhatItKnewOfAnAccount()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ var folder = TempFolder.Create("guard-state");
+ try
+ {
+ var paths = new Anubis.Supervision.GuardPaths(folder);
+ var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{}", System.Net.HttpStatusCode.BadRequest));
+ using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32],
+ new Dictionary { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" }), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None,
+ new Guid("0193a7c0-0000-7000-8000-0000000000aa"), http)
+ { GuardFiles = paths };
+ var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
+ await service.StartAsync(_none).ConfigureAwait(false);
+ var account = service.Managers.Single(m => m.Account.Environment == TradingEnvironments.Demo).Account;
+ await service.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
+ await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false);
+
+ // Nor is it valued at a price of today: the shares of the ledger may be those of another time.
+ service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
+ await service.PhotographAsync(_none).ConfigureAwait(false);
+ Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
+ async Task<(DateTimeOffset At, Anubis.Supervision.GuardAccount Account)> WrittenAsync()
+ {
+ await service.WriteGuardStateAsync(_none).ConfigureAwait(false);
+ var state = Anubis.Supervision.GuardFiles.ReadState(paths)!;
+ return (state.WrittenAt, state.Accounts.Single(a => a.AccountId == account.AccountId));
+ }
+
+ Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions, "Nothing known: no stop is put on a ledger that may be old.");
+
+ // What the last state said, with its time, however often it is written again.
+ var first = rig.Clock.UtcNow;
+ var known = (await WrittenAsync().ConfigureAwait(false)).Account with { Positions = [new Anubis.Supervision.GuardPosition(msft.Id, "MSFT", StrategyNames.EquityMomentum, 4m, 380m, 0.0001m, false, "KKKKKKKK", 3)] };
+ Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, service.InstallationCode, [known with { WrittenAt = null }]));
+ for (var i = 0; i < 2; i++)
+ {
+ rig.Clock.Advance(TimeSpan.FromSeconds(10));
+ var (at, again) = await WrittenAsync().ConfigureAwait(false);
+ Assert.AreEqual(rig.Clock.UtcNow, at);
+ Assert.AreEqual((4m, first), (again.Positions.Single().Quantity, again.WrittenAt!.Value));
+ }
+
+ // Of another installation: not of this account's past.
+ Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, "OTHR", [known]));
+ Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions);
+ }
+ finally
+ {
+ TempFolder.Delete(folder);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task SplitsAndDividendsAreAskedAlsoForWhatLeftTheUniverse()
+ {
+ await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
+ var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{\"corporate_actions\":{},\"next_page_token\":null}"));
+ var bus = new EventBus();
+ var secrets = new SecretStore(rig.Db, rig.Clock, new byte[32], new Dictionary { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" });
+ using var market = new MarketDataService(rig.Db, rig.Clock, bus, new SettingsStore(rig.Db, rig.Clock, bus), secrets, null, http);
+ await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false);
+ Assert.IsEmpty(http.Requests, "Nothing to ask about.");
+
+ var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
+ await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
+ foreach (var (symbol, sold) in new[] { ("MSFT", false), ("NVDA", true), ("OLDX", true) })
+ {
+ var stock = await rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false);
+ var buy = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD");
+ var sell = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD");
+ var at = rig.Clock.UtcNow - TimeSpan.FromDays(symbol == "OLDX" ? 120 : 30);
+ await rig.Ledger.RecordFillAsync(buy with { ExecutedAt = at }, _none).ConfigureAwait(false);
+ if (sold)
+ {
+ await rig.Ledger.RecordFillAsync(sell with { ExecutedAt = at.AddDays(1) }, _none).ConfigureAwait(false);
+ }
+ }
+
+ await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false);
+ StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNVDA&");
+ StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-11-03&");
+ await market.RefreshCorporateActionsAsync(["NEWX"], new DateOnly(2026, 10, 20), _none).ConfigureAwait(false);
+ StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNEWX%2CNVDA&");
+ StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-10-13&");
+ }
}
diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs
index e9c953f..5f0957e 100644
--- a/tests/Anubis.Tests/TradingSupport.cs
+++ b/tests/Anubis.Tests/TradingSupport.cs
@@ -114,7 +114,8 @@ internal sealed class TradingRig : IAsyncDisposable
}
public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func>? marketOpen = null,
- Func>? pendingSplit = null, Func>>? splits = null)
+ Func>? pendingSplit = null, Func>>? splits = null,
+ Func, DateOnly, CancellationToken, Task>? refreshSplits = null, Func? afterFills = null)
{
var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync)
{
@@ -123,6 +124,8 @@ internal sealed class TradingRig : IAsyncDisposable
MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)),
PendingSplit = pendingSplit,
Splits = splits,
+ RefreshSplits = refreshSplits,
+ AfterFills = afterFills,
};
_owned.Add(manager);
return manager;