Replay the past of a rebuilt account in its order
What an account did while the bot was off is now written before the splits and the dividends of those days, once and without acting on it; an attempt cut halfway is taken up from the same point. Until then the account is not valued at today's price, the guard keeps the last figures it knew with their time, and a stop order only cancels what is open. Protective sales of the archive are not continued, and the rest of a stop that fired in part is sold. Also the decisions of the phase (ADR 0020), the manuals and the dates under the equity chart. refs #69 #72 #75 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e58a26e8fa
commit
76b64ef147
31 files changed
+957
-130
No files matched your search
@@ -325,6 +325,9 @@ public sealed class RestoreTests
|
||||
Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE reason = 'rebuilt from the broker'", r => r.Id("id")), "Interrupted after the orders.");
|
||||
Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value, "The protection comes before the first row.");
|
||||
|
||||
// One of them was cut right after its row: it still has no state.
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET status = 'created', filled_quantity = 0 WHERE reason = 'rebuilt from the broker' AND purpose <> 'stop'", _none), _none);
|
||||
|
||||
// The last execution made it into the ledger: what comes before it is still to be read.
|
||||
var last = (await a.Paper.GetFillsAsync(DateTimeOffset.MinValue, _none)).MaxBy(f => f.ExecutedAt)!;
|
||||
await rig.Ledger.RecordFillAsync(new LedgerFill(a.Context.AccountId, a.Eth.Id, StrategyNames.CryptoTrend, last.ExecutionId, last.Side, last.Quantity, last.Price, last.Fee,
|
||||
@@ -333,6 +336,7 @@ public sealed class RestoreTests
|
||||
// The next attempt knows every order already, and finishes all the same.
|
||||
await service.RebuildAsync(manager, _none);
|
||||
await a.SameLedgerAsync(rig, "The ledger is the one that was lost, stops included.");
|
||||
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE status = 'created'", r => r.Id("id")), "Every rebuilt order has the state the broker says.");
|
||||
await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none);
|
||||
await manager.AlignStopsAsync(_none);
|
||||
CollectionAssert.AreEqual(stops, (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList(), "No stop was touched.");
|
||||
@@ -474,14 +478,31 @@ public sealed class RestoreTests
|
||||
|
||||
await using var restored = await rig.RestoreAsync(archive);
|
||||
await Installation.RenewAsync(restored.Db, new DataDirectory(Path.Combine(folder, "data")), restored.Clock, "Salvataggio ripristinato", _none);
|
||||
var again = restored.Manager(broker, context, splits: SplitsAsync);
|
||||
var asked = new List<(string Symbols, DateOnly Since)>();
|
||||
var photographs = new List<decimal>();
|
||||
var down = true;
|
||||
var again = restored.Manager(broker, context, splits: async (i, ct) => down ? [] : await SplitsAsync(i, ct), refreshSplits: (symbols, since, _) =>
|
||||
{
|
||||
asked.Add((string.Join(',', symbols), since));
|
||||
return down ? throw new MarketDataException("rete giù") : Task.CompletedTask;
|
||||
}, afterFills: async ct => photographs.Add((await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, ct))!.Quantity));
|
||||
again.AwaitingRebuild = true;
|
||||
again.StopGeneration = restored.Clock.UtcNow.UtcTicks;
|
||||
var known = await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id"));
|
||||
await Assert.ThrowsExactlyAsync<MarketDataException>(() => again.RebuildAsync(_none));
|
||||
Assert.IsTrue(again.AwaitingRebuild, "Without the splits nothing is replayed.");
|
||||
Assert.HasCount(known.Count, await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id")));
|
||||
down = false;
|
||||
var report = await again.RebuildAsync(_none);
|
||||
Assert.AreEqual(2, asked.Count(a => a == ("MSFT", new DateOnly(2026, 11, 9))), "Back to a day before the last execution of the archive.");
|
||||
CollectionAssert.AreEqual(new[] { 22m }, photographs, "One photograph, when every split is in its place.");
|
||||
Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear));
|
||||
var position = (await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!;
|
||||
Assert.AreEqual((22m, 180m), (position.Quantity, position.StopPrice));
|
||||
Assert.IsEmpty(await restored.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_refused_fill'", r => r.Text("message")));
|
||||
Assert.HasCount(1, await restored.QueryAsync("SELECT id FROM applied_actions WHERE source_key = 'split-msft'", r => r.Id("id")));
|
||||
await again.RebuildAsync(_none);
|
||||
Assert.HasCount(2, asked, "Nothing new to write: no need to ask.");
|
||||
var reconciled = await new Reconciler(restored.Db, restored.Clock, restored.Ledger).ReconcileAsync(again, _none);
|
||||
Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message)));
|
||||
}
|
||||
@@ -491,12 +512,261 @@ public sealed class RestoreTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task StoppingAnAccountNotRebuiltYetKeepsTheStopOfAPurchase()
|
||||
{
|
||||
// The purchase filled and the engine died before reading it; "Ferma tutto" comes while the account waits.
|
||||
await using var a = await Account.OpenAsync();
|
||||
a.Rig.Refresh();
|
||||
await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 57_000m, StartAggressive = true }, _none);
|
||||
a.Broker.FailFillsAt = 2;
|
||||
await Assert.ThrowsExactlyAsync<BrokerException>(() => a.Manager.TickAsync(_none));
|
||||
a.Rig.Refresh();
|
||||
await a.Paper.PumpAsync(_none);
|
||||
|
||||
var manager = a.Rig.Manager(a.Broker, a.Context);
|
||||
manager.AwaitingRebuild = true;
|
||||
Assert.IsEmpty(await manager.CancelWorkingAsync("manual_stop"));
|
||||
await manager.RebuildAsync(_none);
|
||||
Assert.HasCount(1, await manager.CancelWorkingAsync(LiveReasons.Restart));
|
||||
Assert.AreEqual(57_000m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice);
|
||||
Assert.AreEqual(57_000m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ExecutionsOfWhileTheBotWasOffComeBeforeTheSplitsAndTheDividends()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync();
|
||||
var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo);
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT"));
|
||||
var nvda = await rig.InstrumentAsync(TradingRig.Stock("NVDA"));
|
||||
var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false);
|
||||
await paper.DepositAsync(100_000m, "USD", _none);
|
||||
await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none);
|
||||
var broker = new FaultyBroker(paper, TradingEnvironments.Demo);
|
||||
using var service = Service(rig);
|
||||
Task<IReadOnlyList<CorporateAction>> SplitsAsync(Instrument i, CancellationToken ct) => rig.Db.ReadAsync<IReadOnlyList<CorporateAction>>(async s =>
|
||||
[.. await s.QueryAsync("SELECT source_key FROM corporate_actions WHERE symbol = @s AND kind = 'split'", r => new CorporateAction(i.Symbol, "split", new DateOnly(2026, 11, 12), "test", r.Text("source_key")) { Ratio = 10m }, ("s", i.Symbol))], ct);
|
||||
OrderManager Manager() => rig.Manager(broker, context, splits: SplitsAsync);
|
||||
async Task TurnsAsync(OrderManager manager)
|
||||
{
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
rig.Refresh();
|
||||
await paper.PumpAsync(_none);
|
||||
await manager.TickAsync(_none);
|
||||
rig.Clock.Advance(_minute);
|
||||
}
|
||||
}
|
||||
|
||||
Task<(Guid?, string?)> BuyAsync(OrderManager manager, Instrument instrument, decimal quantity) => manager.SubmitAsync(
|
||||
new TradeIntent(instrument.Id, StrategyNames.EquityMomentum, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none);
|
||||
|
||||
// 10 MSFT with their stop; NVDA bought and sold before, then bought again: filled, and the engine dies before reading it.
|
||||
rig.Quote("MSFT", 399.9m, 400m);
|
||||
rig.Quote("NVDA", 399.9m, 400m);
|
||||
var first = Manager();
|
||||
await BuyAsync(first, msft, 10m);
|
||||
await TurnsAsync(first);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD"), _none);
|
||||
await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD"), _none);
|
||||
rig.Clock.Advance(_minute);
|
||||
await BuyAsync(first, nvda, 10m);
|
||||
broker.FailFillsAt = 2;
|
||||
await Assert.ThrowsExactlyAsync<BrokerException>(() => first.TickAsync(_none));
|
||||
rig.Refresh();
|
||||
await paper.PumpAsync(_none);
|
||||
|
||||
// Off: the stop of MSFT fires on Wednesday; Thursday, 10-for-1 for both and a dividend of MSFT.
|
||||
rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||
rig.Quote("MSFT", 350m, 350.1m);
|
||||
await paper.PumpAsync(_none);
|
||||
rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||
rig.Quote("MSFT", 35m, 35.01m);
|
||||
rig.Quote("NVDA", 40m, 40.01m);
|
||||
await rig.Db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (symbol, kind, ratio, cash) in new[] { ("MSFT", "split", (decimal?)10m, (decimal?)null), ("NVDA", "split", 10m, null), ("MSFT", "cash_dividend", null, 1m) })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, @s, @k, '2026-11-12', @r, @c, 'USD', 'test', @key, @now)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("s", symbol), ("k", kind), ("r", ratio), ("c", cash), ("key", kind + symbol), ("now", rig.Clock.UtcNow));
|
||||
}
|
||||
}, _none);
|
||||
|
||||
var second = Manager();
|
||||
second.AwaitingRebuild = true;
|
||||
|
||||
var report = await second.RebuildAsync(_none);
|
||||
Assert.AreEqual(0, report.Orders);
|
||||
await service.CorporateActionsAsync(second, _none);
|
||||
Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))?.Quantity ?? 0m, "The stop sold the 10 old shares.");
|
||||
Assert.AreEqual(100m, (await rig.Ledger.PositionAsync(context.AccountId, nvda.Id, StrategyNames.EquityMomentum, _none))!.Quantity, "The purchase finds its split.");
|
||||
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")), "Sold before the ex-date: nothing is owed.");
|
||||
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id")));
|
||||
Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill' AND message LIKE '%Vend%MSFT%'", r => r.Id("id")), "The sale of the stop reaches the phone.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task TheRestOfAStopThatFiredInPartWhileOffIsSold()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync();
|
||||
var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo);
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT"));
|
||||
var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false);
|
||||
await paper.DepositAsync(100_000m, "USD", _none);
|
||||
await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none);
|
||||
var broker = new FaultyBroker(paper, TradingEnvironments.Demo);
|
||||
var first = rig.Manager(broker, context);
|
||||
rig.Quote("MSFT", 399.9m, 400m);
|
||||
await first.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 1.5m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none);
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
rig.Refresh();
|
||||
await paper.PumpAsync(_none);
|
||||
await first.TickAsync(_none);
|
||||
rig.Clock.Advance(_minute);
|
||||
}
|
||||
|
||||
// The stop of the fraction is a day order and is over; that of the whole share fires while the bot is off.
|
||||
var stops = await paper.GetOpenOrdersAsync(_none);
|
||||
Assert.HasCount(2, stops);
|
||||
await paper.CancelOrderAsync(stops.Single(o => o.Quantity == 0.5m).ClientOrderId, "MSFT", _none);
|
||||
rig.Clock.Advance(TimeSpan.FromHours(1));
|
||||
rig.Quote("MSFT", 350m, 350.1m);
|
||||
await paper.PumpAsync(_none);
|
||||
|
||||
var second = rig.Manager(broker, context);
|
||||
second.AwaitingRebuild = true;
|
||||
await second.RebuildAsync(_none);
|
||||
Assert.AreEqual(0.5m, (await rig.QueryAsync("SELECT quantity FROM executions WHERE purpose = 'protective' AND status = 'working'", r => r.Money("quantity"))).Single());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task TheProtectiveSalesOfTheArchiveAreNotContinued()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none);
|
||||
var simulated = await a.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation);
|
||||
await a.Rig.Manager(a.Rig.Paper(PaperOptions.Okx(), simulated.AccountId, persist: false), simulated)
|
||||
.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none);
|
||||
var (rig, _) = await a.RestoreAsync(await a.ArchiveAsync());
|
||||
async Task<string> StatusAsync(Guid account) => (await rig.QueryAsync("SELECT status FROM executions WHERE account_id = @a AND purpose = 'protective'", r => r.Text("status"), ("a", account))).Single();
|
||||
Assert.AreEqual(ExecutionStates.Canceled, await StatusAsync(a.Context.AccountId));
|
||||
Assert.AreEqual(ExecutionStates.Working, await StatusAsync(simulated.AccountId), "The simulator went back in time with its sales.");
|
||||
|
||||
// One of an execution that is over, still open on the account, is canceled there too.
|
||||
a.Rig.Refresh();
|
||||
await a.Manager.CancelWorkingAsync("prova");
|
||||
await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none);
|
||||
await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.004m, OrderPurpose.Exit, Ids.NewId(a.Rig.Clock)), _none);
|
||||
await a.Manager.TickAsync(_none);
|
||||
Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList());
|
||||
await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none);
|
||||
await a.Rig.Manager(a.Broker, a.Context).RebuildAsync(_none);
|
||||
Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ProtectionFromTheLoopStopsTheOtherAccountsAndKeepsWhatIsOfToday()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
await a.SellAsync(a.Btc, 0.003m);
|
||||
|
||||
foreach (var (asked, kept) in new[] { ("2026-11-07T10:00:00+00:00", false), ("2026-12-31T10:00:00+00:00", true) })
|
||||
{
|
||||
var rig = await a.Rig.RestoreAsync(archive);
|
||||
a.Restored.Add(rig);
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none);
|
||||
using var service = Service(rig);
|
||||
await service.StartAsync(_none);
|
||||
var simulator = service.Managers.Single(m => m.Account.Broker == Venues.Okx);
|
||||
rig.Clock.Advance(_minute);
|
||||
var (buy, _) = await simulator.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(rig.Clock)), _none);
|
||||
await AskCloseAllAsync(rig, asked);
|
||||
var manager = rig.Manager(a.Broker, a.Context);
|
||||
await service.RebuildAsync(manager, _none);
|
||||
Assert.AreEqual(ExecutionStates.Canceled, (await rig.QueryAsync("SELECT status FROM executions WHERE id = @id", r => r.Text("status"), ("id", buy))).Single());
|
||||
var state = (await rig.QueryAsync("SELECT state FROM risk_state WHERE world = 'bot'", r => r.Json("state").Text)).Single();
|
||||
Assert.AreEqual(kept, System.Text.Json.JsonDocument.Parse(state).RootElement.GetProperty("close_all").GetBoolean(), asked);
|
||||
Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message")));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AnAttemptCutRightAfterTheProtectionStillNamesTheStopsAnew()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
await a.SellAsync(a.Btc, 0.003m);
|
||||
var rig = await a.Rig.RestoreAsync(archive);
|
||||
a.Restored.Add(rig);
|
||||
await Installation.ProtectAsync(rig.Db, rig.Clock, rig.Clock.UtcNow, "prova", _none);
|
||||
using var service = Service(rig);
|
||||
var manager = rig.Manager(a.Broker, a.Context);
|
||||
await service.RebuildAsync(manager, _none);
|
||||
Assert.AreEqual((await Installation.ReadRowAsync(rig.Db, _none))!.RenewedAt.UtcTicks, manager.StopGeneration);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AResumedRebuildOfTheGuardsStopsDoesNotStopTheBot()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single();
|
||||
await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none);
|
||||
Task PlaceAsync(int sequence) => a.Paper.SubmitOrderAsync(new OrderRequest(ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend,
|
||||
OrderPurpose.Stop, "GGGGGGGG", sequence), a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity / 2m, TimeInForce.Gtc)
|
||||
{ StopPrice = 57_000m }, _none);
|
||||
using var service = Service(a.Rig);
|
||||
await PlaceAsync(1);
|
||||
a.Broker.FailFillsAt = 2;
|
||||
await Assert.ThrowsExactlyAsync<BrokerException>(() => service.RebuildAsync(a.Manager, _none));
|
||||
await PlaceAsync(2);
|
||||
await service.RebuildAsync(a.Manager, _none);
|
||||
Assert.IsFalse((await Installation.ReadRowAsync(a.Rig.Db, _none))!.ProtectedRestart);
|
||||
Assert.IsEmpty(await a.Rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task TheGuardCountsFromTheMomentTheFiguresOfTheAccountWereRead()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var known = await a.Manager.GuardAccountAsync(_none);
|
||||
var read = a.Rig.Clock.UtcNow;
|
||||
a.Rig.Clock.Advance(_minute);
|
||||
await a.SellAsync(a.Btc, 0.004m);
|
||||
var held = (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||
await a.Paper.SubmitOrderAsync(new OrderRequest("a-mano", a.Btc.Symbol, OrderSide.Buy, OrderKind.Market, 0.5m, TimeInForce.Gtc), _none);
|
||||
await a.TurnsAsync(a.Manager, 2);
|
||||
foreach (var stop in await a.Paper.GetOpenOrdersAsync(_none))
|
||||
{
|
||||
await a.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none);
|
||||
}
|
||||
|
||||
var state = new Anubis.Supervision.GuardState(a.Rig.Clock.UtcNow, TradingRig.Installation, [known with { WrittenAt = read }]);
|
||||
var outcome = await Anubis.Supervision.GuardRepair.RunAsync(state, state.Accounts[0], a.Broker, a.Rig.Clock, _none);
|
||||
Assert.AreEqual(held, outcome.Placed.Single().Quantity, "What was sold after the figures, not what the user holds.");
|
||||
}
|
||||
|
||||
private static TradingService Service(TradingRig rig) => new(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock),
|
||||
TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp());
|
||||
|
||||
private static Task<int> AskCloseAllAsync(TradingRig rig) => rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
private static Task<int> AskCloseAllAsync(TradingRig rig, string since = "2026-11-07T10:00:00+00:00") => rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'bot', @j, @t, @t)", _none,
|
||||
("id", Ids.NewId(rig.Clock)), ("j", new DbJson("{\"close_all\":true,\"close_all_since\":\"2026-11-07T10:00:00+00:00\"}")), ("t", rig.Clock.UtcNow)), _none);
|
||||
("id", Ids.NewId(rig.Clock)), ("j", new DbJson($"{{\"close_all\":true,\"close_all_since\":\"{since}\"}}")), ("t", rig.Clock.UtcNow)), _none);
|
||||
|
||||
private static async Task<int> CloseAllAsync(TradingRig rig, OrderManager manager)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user