Files
Anubis/tests/Anubis.Tests/TradingServiceTests.cs
T
Alby96andClaude Opus 5.5 5ef54b6f2a 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>
2026-12-01 22:15:34 +01:00

193 lines
14 KiB
C#

using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The trading service (issues #26, #28, #29): accounts, the simulator's money, corporate actions.</summary>
[TestClass]
public sealed class TradingServiceTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static TradingService Service(TradingRig rig, FakeHttp http, IReadOnlyDictionary<string, string>? keys = null) =>
new(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32], keys), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None,
new Guid("0193a7c0-0000-7000-8000-0000000000aa"), http);
private static Task<IReadOnlyList<(string Strategy, string Account, string Stage)>> StrategiesAsync(TradingRig rig) =>
rig.QueryAsync("SELECT s.strategy, a.name, s.stage FROM strategy_state s JOIN accounts a ON a.id = s.account_id ORDER BY s.strategy",
r => (r.Text("strategy"), r.Text("name"), r.Text("stage")));
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WithoutKeysBothSimulatorsRunAndNothingLeavesTheHouse()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var http = new FakeHttp();
using var service = Service(rig, http);
await service.StartAsync(_none).ConfigureAwait(false);
var accounts = await rig.QueryAsync("SELECT name, environment FROM accounts ORDER BY name", r => (r.Text("name"), r.Text("environment"))).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { ("Alpaca simulatore", "simulation"), ("OKX simulatore", "simulation") }, accounts.ToArray());
Assert.HasCount(2, service.Managers);
Assert.IsTrue(service.Managers.All(m => m.Broker is PaperBroker));
Assert.IsEmpty(http.Requests, "No keys, no requests.");
// Every strategy starts in observation, crypto on OKX and stocks on Alpaca.
CollectionAssert.AreEqual(new[]
{
(StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray());
// A second start finds what is there.
using var again = Service(rig, http);
await again.StartAsync(_none).ConfigureAwait(false);
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM accounts", r => r.Id("id")).ConfigureAwait(false));
Assert.HasCount(5, await StrategiesAsync(rig).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task StockStrategiesMoveToThePaperAccountOnlyWhileTheirLedgerIsEmpty()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none).ConfigureAwait(false);
var simulator = accounts.Single(a => a.Broker == Venues.Alpaca);
await rig.Ledger.RecordCapitalAsync(simulator.AccountId, StrategyNames.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false);
accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: true, okxDemo: false, _none).ConfigureAwait(false);
Assert.HasCount(3, accounts);
Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2).");
CollectionAssert.AreEqual(new[]
{
(StrategyNames.CryptoRelativeMomentum, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca paper", StrategyNames.Observation),
(StrategyNames.StockAthBreakout, "Alpaca simulatore", StrategyNames.Observation),
}, (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()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false);
using var service = Service(rig, new FakeHttp());
await service.StartAsync(_none).ConfigureAwait(false);
await service.SetCapitalAsync(Venues.Okx, 1000m, "test", _none).ConfigureAwait(false);
var alpaca = await service.SetCapitalAsync(Venues.Alpaca, 2000m, "test", _none).ConfigureAwait(false);
Assert.AreEqual((2200m, 1.10m), (alpaca.Amount, alpaca.FxRate));
await service.FundSimulatorsAsync(_none).ConfigureAwait(false);
async Task<decimal> BookAsync(string broker, string currency)
{
var paper = (PaperBroker)service.Managers.Single(m => m.Account.Broker == broker).Broker;
return (await paper.GetAccountAsync(_none).ConfigureAwait(false)).Cash.GetValueOrDefault(currency);
}
Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false));
Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call.");
var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state WHERE share > 0 ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { (StrategyNames.CryptoTrend, 1000m), (StrategyNames.EquityMeanrev, 550m), (StrategyNames.EquityMomentum, 1650m) }, shares.ToArray());
// The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate.
await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 10), 1.05m, "ecb")], _none).ConfigureAwait(false);
Assert.AreEqual(2200m, (await service.SetCapitalAsync(Venues.Alpaca, 2000m, "test", _none).ConfigureAwait(false)).Amount);
Assert.AreEqual(3250m, (await service.SetCapitalAsync(Venues.Alpaca, 3000m, "test", _none).ConfigureAwait(false)).Amount);
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM capital_changes WHERE broker = 'alpaca'", r => r.Id("id")).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task DividendsAndSplitsReachTheLedgersOnce()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var http = new FakeHttp();
using var service = Service(rig, http);
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
await service.StartAsync(_none).ConfigureAwait(false);
var account = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca).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);
// Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. A split of last
// 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"),
("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,
("id", Ids.NewId(rig.Clock)), ("k", kind), ("d", day), ("r", ratio), ("c", cash), ("key", key), ("now", rig.Clock.UtcNow)).ConfigureAwait(false);
}
}, _none).ConfigureAwait(false);
Task<IReadOnlyList<decimal>> DividendsAsync() => rig.QueryAsync("SELECT amount FROM cash_ledger WHERE kind = 'dividend'", r => r.Money("amount"));
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
Assert.IsEmpty(await DividendsAsync().ConfigureAwait(false), "Nothing before the ex-date.");
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares.");
rig.Clock.Advance(TimeSpan.FromDays(1));
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { 7.5m }, (await DividendsAsync().ConfigureAwait(false)).ToArray());
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
rig.Clock.Advance(TimeSpan.FromDays(1));
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))!;
Assert.AreEqual((20m, 200m), (position.Quantity, position.AveragePrice));
Assert.HasCount(1, await DividendsAsync().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);
// 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);
Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
}
}