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
@@ -92,6 +92,10 @@ public sealed class TradingServiceTests
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, source, source_key, created_at) VALUES (@id, 'MSFT', 'split', '2026-11-11', @r, 'test', 'k', @now)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("r", 2m), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromDays(2));
|
||||
service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
|
||||
await service.PhotographAsync(_none).ConfigureAwait(false);
|
||||
Assert.AreEqual(400m, (await service.Ledger.PositionAsync(paper.Account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice,
|
||||
"Old shares at the price of the new ones would be a loss that is not there.");
|
||||
var before = http.Requests.Count;
|
||||
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
await service.ReconcileAllAsync(_none).ConfigureAwait(false);
|
||||
@@ -170,6 +174,10 @@ public sealed class TradingServiceTests
|
||||
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
|
||||
|
||||
rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||
service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
|
||||
await service.PhotographAsync(_none).ConfigureAwait(false);
|
||||
Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice,
|
||||
"The split is not applied yet: the photograph waits for it.");
|
||||
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!;
|
||||
@@ -189,4 +197,139 @@ public sealed class TradingServiceTests
|
||||
await service.PhotographAsync(_none).ConfigureAwait(false);
|
||||
Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheSimulatorsAbsenceMeetsASplitAtItsDate()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
using var service = Service(rig, new FakeHttp());
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
|
||||
await service.StartAsync(_none).ConfigureAwait(false);
|
||||
var manager = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca);
|
||||
var paper = (PaperBroker)manager.Broker;
|
||||
await paper.DepositAsync(10_000m, "USD", _none).ConfigureAwait(false);
|
||||
await service.Ledger.RecordCapitalAsync(manager.Account.AccountId, StrategyNames.EquityMomentum, 10_000m, "USD", "test", _none).ConfigureAwait(false);
|
||||
await manager.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none)
|
||||
.ConfigureAwait(false);
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
service.Quotes.Put(new Quote("MSFT", 399.9m, 400m, rig.Clock.UtcNow));
|
||||
await paper.PumpAsync(_none).ConfigureAwait(false);
|
||||
await manager.TickAsync(_none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromSeconds(20));
|
||||
}
|
||||
|
||||
Assert.HasCount(1, await paper.GetOpenOrdersAsync(_none).ConfigureAwait(false));
|
||||
|
||||
// Off. Wednesday it falls through the stop and comes back; Thursday 2-for-1 and a dividend.
|
||||
var day = new DateTimeOffset(2026, 11, 11, 16, 0, 0, TimeSpan.Zero);
|
||||
await new BarStore(rig.Db, rig.Clock).UpsertMinuteAsync(msft.Id, [new Bar(day, 365, 366, 350, 364, 1000), new Bar(day.AddDays(1), 199, 201, 198, 200, 1000)], "test", BarQuality.Ok, _none)
|
||||
.ConfigureAwait(false);
|
||||
await rig.Db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (kind, ratio, cash) in new[] { ("split", (decimal?)2m, (decimal?)null), ("cash_dividend", null, 1m) })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, 'MSFT', @k, '2026-11-12', @r, @c, 'USD', 'test', @k, @now)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("k", kind), ("r", ratio), ("c", cash), ("now", rig.Clock.UtcNow)).ConfigureAwait(false);
|
||||
}
|
||||
}, _none).ConfigureAwait(false);
|
||||
rig.Clock.Advance(TimeSpan.FromDays(3));
|
||||
await service.CatchUpAsync(manager, paper, _none).ConfigureAwait(false);
|
||||
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
|
||||
Assert.IsEmpty(await service.Ledger.PositionsAsync(manager.Account.AccountId, _none).ConfigureAwait(false), "The stop of before the split met the prices of before it.");
|
||||
Assert.IsEmpty(await paper.GetPositionsAsync(_none).ConfigureAwait(false));
|
||||
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task UntilItIsRebuiltTheGuardKeepsWhatItKnewOfAnAccount()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("guard-state");
|
||||
try
|
||||
{
|
||||
var paths = new Anubis.Supervision.GuardPaths(folder);
|
||||
var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{}", System.Net.HttpStatusCode.BadRequest));
|
||||
using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32],
|
||||
new Dictionary<string, string> { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" }), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None,
|
||||
new Guid("0193a7c0-0000-7000-8000-0000000000aa"), http)
|
||||
{ GuardFiles = paths };
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
|
||||
await service.StartAsync(_none).ConfigureAwait(false);
|
||||
var account = service.Managers.Single(m => m.Account.Environment == TradingEnvironments.Demo).Account;
|
||||
await service.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
|
||||
await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false);
|
||||
|
||||
// Nor is it valued at a price of today: the shares of the ledger may be those of another time.
|
||||
service.Quotes.Put(new Quote("MSFT", 200m, 200.10m, rig.Clock.UtcNow));
|
||||
await service.PhotographAsync(_none).ConfigureAwait(false);
|
||||
Assert.AreEqual(400m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
|
||||
async Task<(DateTimeOffset At, Anubis.Supervision.GuardAccount Account)> WrittenAsync()
|
||||
{
|
||||
await service.WriteGuardStateAsync(_none).ConfigureAwait(false);
|
||||
var state = Anubis.Supervision.GuardFiles.ReadState(paths)!;
|
||||
return (state.WrittenAt, state.Accounts.Single(a => a.AccountId == account.AccountId));
|
||||
}
|
||||
|
||||
Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions, "Nothing known: no stop is put on a ledger that may be old.");
|
||||
|
||||
// What the last state said, with its time, however often it is written again.
|
||||
var first = rig.Clock.UtcNow;
|
||||
var known = (await WrittenAsync().ConfigureAwait(false)).Account with { Positions = [new Anubis.Supervision.GuardPosition(msft.Id, "MSFT", StrategyNames.EquityMomentum, 4m, 380m, 0.0001m, false, "KKKKKKKK", 3)] };
|
||||
Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, service.InstallationCode, [known with { WrittenAt = null }]));
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
rig.Clock.Advance(TimeSpan.FromSeconds(10));
|
||||
var (at, again) = await WrittenAsync().ConfigureAwait(false);
|
||||
Assert.AreEqual(rig.Clock.UtcNow, at);
|
||||
Assert.AreEqual((4m, first), (again.Positions.Single().Quantity, again.WrittenAt!.Value));
|
||||
}
|
||||
|
||||
// Of another installation: not of this account's past.
|
||||
Anubis.Supervision.GuardFiles.WriteState(paths, new Anubis.Supervision.GuardState(first, "OTHR", [known]));
|
||||
Assert.IsEmpty((await WrittenAsync().ConfigureAwait(false)).Account.Positions);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task SplitsAndDividendsAreAskedAlsoForWhatLeftTheUniverse()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{\"corporate_actions\":{},\"next_page_token\":null}"));
|
||||
var bus = new EventBus();
|
||||
var secrets = new SecretStore(rig.Db, rig.Clock, new byte[32], new Dictionary<string, string> { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" });
|
||||
using var market = new MarketDataService(rig.Db, rig.Clock, bus, new SettingsStore(rig.Db, rig.Clock, bus), secrets, null, http);
|
||||
await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
Assert.IsEmpty(http.Requests, "Nothing to ask about.");
|
||||
|
||||
var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
|
||||
await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
|
||||
foreach (var (symbol, sold) in new[] { ("MSFT", false), ("NVDA", true), ("OLDX", true) })
|
||||
{
|
||||
var stock = await rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false);
|
||||
var buy = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD");
|
||||
var sell = rig.Fill(account, stock, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD");
|
||||
var at = rig.Clock.UtcNow - TimeSpan.FromDays(symbol == "OLDX" ? 120 : 30);
|
||||
await rig.Ledger.RecordFillAsync(buy with { ExecutedAt = at }, _none).ConfigureAwait(false);
|
||||
if (sold)
|
||||
{
|
||||
await rig.Ledger.RecordFillAsync(sell with { ExecutedAt = at.AddDays(1) }, _none).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await market.RefreshCorporateActionsAsync(_none).ConfigureAwait(false);
|
||||
StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNVDA&");
|
||||
StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-11-03&");
|
||||
await market.RefreshCorporateActionsAsync(["NEWX"], new DateOnly(2026, 10, 20), _none).ConfigureAwait(false);
|
||||
StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "symbols=MSFT%2CNEWX%2CNVDA&");
|
||||
StringAssert.Contains(http.Requests[^1].RequestUri!.Query, "start=2026-10-13&");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user