diff --git a/tests/Anubis.Tests/BrokerConformanceTests.cs b/tests/Anubis.Tests/BrokerConformanceTests.cs new file mode 100644 index 0000000..f3f7cc0 --- /dev/null +++ b/tests/Anubis.Tests/BrokerConformanceTests.cs @@ -0,0 +1,368 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// What a conformance run needs: the adapter, an order far from the market and the account's currency. +internal sealed record ConformanceVenue(IBrokerAccount Broker, OrderRequest FarBuy, string Currency, IAsyncDisposable? Owner = null); + +/// +/// The conformance battery (issue #31, SPEC 5.3): every adapter keeps the same contract, so the order manager and +/// reconciliation work the same on the internal simulator, on the brokers' documentation samples and, when the +/// user has given demo keys, on the real demo accounts. Each venue is a subclass that only says how to open it. +/// +public abstract class BrokerConformance +{ + protected static readonly CancellationToken None = CancellationToken.None; + + /// Opens the venue; is the id the battery's order will carry. + internal abstract Task OpenAsync(string clientOrderId); + + /// The documentation's sample key may withdraw: the adapter must say so, never hide it. + protected virtual bool KeyMayWithdraw => false; + + protected abstract string Environment { get; } + + private string ClientId() => + ClientOrderIds.Build(TradingRig.Installation, Environment, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1); + + [TestMethod] + public async Task TheVenueAnswersWithItsTimeAndItsCash() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + Assert.IsGreaterThan(2019, (await venue.Broker.ServerTimeAsync(None).ConfigureAwait(false)).Year); + var account = await venue.Broker.GetAccountAsync(None).ConfigureAwait(false); + Assert.AreEqual(venue.Currency, account.Currency); + Assert.IsTrue(account.Cash.Values.All(c => c >= 0m), "Cash is never negative on an account without leverage."); + Assert.IsTrue(account.BuyingPower is null or >= 0m); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task AnOrderKeepsItsClientIdFromSendToCancel() + { + var id = ClientId(); + var venue = await OpenAsync(id).ConfigureAwait(false); + try + { + var request = venue.FarBuy with { ClientOrderId = id }; + var sent = await venue.Broker.SubmitOrderAsync(request, None).ConfigureAwait(false); + Assert.AreEqual((id, request.Symbol, OrderSide.Buy, OrderKind.Limit), (sent.ClientOrderId, sent.Symbol, sent.Side, sent.Kind)); + Assert.IsTrue(sent.IsOpen, sent.Status.ToString()); + Assert.IsFalse(string.IsNullOrEmpty(sent.BrokerOrderId)); + + var read = await venue.Broker.GetOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + Assert.AreEqual((id, request.Quantity, request.LimitPrice), (read!.ClientOrderId, read.Quantity, read.LimitPrice)); + Assert.IsTrue(read.IsOpen); + Assert.Contains(id, (await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)).Select(o => o.ClientOrderId).ToList()); + + await venue.Broker.CancelOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + var canceled = await venue.Broker.GetOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + Assert.AreEqual(OrderStatus.Canceled, canceled!.Status); + Assert.DoesNotContain(id, (await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)).Select(o => o.ClientOrderId).ToList()); + + // Canceling again, or an order the venue never saw, is not an error: the caller reads the order next. + await venue.Broker.CancelOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + var unknown = id[..^1] + (id[^1] == '9' ? '8' : '9'); + Assert.IsNull(await venue.Broker.GetOrderAsync(unknown, request.Symbol, None).ConfigureAwait(false)); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task OrdersPositionsAndFillsAreWellFormed() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + foreach (var order in await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(order.Symbol)); + Assert.IsTrue(order.Quantity > 0m && order.Remaining >= 0m && order.Remaining <= order.Quantity, order.ClientOrderId); + Assert.IsTrue(order.IsOpen); + } + + foreach (var position in await venue.Broker.GetPositionsAsync(None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(position.Symbol)); + Assert.IsGreaterThan(0m, position.Quantity, position.Symbol); + } + + foreach (var fill in await venue.Broker.GetFillsAsync(DateTimeOffset.UnixEpoch, None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(fill.ExecutionId)); + Assert.IsTrue(fill.Quantity > 0m && fill.Price > 0m, fill.ExecutionId); + Assert.IsGreaterThanOrEqualTo(0m, fill.Fee, "A fee is a cost: the adapter turns the venue's sign around."); + Assert.IsFalse(string.IsNullOrEmpty(fill.FeeCurrency)); + } + + foreach (var activity in await venue.Broker.GetCashActivitiesAsync(DateTimeOffset.UnixEpoch, None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(activity.Id)); + } + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task TheKeyTellsWhatItMayDo() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + var key = await venue.Broker.GetKeyPermissionsAsync(None).ConfigureAwait(false); + Assert.AreEqual((true, true, KeyMayWithdraw), (key.CanRead, key.CanTrade, key.CanWithdraw)); + Assert.IsFalse(string.IsNullOrWhiteSpace(key.Description)); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + private static async Task DisposeAsync(ConformanceVenue venue) + { + if (venue.Owner is not null) + { + await venue.Owner.DisposeAsync().ConfigureAwait(false); + } + } +} + +/// The internal simulator. +[TestClass] +[TestCategory(Category.Simulation)] +public sealed class PaperBrokerConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Simulation; + + internal override async Task OpenAsync(string clientOrderId) + { + var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + rig.Quote("BTC-EUR", 60000m, 60010m); + var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); + await paper.DepositAsync(10_000m, "EUR", None).ConfigureAwait(false); + + // Something held and something filled, so the shapes are checked on real content. + await paper.SubmitOrderAsync(new OrderRequest("seed-buy", "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Gtc), None).ConfigureAwait(false); + await paper.PumpAsync(None).ConfigureAwait(false); + return new ConformanceVenue(paper, new OrderRequest(clientOrderId, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 30000m }, "EUR", rig); + } +} + +/// +/// Alpaca's trading API on the samples of its documentation (Fixtures/alpaca-trading), with the order's state +/// following what the adapter does: open after the send, canceled after the DELETE. +/// +[TestClass] +[TestCategory(Category.Unit)] +public sealed class AlpacaDocConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var order = JsonNode.Parse(Fixture.Text("alpaca-trading/order-limit.json"))!.AsObject(); + order["client_order_id"] = clientOrderId; + var brokerId = order["id"]!.GetValue(); + var placed = false; + var canceled = false; + string Order() => Status(order, !placed ? "unknown" : canceled ? "canceled" : "accepted"); + + // The fill's order, as the orders list of the same period shows it. + var filledOrder = JsonNode.Parse(Fixture.Text("alpaca-trading/order-limit.json"))!.AsObject(); + filledOrder["id"] = JsonNode.Parse(Fixture.Text("alpaca-trading/activity-fill.json"))!["order_id"]!.GetValue(); + filledOrder["client_order_id"] = "manual-order"; + + var http = new FakeHttp() + .On("/v2/clock", Fixture.Text("alpaca/clock-v2.json")) + .On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json"))) + .On("/v2/positions", "[" + Fixture.Text("alpaca-trading/position.json") + "]") + .On(u => u.AbsolutePath.StartsWith("/v2/orders:by_client_order_id", StringComparison.Ordinal), r => + placed && r.RequestUri!.Query.Contains(Uri.EscapeDataString(clientOrderId), StringComparison.Ordinal) + ? FakeHttp.Respond(Order()) + : FakeHttp.Respond("{\"code\":40410000,\"message\":\"order not found\"}", HttpStatusCode.NotFound)) + .On(u => u.AbsolutePath == "/v2/orders/" + brokerId, r => + { + canceled = r.Method == HttpMethod.Delete || canceled; + return r.Method == HttpMethod.Delete ? new HttpResponseMessage(HttpStatusCode.NoContent) : FakeHttp.Respond(Order()); + }) + .On(u => u.AbsolutePath == "/v2/orders", r => + { + if (r.Method == HttpMethod.Post) + { + placed = true; + return FakeHttp.Respond(Order()); + } + + var query = r.RequestUri!.Query; + return FakeHttp.Respond(query.Contains("status=open", StringComparison.Ordinal) + ? (placed && !canceled ? "[" + Order() + "]" : "[]") + : "[" + filledOrder.ToJsonString() + "]"); + }) + .On(u => u.AbsolutePath == "/v2/account/activities", r => FakeHttp.Respond(r.RequestUri!.Query.Contains("FILL", StringComparison.Ordinal) + ? "[" + Fixture.Text("alpaca-trading/activity-fill.json") + "]" + : "[" + Fixture.Text("alpaca-trading/activity-div.json") + "]")); + var adapter = new AlpacaTrading(http.Client(), new ManualClock(TradingRig.Start), new AlpacaCredentials("doc-key-id", "doc-secret"), + new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "AAPL", OrderSide.Buy, OrderKind.Limit, 2m, TimeInForce.Gtc) { LimitPrice = 150m }, "USD")); + } + + private static string Status(JsonObject order, string status) + { + var copy = order.DeepClone().AsObject(); + copy["status"] = status; + return copy.ToJsonString(); + } +} + +/// OKX Europe on the samples of its documentation (Fixtures/okx-trading), in USDT as the samples are. +[TestClass] +[TestCategory(Category.Unit)] +public sealed class OkxDocConformance : BrokerConformance +{ + /// The documentation's account configuration lists withdraw among the key's permissions. + protected override bool KeyMayWithdraw => true; + + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var pending = JsonNode.Parse(Fixture.Text("okx-trading/orders-pending.json"))!["data"]![0]!.AsObject(); + pending["clOrdId"] = clientOrderId; + var placed = false; + var canceled = false; + string Order() => Envelope(Status(pending, canceled ? "canceled" : "live")); + + var http = new FakeHttp() + .On("/api/v5/public/time", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"ts\":\"1597026383085\"}]}") + .On("/api/v5/account/balance", Fixture.Text("okx-trading/balance.json")) + .On("/api/v5/account/config", Fixture.Text("okx-trading/account-config.json")) + .On(u => u.AbsolutePath == "/api/v5/trade/orders-pending", _ => FakeHttp.Respond(placed && !canceled ? Envelope(pending.ToJsonString()) : "{\"code\":\"0\",\"msg\":\"\",\"data\":[]}")) + .On("/api/v5/trade/orders-algo-pending", Fixture.Text("okx-trading/algos-pending.json")) + .On(u => u.AbsolutePath == "/api/v5/trade/order", r => + { + if (r.Method == HttpMethod.Post) + { + placed = true; + return FakeHttp.Respond(Fixture.Text("okx-trading/order-placed.json").Replace("oktswap6", clientOrderId, StringComparison.Ordinal)); + } + + var query = r.RequestUri!.Query; + if (query.Contains("ordId=", StringComparison.Ordinal) && !query.Contains("clOrdId=", StringComparison.Ordinal)) + { + return FakeHttp.Respond(Fixture.Text("okx-trading/order-filled.json")); + } + + return placed && query.Contains("clOrdId=" + clientOrderId, StringComparison.Ordinal) + ? FakeHttp.Respond(Order()) + : FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}"); + }) + .On(u => u.AbsolutePath == "/api/v5/trade/cancel-order", _ => + { + var already = canceled; + canceled = true; + return FakeHttp.Respond(already + ? "{\"code\":\"1\",\"msg\":\"\",\"data\":[{\"clOrdId\":\"" + clientOrderId + "\",\"ordId\":\"\",\"sCode\":\"51400\",\"sMsg\":\"Order cancellation failed as the order has been filled, canceled or does not exist\"}]}" + : Fixture.Text("okx-trading/order-canceled.json").Replace("oktswap6", clientOrderId, StringComparison.Ordinal)); + }) + .On("/api/v5/trade/fills", Fixture.Text("okx-trading/fills.json")); + var adapter = new OkxTrading(http.Client(), new ManualClock(TradingRig.Start), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), + new OkxTradingOptions { Environment = TradingEnvironments.Demo, QuoteCurrency = "USDT" }, TradingConsent.None); + var px = decimal.Parse(pending["px"]!.GetValue(), System.Globalization.CultureInfo.InvariantCulture); + var sz = decimal.Parse(pending["sz"]!.GetValue(), System.Globalization.CultureInfo.InvariantCulture); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, pending["instId"]!.GetValue(), OrderSide.Buy, OrderKind.Limit, sz, TimeInForce.Gtc) { LimitPrice = px }, "USDT")); + } + + private static string Status(JsonObject order, string state) + { + var copy = order.DeepClone().AsObject(); + copy["state"] = state; + copy["ordType"] = "limit"; + return copy.ToJsonString(); + } + + private static string Envelope(string item) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + item + "]}"; +} + +/// +/// The same battery on the real demo accounts, with the keys the user puts in the environment. Without them the +/// tests are inconclusive: the criterion is waiting for the user (issue #31). Never a live account (SPEC 2.2). +/// +[TestClass] +[TestCategory(Category.LiveDemo)] +public sealed class AlpacaPaperConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var key = System.Environment.GetEnvironmentVariable("ALPACA_API_KEY_DEMO"); + var secret = System.Environment.GetEnvironmentVariable("ALPACA_API_SECRET_DEMO"); + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret)) + { + Assert.Inconclusive("In attesa dell'utente: servono le chiavi del conto paper di Alpaca."); + } + + var http = new HttpClient(); + var adapter = new AlpacaTrading(http, SystemClock.Instance, new AlpacaCredentials(key, secret), new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "AAPL", OrderSide.Buy, OrderKind.Limit, 1m, TimeInForce.Day) { LimitPrice = 1m }, "USD", new HttpOwner(http))); + } +} + +/// The battery on the OKX Europe demo account, with the user's demo keys. +[TestClass] +[TestCategory(Category.LiveDemo)] +public sealed class OkxDemoConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var key = System.Environment.GetEnvironmentVariable("OKX_API_KEY_DEMO"); + var secret = System.Environment.GetEnvironmentVariable("OKX_API_SECRET_DEMO"); + var passphrase = System.Environment.GetEnvironmentVariable("OKX_API_PASSPHRASE_DEMO"); + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(passphrase)) + { + Assert.Inconclusive("In attesa dell'utente: servono le chiavi del conto demo di OKX."); + } + + var http = new HttpClient(); + var adapter = new OkxTrading(http, SystemClock.Instance, new OkxCredentials(key, secret, passphrase), new OkxTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.0001m, TimeInForce.Gtc) { LimitPrice = 10000m }, "EUR", new HttpOwner(http))); + } +} + +internal sealed class HttpOwner(HttpClient http) : IAsyncDisposable +{ + public ValueTask DisposeAsync() + { + http.Dispose(); + return ValueTask.CompletedTask; + } +} diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs new file mode 100644 index 0000000..00830df --- /dev/null +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -0,0 +1,141 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The trading service (issues #26, #28, #29): accounts, the simulator's money, corporate actions. +[TestClass] +public sealed class TradingServiceTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + private static TradingService Service(TradingRig rig, FakeHttp http, IReadOnlyDictionary? 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> 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[] + { + (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), + (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), + (Strategies.EquityMomentum, "Alpaca simulatore", Strategies.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(3, 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, Strategies.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[] + { + (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), + (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), + (Strategies.EquityMomentum, "Alpaca paper", Strategies.Observation), + }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is."); + } + + [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 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 ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { (Strategies.CryptoTrend, 1000m), (Strategies.EquityMeanrev, 550m), (Strategies.EquityMomentum, 1650m) }, shares.ToArray()); + } + + [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, Strategies.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + await service.Ledger.RecordFillAsync(rig.Fill(account, msft, Strategies.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. + 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") }) + { + 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> 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."); + + 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, Strategies.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, Strategies.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); + } +}