Finish an interrupted rebuild and replay the past without acting on it

The independent review found that a rebuild cut halfway was never finished
(stops canceled or lowered), that old stop executions replayed from the broker
queued a real sale, that a pending "close all" survived the restore, and that
reconciliation and corporate actions touched accounts not rebuilt yet. The
rebuild now keeps its starting point until it ends, protects the bot before the
first row, meets the splits at their date and leaves the ledger alone until it
is done. Dividends count the shares of after a split. A failed restore of a
missing SQLite file leaves no empty database, and a failed migration can be
tried again from the choice page.

refs #69 #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 22:15:34 +01:00
1 parent 24e20584d4
commit 5ef54b6f2a
17 files changed
+613 -80

No files matched your search

+47 -1
View File
@@ -136,7 +136,53 @@ internal sealed partial class AnubisHost(
/// For an error-page choice that writes into a missing SQLite file: the only place where a known installation gets a
/// new one. Called while the choice holds <see cref="ExclusiveAsync"/>.
/// </summary>
internal Database OpenForChoice() => _db ??= Database.Open(Config.Db!, allowCreate: SqliteFileMissing);
internal Database OpenForChoice()
{
if (_db is null)
{
_createdByChoice = SqliteFileMissing;
_db = Database.Open(Config.Db!, allowCreate: _createdByChoice);
}
return _db;
}
private bool _createdByChoice;
/// <summary>
/// A choice that failed or was cut halfway leaves nothing open that could create the missing file, and what it had
/// begun to write steps aside: moved and not deleted, because in the meantime the true file may have come back.
/// </summary>
internal async Task AbandonChoiceAsync()
{
if (!_createdByChoice || _db is null)
{
return;
}
await _db.DisposeAsync().ConfigureAwait(false);
_db = null;
_createdByChoice = false;
var path = Config.Db!.SqlitePath!;
var aside = path + ".incompleto-" + clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture);
foreach (var part in new[] { "", "-wal", "-shm" })
{
try
{
if (File.Exists(path + part))
{
File.Move(path + part, aside + part, overwrite: true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
LogStepFailed(logger, ex);
}
}
}
/// <summary>The choice is done: the database it opened is the one in use.</summary>
internal void KeepChoice() => _createdByChoice = false;
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
+13
View File
@@ -1168,6 +1168,7 @@ internal static partial class Forms
}
var verdict = status.Identity.Verdict;
var done = false;
try
{
switch (choice)
@@ -1197,19 +1198,31 @@ internal static partial class Forms
break;
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile:
// An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected.
// Asked by the user: one more attempt, even after one that failed.
host.MigrationFailed = null;
await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false);
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
break;
default:
return Results.Redirect("/?errore=scelta");
}
done = true;
}
catch (Exception ex) when (IsArchiveProblem(ex))
{
LogChoiceFailed(logger, ex, choice);
return Results.Redirect("/?errore=importazione");
}
finally
{
if (!done)
{
await host.AbandonChoiceAsync().ConfigureAwait(false);
}
}
host.KeepChoice();
LogChoice(logger, choice);
// Reset while the loop is still held: released first, it could start the application again before the reset
+5 -1
View File
@@ -576,7 +576,11 @@ public sealed partial class MarketDataService : IDisposable
return;
}
var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), today.AddDays(-7), today.AddDays(30), cancellationToken)
// Back to a week before the last news: after a long stop or a restore the days in between are missing too.
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);
await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false);
}
+6 -4
View File
@@ -118,6 +118,12 @@ public static class Archive
throw new SchemaException($"L'archivio è alla versione {index.SchemaVersion} dello schema, più recente di questa versione di Anubis.");
}
var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion));
// The whole archive is read and checked before the database is even opened: opening a SQLite file that
// is not there creates it.
await VerifyAsync(index, folder, tables, cancellationToken).ConfigureAwait(false);
var status = await Migrations.StatusAsync(db, cancellationToken).ConfigureAwait(false);
if (!status.IsEmpty && !await IsEmptyAsync(db, cancellationToken).ConfigureAwait(false))
{
@@ -129,10 +135,6 @@ public static class Archive
throw new InvalidOperationException("Il database di arrivo ha già uno schema più recente dell'archivio: usa un database vuoto.");
}
var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion));
// The whole archive is read and checked before the database is touched: a damaged one leaves it as it was.
await VerifyAsync(index, folder, tables, cancellationToken).ConfigureAwait(false);
await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false);
await db.WriteAsync(async s =>
@@ -0,0 +1,6 @@
-- A rebuild from the broker that has begun and is not finished (SPEC 15.1): from when it reads the executions and how
-- many orders it has written so far. Both leave together, in the write that ends it: an interrupted rebuild is taken
-- up again from the same point.
ALTER TABLE account_status ADD COLUMN rebuild_since {timestamp};
ALTER TABLE account_status ADD COLUMN rebuild_orders INTEGER;
+11
View File
@@ -236,6 +236,17 @@ public static class Installation
("x", true), ("t", now), ("a", Trading.StrategyStages.Reduced), ("b", Trading.StrategyStages.Real)).ConfigureAwait(false);
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);
// 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<Trading.BotRiskState>(bot, Trading.RiskEngine.Json) is { CloseAll: true })
{
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);
await Trading.Diary.NotifyAsync(s, clock, "close_all_dropped",
"Nel salvataggio c'era una chiusura di tutte le posizioni non ancora finita: non la continuo. Se la vuoi ancora, chiedila di nuovo dalla pagina Rischio.", cancellationToken)
.ConfigureAwait(false);
}
}
/// <summary>Why an order planned before a restore did not leave.</summary>
+10 -3
View File
@@ -1,5 +1,6 @@
using System.Globalization;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Trading;
@@ -481,13 +482,19 @@ public sealed class Ledger(Database db, IClock clock)
db.ReadAsync(async s =>
{
var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false);
var rows = await s.QueryAsync("SELECT side, quantity, fee, fee_currency FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at < @at",
r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency")),
var rows = await s.QueryAsync("SELECT side, quantity, fee, fee_currency, executed_at FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at < @at",
r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency"), At: r.Moment("executed_at")),
("a", accountId), ("i", instrumentId), ("s", strategy), ("at", at)).ConfigureAwait(false);
// The shares of before a split count as the new ones they became.
var splits = (await s.QueryAsync("SELECT c.ex_date, c.ratio FROM corporate_actions c JOIN instruments i ON i.symbol = c.symbol WHERE i.id = @i AND c.kind IN (@k1, @k2)",
r => (At: new DateTimeOffset(BarStore.ParseDay(r.Text("ex_date")).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), Ratio: r.MoneyOrNull("ratio")),
("i", instrumentId), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)).ConfigureAwait(false)).Where(x => x.Ratio is > 0m && x.At < at).ToList();
return rows.Sum(r =>
{
var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m;
return r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind);
var ratio = splits.Where(x => x.At > r.At).Aggregate(1m, (all, x) => all * x.Ratio!.Value);
return (r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind)) * ratio;
});
}, cancellationToken);
@@ -133,7 +133,7 @@ public sealed partial class OrderManager
}
}
private async Task ApplySplitCoreAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken)
private async Task ApplySplitCoreAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken, bool replay = false)
{
if (!split.ChangesShares)
{
@@ -154,7 +154,8 @@ public sealed partial class OrderManager
await paper.ApplySplitAsync(instrument.Symbol, split.Ratio.Value, oldShares.Value, exDate, cancellationToken).ConfigureAwait(false);
}
foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.InstrumentId == instrument.Id))
// Replayed, the split is old news: the stops on the account may be those put after it.
foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => !replay && p.InstrumentId == instrument.Id))
{
await CancelStopsOfAsync(instrument.Id, position.Strategy, instrument, cancellationToken).ConfigureAwait(false);
}
@@ -181,6 +182,11 @@ public sealed partial class OrderManager
private async Task AlignPositionAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken)
{
if (AwaitingRebuild)
{
return;
}
// An execution in progress owns the stops of its position until it ends. Where the broker refuses a purchase
// while any sell stop rests on the symbol (Alpaca), a purchase of any strategy holds every stop on it.
var sql = "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND status = @w AND (strategy = @s" +
+79 -20
View File
@@ -1,4 +1,5 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Trading;
@@ -30,20 +31,24 @@ public sealed partial class OrderManager
/// <summary>
/// Writes back every order of this installation the database does not know, then its executions. Run at every
/// start, before reconciliation: on a database that is up to date it finds nothing and writes nothing.
/// start, before reconciliation: on a database that is up to date it finds nothing and writes nothing. When the
/// account turns out to be ahead of the database, <paramref name="protect"/> runs before the first row is written.
/// </summary>
public async Task<RebuildReport> RebuildAsync(CancellationToken cancellationToken)
public async Task<RebuildReport> RebuildAsync(CancellationToken cancellationToken, Func<CancellationToken, Task>? protect = null)
{
if (_account.Environment == TradingEnvironments.Simulation)
{
// The internal simulator lives in the database: it went back in time together with the ledger.
AwaitingRebuild = false;
return RebuildReport.Nothing;
}
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
return await RebuildCoreAsync(cancellationToken).ConfigureAwait(false);
var report = await RebuildCoreAsync(protect, cancellationToken).ConfigureAwait(false);
AwaitingRebuild = false;
return report;
}
finally
{
@@ -51,14 +56,16 @@ public sealed partial class OrderManager
}
}
private async Task<RebuildReport> RebuildCoreAsync(CancellationToken cancellationToken)
private async Task<RebuildReport> RebuildCoreAsync(Func<CancellationToken, Task>? protect, CancellationToken cancellationToken)
{
var since = await RebuildSinceAsync(cancellationToken).ConfigureAwait(false);
// A rebuild interrupted halfway goes on from where it started reading, whatever was written since.
var (begun, written) = await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT rebuild_since, rebuild_orders FROM account_status WHERE account_id = @a",
r => (Since: r.MomentOrNull("rebuild_since"), Orders: r.IsNull("rebuild_orders") ? 0 : (int)r.Number("rebuild_orders")), ("a", _account.AccountId)), cancellationToken).ConfigureAwait(false);
var since = begun ?? await RebuildSinceAsync(cancellationToken).ConfigureAwait(false);
var fills = (await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false)).Where(f => IsMine(f.ClientOrderId)).OrderBy(f => f.ExecutedAt).ToList();
var open = (await _broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)).Where(o => IsMine(o.ClientOrderId)).ToList();
var unclear = new List<string>();
var orders = 0;
var onlyStops = true;
var unknown = new List<(string ClientId, ClientOrderIdParts Parts, Guid Instrument, List<BrokerFill> Own, BrokerOrder? Resting)>();
foreach (var clientId in fills.Select(f => f.ClientOrderId).Concat(open.Select(o => o.ClientOrderId)).Distinct(StringComparer.Ordinal))
{
if (await OrderByClientIdAsync(clientId, cancellationToken).ConfigureAwait(false) is not null)
@@ -66,16 +73,28 @@ public sealed partial class OrderManager
continue;
}
var parts = ClientOrderIds.Parse(clientId)!;
var own = fills.Where(f => f.ClientOrderId == clientId).ToList();
var resting = open.FirstOrDefault(o => o.ClientOrderId == clientId);
var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol;
if (await InstrumentBySymbolAsync(symbol, cancellationToken).ConfigureAwait(false) is not { } instrumentId)
if (await InstrumentBySymbolAsync(symbol, cancellationToken).ConfigureAwait(false) is { } instrumentId)
{
unknown.Add((clientId, ClientOrderIds.Parse(clientId)!, instrumentId, own, resting));
}
else
{
unclear.Add($"{symbol}: non è nel catalogo, l'ordine {clientId} resta da controllare a mano.");
continue;
}
}
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)))
{
await protect(cancellationToken).ConfigureAwait(false);
}
foreach (var (clientId, parts, instrumentId, own, resting) in unknown)
{
var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol;
var remote = resting ?? await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false);
if (resting is not null && parts.Purpose != OrderPurpose.Stop)
{
@@ -84,14 +103,19 @@ public sealed partial class OrderManager
remote = await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false) ?? resting with { Status = OrderStatus.Canceled };
}
await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, cancellationToken).ConfigureAwait(false);
onlyStops &= parts.Purpose == OrderPurpose.Stop && own.Count == 0;
orders++;
await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, since, cancellationToken).ConfigureAwait(false);
written++;
}
if (orders > 0)
if (written > 0)
{
var recorded = await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false);
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())
{
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))
{
@@ -99,10 +123,15 @@ public sealed partial class OrderManager
unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire.");
}
var message = $"Conto {_account.Name}: sul conto c'erano {orders} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." +
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(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken), cancellationToken).ConfigureAwait(false);
return new RebuildReport(orders, recorded, unclear, onlyStops);
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)
@@ -114,6 +143,22 @@ public sealed partial class OrderManager
return new RebuildReport(0, 0, unclear);
}
/// <summary>The splits with an ex-date up to <paramref name="until"/>, in the ledger only: each is applied once.</summary>
private async Task ReplaySplitsAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken)
{
foreach (var (instrument, split) in await SplitsUntilAsync(instrumentId, until, cancellationToken).ConfigureAwait(false))
{
await ApplySplitCoreAsync(instrument, split, cancellationToken, replay: true).ConfigureAwait(false);
}
}
private async Task<List<(Instrument Instrument, CorporateAction Split)>> SplitsUntilAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken) =>
Splits is null || await _instruments(instrumentId, cancellationToken).ConfigureAwait(false) is not { IsCrypto: false } instrument
? []
: [.. (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);
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."
: "";
@@ -144,7 +189,8 @@ public sealed partial class OrderManager
return id == Guid.Empty ? (Guid?)null : id;
}, cancellationToken);
private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List<BrokerFill> own, CancellationToken cancellationToken)
private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List<BrokerFill> own, DateTimeOffset since,
CancellationToken cancellationToken)
{
var filled = own.Sum(f => f.Quantity);
var side = remote?.Side ?? own[0].Side;
@@ -154,6 +200,12 @@ public sealed partial class OrderManager
remote?.StopPrice, OrderStatus.Created, 0m, null, remote?.StopPrice ?? remote?.LimitPrice, null, remote?.TimeInForce ?? TimeInForce.Gtc, false, created);
await _db.WriteAsync(async s =>
{
// The mark of a rebuild under way travels with its first row and leaves when everything is done.
var now = _clock.UtcNow;
await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, created_at, updated_at) VALUES (@id, @a, @m, @now, @now) ON CONFLICT (account_id) DO NOTHING",
cancellationToken, ("id", Ids.NewId(_clock)), ("a", _account.AccountId), ("m", AccountModes.Normal), ("now", now)).ConfigureAwait(false);
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);
@@ -162,7 +214,7 @@ public sealed partial class OrderManager
// The archive may be older than the promotion: what the bot holds on the real account gets its stops and
// its exits, and nothing else until the user confirms the strategy again.
await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, exit_only = @x, updated_at = @now WHERE strategy = @s AND live_account_id IS NULL", cancellationToken,
("a", _account.AccountId), ("x", true), ("now", _clock.UtcNow), ("s", parts.Strategy)).ConfigureAwait(false);
("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)
@@ -187,6 +239,13 @@ public sealed partial class OrderManager
}
var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, parts.Strategy, cancellationToken).ConfigureAwait(false);
var split = (await SplitsUntilAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false)).LastOrDefault().Split;
if (split is not null && stop.UpdatedAt < ExDate(split))
{
// A level of before the split is in old money: the one of the ledger has been divided.
continue;
}
if (position is { Quantity: > 0m } && (position.StopPrice is null || position.StopPrice < stop.StopPrice))
{
await _ledger.SetStopAsync(_account.AccountId, instrumentId, parts.Strategy, stop.StopPrice, cancellationToken).ConfigureAwait(false);
+30 -4
View File
@@ -132,6 +132,15 @@ public sealed partial class OrderManager : IDisposable
/// <summary>A split of the instrument not yet applied, looked for when the price is far below a stop (SPEC 6.10).</summary>
public Func<Instrument, CancellationToken, Task<CorporateAction?>>? PendingSplit { get; init; }
/// <summary>The splits of the instrument up to today, the oldest first, applied or not: a rebuild meets them at their date (SPEC 15.1).</summary>
public Func<Instrument, CancellationToken, Task<IReadOnlyList<CorporateAction>>>? Splits { get; init; }
/// <summary>
/// The account has not been compared with the executions of the broker since the start (SPEC 15.1): until then the
/// ledger may be older than the account, so nothing is written in it, no stop is moved and nothing is sold for it.
/// </summary>
public bool AwaitingRebuild { get; set; }
/// <summary>Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5).</summary>
public Func<CancellationToken, Task>? AfterFills { get; init; }
@@ -723,6 +732,11 @@ public sealed partial class OrderManager : IDisposable
private async Task<int> SyncFillsCoreAsync(CancellationToken cancellationToken)
{
if (AwaitingRebuild)
{
return 0;
}
var since = await _db.ReadAsync(async s =>
{
var last = (await s.QueryAsync("SELECT executed_at FROM fills WHERE account_id = @a AND execution_id NOT LIKE 'ANU%'", r => r.Moment("executed_at"), ("a", _account.AccountId))
@@ -734,7 +748,11 @@ public sealed partial class OrderManager : IDisposable
return await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false);
}
private async Task<int> SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken)
/// <summary>
/// With <paramref name="replay"/> 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.
/// </summary>
private async Task<int> SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, bool replay = false)
{
var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false);
var recorded = 0;
@@ -751,6 +769,11 @@ public sealed partial class OrderManager : IDisposable
continue;
}
if (replay)
{
await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false);
}
FillOutcome outcome;
try
{
@@ -795,10 +818,13 @@ 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);
// 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);
if (!replay)
{
// 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 (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
if (!replay && 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);
+5
View File
@@ -221,6 +221,11 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
throw new InvalidOperationException("A key that may withdraw is replaced, not aligned.");
}
if (manager.AwaitingRebuild)
{
return ReconcileResolution.NotCompared;
}
// Compared again right now: the choice applies to the differences that exist, never to old ones.
var report = await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
if (ReconcileOutcomes.IsDown(report.Outcome))
+8 -1
View File
@@ -40,7 +40,7 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
public const string NoRate = "no_fx_rate";
public const int PdtMaxDayTrades = 3;
private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
internal static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
/// <summary>The file that stops the bot (SPEC 9.3): <c>/data/STOP</c> in Docker, the data folder on desktop.</summary>
@@ -345,6 +345,13 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
var waiting = 0;
foreach (var manager in managers)
{
if (manager.AwaitingRebuild)
{
// The ledger may not be the true one yet: it is sold when it is.
waiting++;
continue;
}
foreach (var position in await ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false))
{
if (await instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument)
+62 -40
View File
@@ -330,6 +330,8 @@ public sealed partial class TradingService : IDisposable
ConfirmPrice = Quotes.ConfirmAsync,
MarketOpen = MarketOpenAsync,
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
Splits = SplitsAsync,
AwaitingRebuild = account.Environment != TradingEnvironments.Simulation,
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
Gate = Risk is null ? null : Risk.GateAsync,
LivePermit = Stages.LiveRefusalAsync,
@@ -351,7 +353,6 @@ public sealed partial class TradingService : IDisposable
await GuardAsync("azioni societarie", () => _market.RefreshCorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
}
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values)
{
await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false);
@@ -411,6 +412,7 @@ 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);
}
else
@@ -418,6 +420,9 @@ public sealed partial class TradingService : IDisposable
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);
}
Guard?.Step("riconciliazione " + name);
@@ -438,14 +443,11 @@ public sealed partial class TradingService : IDisposable
/// 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.
/// </summary>
internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken)
{
var report = await manager.RebuildAsync(cancellationToken).ConfigureAwait(false);
if (!report.FoundAnything)
{
return;
}
internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) =>
manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct));
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\"")
@@ -840,7 +842,7 @@ public sealed partial class TradingService : IDisposable
public async Task ReconcileAllAsync(CancellationToken cancellationToken)
{
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values)
foreach (var manager in _managers.Values.Where(m => !m.AwaitingRebuild))
{
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
}
@@ -852,6 +854,19 @@ public sealed partial class TradingService : IDisposable
/// </summary>
public async Task CorporateActionsAsync(CancellationToken cancellationToken)
{
foreach (var manager in _managers.Values.Where(m => !m.AwaitingRebuild))
{
await CorporateActionsAsync(manager, cancellationToken).ConfigureAwait(false);
}
}
private async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken)
{
if (manager.Account.Broker != Venues.Alpaca)
{
return;
}
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
var actions = await _db.ReadAsync(s => s.QueryAsync(
"SELECT symbol, kind, ex_date, ratio, cash_amount, currency, new_symbol, source, source_key FROM corporate_actions WHERE ex_date <= @d ORDER BY ex_date",
@@ -862,34 +877,37 @@ public sealed partial class TradingService : IDisposable
Currency = r.TextOrNull("currency"),
NewSymbol = r.TextOrNull("new_symbol"),
}, ("d", BarStore.DayText(today))), cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca))
{
var positions = await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false);
var held = new Dictionary<string, Instrument>(StringComparer.Ordinal);
foreach (var id in positions.Select(p => p.InstrumentId).Distinct())
{
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument)
{
held[instrument.Symbol] = instrument;
}
}
var positions = await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false);
foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol)))
// 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<string, Instrument>(StringComparer.Ordinal);
foreach (var id in positions.Select(p => p.InstrumentId).Concat(traded).Distinct())
{
if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument)
{
var instrument = held[action.Symbol];
if (action.ChangesShares)
{
// The ledger and, on the simulator, the broker's book, together and once.
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false);
}
else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m)
{
await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false);
}
held[instrument.Symbol] = instrument;
}
}
foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol)))
{
var instrument = held[action.Symbol];
if (action.ChangesShares)
{
// The ledger and, on the simulator, the broker's book, together and once.
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false);
}
else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m)
{
await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false);
}
}
}
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;
@@ -901,8 +919,8 @@ public sealed partial class TradingService : IDisposable
var exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
var currency = action.Currency ?? account.Currency;
var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false))
.Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList();
var strategies = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT strategy FROM fills WHERE account_id = @a AND instrument_id = @i", r => r.Text("strategy"),
("a", account.AccountId), ("i", instrument.Id)), cancellationToken).ConfigureAwait(false);
var held = new List<(string Strategy, decimal Quantity)>();
foreach (var strategy in strategies)
{
@@ -940,13 +958,7 @@ public sealed partial class TradingService : IDisposable
private async Task<CorporateAction?> PendingSplitAsync(Guid accountId, Instrument instrument, CancellationToken cancellationToken)
{
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
var splits = await _db.ReadAsync(s => s.QueryAsync(
"SELECT kind, ex_date, ratio, source, source_key FROM corporate_actions WHERE symbol = @s AND ex_date <= @d AND kind IN (@k1, @k2) ORDER BY ex_date DESC",
r => new CorporateAction(instrument.Symbol, r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) { Ratio = r.MoneyOrNull("ratio") },
("s", instrument.Symbol), ("d", BarStore.DayText(today)), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)), cancellationToken)
.ConfigureAwait(false);
foreach (var split in splits.Where(s => s.ChangesShares))
foreach (var split in (await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false)).Reverse())
{
if (!await AppliedAsync(accountId, split.SourceKey, cancellationToken).ConfigureAwait(false))
{
@@ -957,6 +969,16 @@ public sealed partial class TradingService : IDisposable
return null;
}
private Task<IReadOnlyList<CorporateAction>> SplitsAsync(Instrument instrument, CancellationToken cancellationToken)
{
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
return _db.ReadAsync<IReadOnlyList<CorporateAction>>(async s => [.. (await s.QueryAsync(
"SELECT kind, ex_date, ratio, source, source_key FROM corporate_actions WHERE symbol = @s AND ex_date <= @d AND kind IN (@k1, @k2) ORDER BY ex_date",
r => new CorporateAction(instrument.Symbol, r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) { Ratio = r.MoneyOrNull("ratio") },
("s", instrument.Symbol), ("d", BarStore.DayText(today)), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)).ConfigureAwait(false))
.Where(a => a.ChangesShares)], cancellationToken);
}
private Task<bool> MarketOpenAsync(Instrument instrument, CancellationToken cancellationToken)
{
if (instrument.IsCrypto)