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

+60
View File
@@ -94,6 +94,24 @@ public sealed class RestoreServerTests
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.");
File.Copy(away, file);
await server.WaitForAsync(HostMode.Ready);
@@ -260,6 +278,48 @@ public sealed class RestoreServerTests
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]
public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine()
{
+206 -2
View File
@@ -262,8 +262,7 @@ public sealed class RestoreTests
var rig = await a.Rig.RestoreAsync(archive);
a.Restored.Add(rig);
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none);
using var service = new TradingService(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());
using var service = Service(rig);
var manager = rig.Manager(a.Broker, a.Context);
await service.RebuildAsync(manager, _none);
@@ -300,4 +299,209 @@ public sealed class RestoreTests
var open = await a.Paper.GetOpenOrdersAsync(_none);
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.");
}
[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]
[TestCategory(Category.Integration)]
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.
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) " +
"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.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.
service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow));
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,
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)
{
@@ -122,6 +122,7 @@ internal sealed class TradingRig : IAsyncDisposable
ConfirmPrice = QuoteAsync,
MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)),
PendingSplit = pendingSplit,
Splits = splits,
};
_owned.Add(manager);
return manager;
@@ -181,6 +182,12 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
/// <summary>Every fill is reported twice.</summary>
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>
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)
{
if (FailFillsAt > 0 && --FailFillsAt == 0)
{
throw new BrokerException("risposta interrotta", retryable: true);
}
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;
}