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 /// 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"/>. /// new one. Called while the choice holds <see cref="ExclusiveAsync"/>.
/// </summary> /// </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> /// <summary>Holds the loop still while an error-page choice works on the database.</summary>
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken) 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 verdict = status.Identity.Verdict;
var done = false;
try try
{ {
switch (choice) switch (choice)
@@ -1197,19 +1198,31 @@ internal static partial class Forms
break; break;
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile: 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. // 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 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); await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
break; break;
default: default:
return Results.Redirect("/?errore=scelta"); return Results.Redirect("/?errore=scelta");
} }
done = true;
} }
catch (Exception ex) when (IsArchiveProblem(ex)) catch (Exception ex) when (IsArchiveProblem(ex))
{ {
LogChoiceFailed(logger, ex, choice); LogChoiceFailed(logger, ex, choice);
return Results.Redirect("/?errore=importazione"); return Results.Redirect("/?errore=importazione");
} }
finally
{
if (!done)
{
await host.AbandonChoiceAsync().ConfigureAwait(false);
}
}
host.KeepChoice();
LogChoice(logger, choice); LogChoice(logger, choice);
// Reset while the loop is still held: released first, it could start the application again before the reset // 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; 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); .ConfigureAwait(false);
await new CorporateActionStore(_db, _clock).UpsertAsync(actions, 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."); 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); var status = await Migrations.StatusAsync(db, cancellationToken).ConfigureAwait(false);
if (!status.IsEmpty && !await IsEmptyAsync(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."); 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 Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false);
await db.WriteAsync(async s => 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); ("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, 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); ("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> /// <summary>Why an order planned before a restore did not leave.</summary>
+10 -3
View File
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using Anubis.Core; using Anubis.Core;
using Anubis.Data;
using Anubis.Db; using Anubis.Db;
namespace Anubis.Trading; namespace Anubis.Trading;
@@ -481,13 +482,19 @@ public sealed class Ledger(Database db, IClock clock)
db.ReadAsync(async s => db.ReadAsync(async s =>
{ {
var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); 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", 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")), 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); ("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 => return rows.Sum(r =>
{ {
var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m; 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); }, 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) 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); 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); 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) 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 // 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. // 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" + 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.Core;
using Anubis.Data;
using Anubis.Db; using Anubis.Db;
namespace Anubis.Trading; namespace Anubis.Trading;
@@ -30,20 +31,24 @@ public sealed partial class OrderManager
/// <summary> /// <summary>
/// Writes back every order of this installation the database does not know, then its executions. Run at every /// 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> /// </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) if (_account.Environment == TradingEnvironments.Simulation)
{ {
// The internal simulator lives in the database: it went back in time together with the ledger. // The internal simulator lives in the database: it went back in time together with the ledger.
AwaitingRebuild = false;
return RebuildReport.Nothing; return RebuildReport.Nothing;
} }
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try try
{ {
return await RebuildCoreAsync(cancellationToken).ConfigureAwait(false); var report = await RebuildCoreAsync(protect, cancellationToken).ConfigureAwait(false);
AwaitingRebuild = false;
return report;
} }
finally 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 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 open = (await _broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)).Where(o => IsMine(o.ClientOrderId)).ToList();
var unclear = new List<string>(); var unclear = new List<string>();
var orders = 0; var unknown = new List<(string ClientId, ClientOrderIdParts Parts, Guid Instrument, List<BrokerFill> Own, BrokerOrder? Resting)>();
var onlyStops = true;
foreach (var clientId in fills.Select(f => f.ClientOrderId).Concat(open.Select(o => o.ClientOrderId)).Distinct(StringComparer.Ordinal)) 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) if (await OrderByClientIdAsync(clientId, cancellationToken).ConfigureAwait(false) is not null)
@@ -66,16 +73,28 @@ public sealed partial class OrderManager
continue; continue;
} }
var parts = ClientOrderIds.Parse(clientId)!;
var own = fills.Where(f => f.ClientOrderId == clientId).ToList(); var own = fills.Where(f => f.ClientOrderId == clientId).ToList();
var resting = open.FirstOrDefault(o => o.ClientOrderId == clientId); var resting = open.FirstOrDefault(o => o.ClientOrderId == clientId);
var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol; 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."); 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); var remote = resting ?? await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false);
if (resting is not null && parts.Purpose != OrderPurpose.Stop) 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 }; remote = await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false) ?? resting with { Status = OrderStatus.Canceled };
} }
await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, cancellationToken).ConfigureAwait(false); await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, since, cancellationToken).ConfigureAwait(false);
onlyStops &= parts.Purpose == OrderPurpose.Stop && own.Count == 0; written++;
orders++;
} }
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); 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)) 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."); 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); (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since);
await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken), cancellationToken).ConfigureAwait(false); await _db.WriteAsync(async s =>
return new RebuildReport(orders, recorded, unclear, onlyStops); {
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) if (unclear.Count > 0)
@@ -114,6 +143,22 @@ public sealed partial class OrderManager
return new RebuildReport(0, 0, unclear); 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 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." ? $" 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; return id == Guid.Empty ? (Guid?)null : id;
}, cancellationToken); }, 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 filled = own.Sum(f => f.Quantity);
var side = remote?.Side ?? own[0].Side; 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); remote?.StopPrice, OrderStatus.Created, 0m, null, remote?.StopPrice ?? remote?.LimitPrice, null, remote?.TimeInForce ?? TimeInForce.Gtc, false, created);
await _db.WriteAsync(async s => 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 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, 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); ("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 // 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. // 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, 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); }, cancellationToken).ConfigureAwait(false);
remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt) 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 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)) 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); 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> /// <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; } 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> /// <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; } public Func<CancellationToken, Task>? AfterFills { get; init; }
@@ -723,6 +732,11 @@ public sealed partial class OrderManager : IDisposable
private async Task<int> SyncFillsCoreAsync(CancellationToken cancellationToken) private async Task<int> SyncFillsCoreAsync(CancellationToken cancellationToken)
{ {
if (AwaitingRebuild)
{
return 0;
}
var since = await _db.ReadAsync(async s => 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)) 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); 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 fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false);
var recorded = 0; var recorded = 0;
@@ -751,6 +769,11 @@ public sealed partial class OrderManager : IDisposable
continue; continue;
} }
if (replay)
{
await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false);
}
FillOutcome outcome; FillOutcome outcome;
try try
{ {
@@ -795,10 +818,13 @@ public sealed partial class OrderManager : IDisposable
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text, await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text,
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false); 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). if (!replay)
await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, 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);
}
}, 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). // 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); 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."); 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. // Compared again right now: the choice applies to the differences that exist, never to old ones.
var report = await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); var report = await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
if (ReconcileOutcomes.IsDown(report.Outcome)) 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 string NoRate = "no_fx_rate";
public const int PdtMaxDayTrades = 3; 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"); 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> /// <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; var waiting = 0;
foreach (var manager in managers) 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)) foreach (var position in await ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false))
{ {
if (await instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) 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, ConfirmPrice = Quotes.ConfirmAsync,
MarketOpen = MarketOpenAsync, MarketOpen = MarketOpenAsync,
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
Splits = SplitsAsync,
AwaitingRebuild = account.Environment != TradingEnvironments.Simulation,
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false), AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
Gate = Risk is null ? null : Risk.GateAsync, Gate = Risk is null ? null : Risk.GateAsync,
LivePermit = Stages.LiveRefusalAsync, 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", () => _market.RefreshCorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
} }
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
foreach (var manager in _managers.Values) foreach (var manager in _managers.Values)
{ {
await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false); await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false);
@@ -411,6 +412,7 @@ public sealed partial class TradingService : IDisposable
{ {
if (manager.Broker is PaperBroker paper) 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 paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
} }
else else
@@ -418,6 +420,9 @@ public sealed partial class TradingService : IDisposable
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("esecuzioni dal broker " + name); Guard?.Step("esecuzioni dal broker " + name);
await RebuildAsync(manager, cancellationToken).ConfigureAwait(false); 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); 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: /// 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. /// the protected restart starts here, as it would have after an import.
/// </summary> /// </summary>
internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) =>
{ manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct));
var report = await manager.RebuildAsync(cancellationToken).ConfigureAwait(false);
if (!report.FoundAnything)
{
return;
}
private async Task ProtectAsync(OrderManager manager, CancellationToken cancellationToken)
{
if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true } 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) && 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\"") .ConfigureAwait(false) == "\"stopped\"")
@@ -840,7 +842,7 @@ public sealed partial class TradingService : IDisposable
public async Task ReconcileAllAsync(CancellationToken cancellationToken) public async Task ReconcileAllAsync(CancellationToken cancellationToken)
{ {
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); 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); await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
} }
@@ -852,6 +854,19 @@ public sealed partial class TradingService : IDisposable
/// </summary> /// </summary>
public async Task CorporateActionsAsync(CancellationToken cancellationToken) 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 today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
var actions = await _db.ReadAsync(s => s.QueryAsync( 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", "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"), Currency = r.TextOrNull("currency"),
NewSymbol = r.TextOrNull("new_symbol"), NewSymbol = r.TextOrNull("new_symbol"),
}, ("d", BarStore.DayText(today))), cancellationToken).ConfigureAwait(false); }, ("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 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;
}
}
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]; held[instrument.Symbol] = instrument;
if (action.ChangesShares) }
{ }
// The ledger and, on the simulator, the broker's book, together and once.
await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol)))
} {
else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m) var instrument = held[action.Symbol];
{ if (action.ChangesShares)
await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false); {
} // 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) private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken)
{ {
var key = "div:" + action.SourceKey; 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 exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
var currency = action.Currency ?? account.Currency; var currency = action.Currency ?? account.Currency;
var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)) 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"),
.Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList(); ("a", account.AccountId), ("i", instrument.Id)), cancellationToken).ConfigureAwait(false);
var held = new List<(string Strategy, decimal Quantity)>(); var held = new List<(string Strategy, decimal Quantity)>();
foreach (var strategy in strategies) 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) private async Task<CorporateAction?> PendingSplitAsync(Guid accountId, Instrument instrument, CancellationToken cancellationToken)
{ {
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); foreach (var split in (await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false)).Reverse())
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))
{ {
if (!await AppliedAsync(accountId, split.SourceKey, cancellationToken).ConfigureAwait(false)) if (!await AppliedAsync(accountId, split.SourceKey, cancellationToken).ConfigureAwait(false))
{ {
@@ -957,6 +969,16 @@ public sealed partial class TradingService : IDisposable
return null; 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) private Task<bool> MarketOpenAsync(Instrument instrument, CancellationToken cancellationToken)
{ {
if (instrument.IsCrypto) if (instrument.IsCrypto)
+60
View File
@@ -94,6 +94,24 @@ public sealed class RestoreServerTests
StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta"); StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta");
} }
// A damaged archive: refused, and the file is still not there, however many turns the loop makes.
foreach (var damage in new[] { "index.json", "users.jsonl" })
{
var saved = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
var part = Path.Combine(saved.Folder, Backups.ArchiveFolder, damage);
var good = await File.ReadAllTextAsync(part);
await File.WriteAllTextAsync(part, good[..(good.Length / 2)]);
using (var failed = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", saved.Name)))
{
StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione", damage);
}
await File.WriteAllTextAsync(part, good);
await Task.Delay(6000);
Assert.IsFalse(File.Exists(file), "Trap 20, after a damaged " + damage);
StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è");
}
Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself."); Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself.");
File.Copy(away, file); File.Copy(away, file);
await server.WaitForAsync(HostMode.Ready); await server.WaitForAsync(HostMode.Ready);
@@ -260,6 +278,48 @@ public sealed class RestoreServerTests
TempFolder.Delete(data); TempFolder.Delete(data);
} }
[TestMethod]
public async Task AfterAFailedMigrationTheDatabaseCanBeChosenAgain()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("migration-choice");
var directory = new DataDirectory(data);
directory.Ensure();
var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile };
await using (var db = Database.Open(settings))
{
await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12);
await Installation.CheckAsync(db, directory, SystemClock.Instance);
await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)"));
}
File.Delete(directory.InstallationFile);
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
for (var i = 0; i < 2; i++)
{
using var failed = await server.PostFormAsync("/", "/azioni/servizio/usa-questo", ("password", ServerHarness.AdminPassword));
StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione");
}
await using (var db = Database.Open(settings))
{
await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates"));
}
using (var again = await server.PostFormAsync("/", "/azioni/servizio/usa-questo", ("password", ServerHarness.AdminPassword)))
{
Assert.AreEqual("/", ServerHarness.Location(again));
}
await server.WaitForAsync(HostMode.Ready);
}
TempFolder.Delete(data);
}
[TestMethod] [TestMethod]
public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine() public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine()
{ {
+206 -2
View File
@@ -262,8 +262,7 @@ public sealed class RestoreTests
var rig = await a.Rig.RestoreAsync(archive); var rig = await a.Rig.RestoreAsync(archive);
a.Restored.Add(rig); a.Restored.Add(rig);
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none); await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none);
using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock), using var service = Service(rig);
TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp());
var manager = rig.Manager(a.Broker, a.Context); var manager = rig.Manager(a.Broker, a.Context);
await service.RebuildAsync(manager, _none); await service.RebuildAsync(manager, _none);
@@ -300,4 +299,209 @@ public sealed class RestoreTests
var open = await a.Paper.GetOpenOrdersAsync(_none); var open = await a.Paper.GetOpenOrdersAsync(_none);
Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity."); Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity.");
} }
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ARebuildInterruptedHalfwayIsTakenUpFromTheSamePoint()
{
await using var a = await Account.OpenAsync();
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
var archive = await a.ArchiveAsync();
await a.BuyAsync(a.Eth, 0.5m, 1_900m);
a.Rig.Clock.Advance(TimeSpan.FromHours(30));
await a.Rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 58_500m, _none);
await a.TurnsAsync(a.Manager, 2);
await a.BuyAsync(a.Eth, 1m, 1_900m);
var stops = (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList();
// A copy put back by hand: the bot is active, and the broker stops answering after the orders are written.
var rig = await a.Rig.RestoreAsync(archive);
a.Restored.Add(rig);
var manager = rig.Manager(a.Broker, a.Context);
var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus());
using var service = Service(rig);
a.Broker.FailFillsAt = 2;
await Assert.ThrowsExactlyAsync<BrokerException>(() => service.RebuildAsync(manager, _none));
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.");
// 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,
last.FeeCurrency, last.ExecutedAt), _none);
// 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.");
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.");
Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_rebuilt'", r => r.Text("message")));
Assert.IsFalse((await manager.RebuildAsync(_none)).FoundAnything);
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task AnOldStopReplayedFromTheBrokerSellsNothingToday()
{
// The stop fired in two executions, the strategy bought again later: only the last position counts.
await using var a = await Account.OpenAsync();
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
var archive = await a.ArchiveAsync();
a.Broker.SplitStopFills = true;
a.Rig.Clock.Advance(TimeSpan.FromHours(2));
a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m);
await a.TurnsAsync(a.Manager, 4);
a.Rig.Quote(a.Btc.Symbol, 60_000m, 60_010m);
await a.TurnsAsync(a.Manager, 2);
await a.BuyAsync(a.Btc, 0.01m, 57_500m);
var (rig, manager) = await a.RestoreAsync(archive);
var before = await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill'", r => r.Id("id"));
Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything);
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id")), "Nothing is sold for a stop of the past.");
Assert.HasCount(before.Count, await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill'", r => r.Id("id")), "Old executions do not reach the phone as new.");
await manager.AlignStopsAsync(_none);
await a.TurnsAsync(manager, 3);
Assert.AreEqual(0.01m, (await a.Paper.GetPositionsAsync(_none)).Single(p => p.Symbol == a.Btc.Symbol).Quantity, 0.001m);
Assert.AreEqual(57_500m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice);
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task UntilItIsRebuiltAnAccountIsNotTouched()
{
await using var a = await Account.OpenAsync();
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
var archive = await a.ArchiveAsync();
// Days later: a trade opened and closed, then the stop the archive knows fires.
a.Rig.Clock.Advance(TimeSpan.FromDays(3));
await a.BuyAsync(a.Eth, 1m, 1_900m);
await a.SellAsync(a.Eth, 1m);
a.Rig.Clock.Advance(TimeSpan.FromDays(6));
a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m);
await a.TurnsAsync(a.Manager, 3);
var (rig, manager) = await a.RestoreAsync(archive);
manager.AwaitingRebuild = true;
var count = async () => (await rig.QueryAsync("SELECT id FROM fills", r => r.Id("id"))).Count;
var known = await count();
Assert.AreEqual(0, await manager.SyncFillsAsync(_none));
await manager.RefreshAsync(_none);
await manager.AlignStopsAsync(_none);
Assert.AreEqual(ReconcileResolution.NotCompared, await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ResolveAsync(manager, ReconcileChoice.Align, "test", _none));
Assert.AreEqual(known, await count(), "No execution is written before the rebuild.");
await AskCloseAllAsync(rig);
Assert.AreEqual(0, await CloseAllAsync(rig, manager), "And nothing is sold.");
Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything);
Assert.IsFalse(manager.AwaitingRebuild);
await manager.SyncFillsAsync(_none);
await a.SameLedgerAsync(rig, "The trade of the days in between is there.");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task APendingCloseAllDoesNotSurviveTheRestore()
{
await using var a = await Account.OpenAsync();
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
await AskCloseAllAsync(a.Rig);
var (rig, manager) = await a.RestoreAsync(await a.ArchiveAsync());
await manager.RebuildAsync(_none);
Assert.AreEqual(0, await CloseAllAsync(rig, manager), "The command belonged to before the archive.");
Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'close_all_dropped'", r => r.Text("message")));
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task SplitsMeetTheRebuiltExecutionsAtTheirDate()
{
// 10 shares in the archive; then 5 more, a 2-for-1 split, 8 new shares sold, and a stop put after the split.
await using var rig = await TradingRig.CreateAsync();
var folder = TempFolder.Create("restore-split");
try
{
await Installation.CheckAsync(rig.Db, new DataDirectory(Path.Combine(folder, "data")), rig.Clock, _none);
var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo);
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT"));
rig.Quote(msft.Symbol, 399.9m, 400m);
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 split = new CorporateAction("MSFT", CorporateActionKinds.Split, new DateOnly(2026, 11, 12), "test", "split-msft") { Ratio = 2m };
Task<IReadOnlyList<CorporateAction>> SplitsAsync(Instrument i, CancellationToken ct) =>
Task.FromResult<IReadOnlyList<CorporateAction>>(rig.Clock.UtcNow >= new DateTimeOffset(2026, 11, 12, 0, 0, 0, TimeSpan.Zero) ? [split] : []);
var manager = rig.Manager(broker, context, splits: SplitsAsync);
async Task TradeAsync(OrderSide side, decimal quantity, decimal? stop)
{
rig.Refresh();
Assert.IsNull((await manager.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, side, quantity, side == OrderSide.Buy ? OrderPurpose.Entry : OrderPurpose.Exit, Ids.NewId(rig.Clock))
{
StopLevel = stop,
StartAggressive = true,
}, _none)).Refusal);
await TurnsAsync();
}
async Task TurnsAsync()
{
for (var i = 0; i < 3; i++)
{
rig.Refresh();
await paper.PumpAsync(_none);
await manager.TickAsync(_none);
rig.Clock.Advance(_minute);
}
}
await TradeAsync(OrderSide.Buy, 10m, 360m);
var archive = Path.Combine(folder, "archivio");
await Archive.ExportAsync(rig.Db, archive, rig.Clock, _none);
rig.Clock.Advance(TimeSpan.FromDays(1));
await TradeAsync(OrderSide.Buy, 5m, 360m);
rig.Clock.Advance(TimeSpan.FromDays(1));
rig.Quote(msft.Symbol, 199.9m, 200m);
await paper.ApplySplitAsync("MSFT", 2m, 15m, new DateTimeOffset(2026, 11, 12, 0, 0, 0, TimeSpan.Zero), _none);
await manager.ApplySplitAsync(msft, split, _none);
await TurnsAsync();
await TradeAsync(OrderSide.Sell, 8m, null);
var lost = (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!;
Assert.AreEqual((22m, 180m), (lost.Quantity, lost.StopPrice));
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);
again.StopGeneration = restored.Clock.UtcNow.UtcTicks;
var report = await again.RebuildAsync(_none);
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")));
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)));
}
finally
{
TempFolder.Delete(folder);
}
}
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<int> AskCloseAllAsync(TradingRig rig) => 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);
private static async Task<int> CloseAllAsync(TradingRig rig, OrderManager manager)
{
var risk = new RiskEngine(rig.Db, rig.Clock, rig.Ledger, new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), new SettingsStore(rig.Db, rig.Clock, new EventBus()), new FxStore(rig.Db, rig.Clock), rig.FindAsync, rig.QuoteAsync);
await risk.ContinueCloseAllAsync([manager], _none);
return (await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id"))).Count;
}
} }
+35 -1
View File
@@ -72,6 +72,33 @@ public sealed class TradingServiceTests
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is."); }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is.");
} }
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnAccountOfTheBrokerWaitsForItsRebuildBeforeAnythingTouchesIt()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{}", System.Net.HttpStatusCode.BadRequest));
using var service = Service(rig, http, new Dictionary<string, string> { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" });
await service.StartAsync(_none).ConfigureAwait(false);
var paper = service.Managers.Single(m => m.Account.Environment == TradingEnvironments.Demo);
Assert.IsTrue(paper.AwaitingRebuild, "The broker answers nothing: the rebuild is still to be done.");
Assert.IsTrue(service.Managers.Where(m => m != paper).All(m => !m.AwaitingRebuild));
CollectionAssert.Contains(service.AccountsToRebuild.ToList(), paper.Account.Name);
// A split and a dividend in the table, and the five minutes of the reconciliation: nothing reaches the account.
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
await service.Ledger.RecordCapitalAsync(paper.Account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
await service.Ledger.RecordFillAsync(rig.Fill(paper.Account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false);
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));
var before = http.Requests.Count;
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.ReconcileAllAsync(_none).ConfigureAwait(false);
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(paper.Account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(before, http.Requests.Count, "The reconciliation does not ask anything either.");
}
[TestMethod] [TestMethod]
[TestCategory(Category.Integration)] [TestCategory(Category.Integration)]
public async Task TheSimulatorHoldsTheMoneyItsLedgersGive() public async Task TheSimulatorHoldsTheMoneyItsLedgersGive()
@@ -121,7 +148,8 @@ public sealed class TradingServiceTests
// month is still in the table: it came before the purchase and must change nothing. // month is still in the table: it came before the purchase and must change nothing.
await rig.Db.WriteAsync(async s => await rig.Db.WriteAsync(async s =>
{ {
foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft"), ("split", "2026-10-01", 3m, null, "split-msft-old") }) foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft"), ("split", "2026-10-01", 3m, null, "split-msft-old"),
("cash_dividend", "2026-11-14", null, 0.50m, "div-msft-2") })
{ {
await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) " + 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, @d, @r, @c, 'USD', 'test', @key, @now)", _none, "VALUES (@id, 'MSFT', @k, @d, @r, @c, 'USD', 'test', @key, @now)", _none,
@@ -150,6 +178,12 @@ public sealed class TradingServiceTests
Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false)); Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false));
Assert.IsEmpty(http.Requests); Assert.IsEmpty(http.Requests);
// A dividend after the split pays the new shares, sold since or not.
rig.Clock.Advance(TimeSpan.FromDays(3));
await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Sell, 4m, 200m, feeCurrency: "USD"), _none).ConfigureAwait(false);
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
CollectionAssert.AreEquivalent(new[] { 7.5m, 10m }, (await DividendsAsync().ConfigureAwait(false)).ToArray(), "20 new shares at 0,50.");
// Every photograph values the positions at the market, not at their last fill. // Every photograph values the positions at the market, not at their last fill.
service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow)); service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow));
await service.PhotographAsync(_none).ConfigureAwait(false); await service.PhotographAsync(_none).ConfigureAwait(false);
+22 -1
View File
@@ -114,7 +114,7 @@ internal sealed class TradingRig : IAsyncDisposable
} }
public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func<Instrument, CancellationToken, Task<bool>>? marketOpen = null, public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func<Instrument, CancellationToken, Task<bool>>? marketOpen = null,
Func<Instrument, CancellationToken, Task<CorporateAction?>>? pendingSplit = null) Func<Instrument, CancellationToken, Task<CorporateAction?>>? pendingSplit = null, Func<Instrument, CancellationToken, Task<IReadOnlyList<CorporateAction>>>? splits = null)
{ {
var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync) var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync)
{ {
@@ -122,6 +122,7 @@ internal sealed class TradingRig : IAsyncDisposable
ConfirmPrice = QuoteAsync, ConfirmPrice = QuoteAsync,
MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)), MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)),
PendingSplit = pendingSplit, PendingSplit = pendingSplit,
Splits = splits,
}; };
_owned.Add(manager); _owned.Add(manager);
return manager; return manager;
@@ -181,6 +182,12 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
/// <summary>Every fill is reported twice.</summary> /// <summary>Every fill is reported twice.</summary>
public bool DuplicateFills { get; set; } public bool DuplicateFills { get; set; }
/// <summary>Every execution of a stop is reported in two halves.</summary>
public bool SplitStopFills { get; set; }
/// <summary>Which reading of the fills fails, counting from now: 1 the next, 2 the one after it.</summary>
public int FailFillsAt { get; set; }
/// <summary>Every call fails as if the network were down.</summary> /// <summary>Every call fails as if the network were down.</summary>
public bool Down { get; set; } public bool Down { get; set; }
@@ -246,7 +253,21 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
public async Task<IReadOnlyList<BrokerFill>> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) public async Task<IReadOnlyList<BrokerFill>> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken)
{ {
if (FailFillsAt > 0 && --FailFillsAt == 0)
{
throw new BrokerException("risposta interrotta", retryable: true);
}
var fills = await Guard(() => inner.GetFillsAsync(since, cancellationToken)).ConfigureAwait(false); var fills = await Guard(() => inner.GetFillsAsync(since, cancellationToken)).ConfigureAwait(false);
if (SplitStopFills)
{
fills = [.. fills.SelectMany(f => ClientOrderIds.Parse(f.ClientOrderId)?.Purpose != OrderPurpose.Stop ? [f] : new[]
{
f with { ExecutionId = f.ExecutionId + "a", Quantity = f.Quantity / 2m, Fee = f.Fee / 2m },
f with { ExecutionId = f.ExecutionId + "b", Quantity = f.Quantity / 2m, Fee = f.Fee / 2m, ExecutedAt = f.ExecutedAt.AddSeconds(1) },
})];
}
return DuplicateFills ? [.. fills, .. fills] : fills; return DuplicateFills ? [.. fills, .. fills] : fills;
} }