using Anubis.Core; using Anubis.Data; using Anubis.Trading; namespace Anubis.Tests; /// The bot's books (issue #29, SPEC 7.5): append-only rows, lots, trades from zero to zero, equity, returns. [TestClass] public sealed class LedgerTests { private static readonly CancellationToken _none = CancellationToken.None; [TestMethod] [TestCategory(Category.Integration)] public async Task BuyAndSellMakeATradeFromZeroToZeroWithFeesAndResult() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); const string strategy = StrategyNames.EquityMomentum; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false); var first = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 10m, 400m, 0.03m) with { ReferencePrice = 399.8m }, _none).ConfigureAwait(false); Assert.IsTrue(first.Recorded); Assert.AreEqual(10m, first.Quantity); Assert.AreEqual(400.003m, first.AveragePrice, "The fee is part of the cost."); Assert.AreEqual(Math.Round(0.2m / 399.8m * 10000m, 6), Math.Round(first.SlippageBp!.Value, 6), "Slippage against the reference, in basis points."); await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 5m, 412m), _none).ConfigureAwait(false); // A partial sale enters the realised result at once; the trade stays open. var partial = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 6m, 420m, 0.06m), _none).ConfigureAwait(false); Assert.AreEqual(9m, partial.Quantity); Assert.IsFalse(partial.TradeClosed); var last = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 9m, 430m, 0.09m) with { ExitReason = "stop" }, _none).ConfigureAwait(false); Assert.IsTrue(last.TradeClosed); Assert.AreEqual(0m, last.Quantity); Assert.IsNull(await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false), "A closed position is gone."); var trade = (await rig.QueryAsync("SELECT status, bought_quantity, sold_quantity, fees, realized, exit_reason FROM trades", r => (Status: r.Text("status"), Bought: r.Money("bought_quantity"), Sold: r.Money("sold_quantity"), Fees: r.Money("fees"), Realized: r.Money("realized"), Exit: r.TextOrNull("exit_reason"))) .ConfigureAwait(false)).Single(); Assert.AreEqual(("closed", 15m, 15m, 0.18m, "stop"), (trade.Status, trade.Bought, trade.Sold, trade.Fees, trade.Exit)); // Net result: money in minus money out, fees included. var expected = (6m * 420m) + (9m * 430m) - (10m * 400m) - (5m * 412m) - 0.18m; Assert.AreEqual(expected, trade.Realized); var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(); Assert.AreEqual(10000m + expected, equity.Equity); Assert.AreEqual(expected, equity.Result); // The same execution twice is recorded once (duplicate fills, SPEC 7.4). var fill = rig.Fill(account, msft, strategy, OrderSide.Buy, 1m, 400m); Assert.IsTrue((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded); Assert.IsFalse((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded); Assert.AreEqual(1m, (await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false))!.Quantity); // Never sells what the strategy does not hold. await Assert.ThrowsExactlyAsync(() => rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 2m, 400m), _none)).ConfigureAwait(false); } [TestMethod] [TestCategory(Category.Integration)] public async Task FeesTakenInTheCoinReduceTheQuantityAndLotsFollowTheTaxMethod() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); const string strategy = StrategyNames.CryptoTrend; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 5000m, "EUR", "test", _none).ConfigureAwait(false); // OKX keeps the fee of a purchase in the bought coin (SPEC 4.2): 0.01 bought, 0.00001 kept. var buy = await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 60000m, 0.00001m, "BTC"), _none).ConfigureAwait(false); Assert.AreEqual(0.00999m, buy.Quantity); Assert.AreEqual(Math.Round(600m / 0.00999m, 10), Math.Round(buy.AveragePrice, 10)); await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 62000m, 0.00001m, "BTC"), _none).ConfigureAwait(false); // LIFO (default): the newest lot leaves first. await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Sell, 0.005m, 63000m, 0.63m, "EUR"), _none).ConfigureAwait(false); var lots = await rig.Ledger.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); Assert.HasCount(2, lots); Assert.AreEqual(0.00499m, lots.Single(l => l.Price > 61000m).Remaining); Assert.AreEqual(0.00999m, lots.Single(l => l.Price < 61000m).Remaining); var fifo = new Ledger(rig.Db, rig.Clock) { LotMethod = LotMethod.Fifo }; var ordered = await fifo.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); Assert.IsLessThan(ordered[1].Price, ordered[0].Price, "FIFO lists the oldest lot first."); var position = await rig.Ledger.PositionAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); Assert.AreEqual(0.01498m, position!.Quantity); Assert.AreEqual(position.Quantity, lots.Sum(l => l.Remaining), "Lots and position always agree."); } [TestMethod] [TestCategory(Category.Integration)] public async Task ResiduesDividendsSplitsAndReversalsKeepTheBooksRight() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false); var aapl = await rig.InstrumentAsync(TradingRig.Stock("AAPL")).ConfigureAwait(false); await rig.Ledger.RecordCapitalAsync(okx.AccountId, StrategyNames.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false); await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false); // A residue below the minimum is written off at market value as a cost: the trade closes (SPEC 7.2). await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false); await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false); await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false); Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false)); var residue = (await rig.QueryAsync("SELECT quantity, value FROM residues", r => (Q: r.Money("quantity"), V: r.Money("value"))).ConfigureAwait(false)).Single(); Assert.AreEqual((50_000m, 0.55m), (residue.Q, residue.V)); var trade = (await rig.QueryAsync("SELECT status, realized FROM trades WHERE instrument_id = @i", r => (S: r.Text("status"), R: r.Money("realized")), ("i", pepe.Id)) .ConfigureAwait(false)).Single(); Assert.AreEqual("closed", trade.S); var okxEquity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == okx.AccountId); Assert.AreEqual(okxEquity.Result, trade.R, "The written-off value is a loss of the trade, nothing else."); // A dividend goes to whoever held the stock before the ex-date. await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromDays(3)); Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false)); Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false)); await rig.Ledger.RecordDividendAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false); // A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once. await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, 180m, _none).ConfigureAwait(false); var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); // A split whose ex-date came before the purchase changes nothing: those shares were new shares already. Assert.AreEqual(0m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-old", 2m, TradingRig.Start.AddDays(-30), _none).ConfigureAwait(false)); Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); Assert.AreEqual(10m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false)); Assert.IsNull(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false), "Never twice."); var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!; Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice)); Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining)); var after = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); Assert.AreEqual(before.Equity, after.Equity); Assert.AreEqual(3002.5m, after.Equity, "Capital, plus the dividend; the position at its own price."); // A cash row is never changed: it is reversed by an opposite row that points at it. var dividend = (await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false)).Single(); await rig.Ledger.ReverseCashAsync(dividend, "Dividendo registrato due volte", _none).ConfigureAwait(false); Assert.AreEqual(3000m, (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId).Equity); } [TestMethod] [TestCategory(Category.Simulation)] public async Task RandomFillsNeverBreakTheBooks() { // Fixed seed (SPEC 18): cash + positions = equity, no negative quantity, lots = position, result = realised + unrealised. await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR")).ConfigureAwait(false); const string strategy = StrategyNames.CryptoTrend; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 100_000m, "EUR", "test", _none).ConfigureAwait(false); var gen = new Gen(Property.DefaultSeed); var prices = new Dictionary { [btc.Id] = 60000m, [eth.Id] = 3000m }; for (var step = 0; step < 60; step++) { var instrument = gen.Bool() ? btc : eth; prices[instrument.Id] = Math.Round(prices[instrument.Id] * (1m + gen.Decimal(-0.03m, 0.03m, 4)), 2); var price = prices[instrument.Id]; var held = (await rig.Ledger.PositionAsync(account.AccountId, instrument.Id, strategy, _none).ConfigureAwait(false))?.Quantity ?? 0m; var buy = held == 0m || gen.Int(0, 3) > 0; var inKind = gen.Bool(); rig.Clock.Advance(TimeSpan.FromMinutes(7)); if (buy) { var quantity = gen.Decimal(0.001m, 0.05m, 5); var fee = inKind ? Math.Round(quantity * 0.001m, 8) : Math.Round(quantity * price * 0.002m, 2); await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Buy, quantity, price, fee, inKind ? instrument.Spec.BaseCurrency : "EUR"), _none) .ConfigureAwait(false); } else { var quantity = gen.Int(0, 4) == 0 ? held : Math.Round(held * gen.Decimal(0.1m, 0.9m, 2), 8); await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Sell, quantity, price, Math.Round(quantity * price * 0.002m, 2)), _none) .ConfigureAwait(false); } await rig.Ledger.MarkAsync(instrument.Id, price, _none).ConfigureAwait(false); await AssertBooksAsync(rig, account, strategy, step).ConfigureAwait(false); } } private static async Task AssertBooksAsync(TradingRig rig, AccountContext account, string strategy, int step) { var positions = await rig.Ledger.PositionsAsync(account.AccountId, _none).ConfigureAwait(false); var cash = (await rig.QueryAsync("SELECT amount FROM cash_ledger WHERE account_id = @a AND currency = 'EUR'", r => r.Money("amount"), ("a", account.AccountId)).ConfigureAwait(false)).Sum(); var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(); Assert.AreEqual(cash + positions.Sum(p => p.Value), equity.Equity, 0.000001m, $"passo {step}: liquidità + posizioni = patrimonio"); Assert.IsTrue(positions.All(p => p.Quantity > 0m), $"passo {step}: nessuna quantità negativa"); foreach (var position in positions) { var lots = (await rig.Ledger.OpenLotsAsync(account.AccountId, position.InstrumentId, strategy, _none).ConfigureAwait(false)).Sum(l => l.Remaining); Assert.AreEqual(position.Quantity, lots, 0.000000001m, $"passo {step}: lotti = posizione"); } var realized = (await rig.QueryAsync("SELECT realized FROM trades", r => r.Money("realized")).ConfigureAwait(false)).Sum(); Assert.AreEqual(realized + positions.Sum(p => p.Unrealized), equity.Result, 0.0001m, $"passo {step}: risultato = realizzato + non realizzato"); } [TestMethod] [TestCategory(Category.Integration)] public async Task EquityPhotographsSeparateWorldsAndCorrectForCapitalChanges() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var fx = new FxStore(rig.Db, rig.Clock); await fx.UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false); var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false); await rig.Db.WriteAsync(async s => { foreach (var (strategy, account, share) in new[] { (StrategyNames.CryptoTrend, okx, 1m), (StrategyNames.EquityMomentum, alpaca, 0.75m), (StrategyNames.EquityMeanrev, alpaca, 0.25m) }) { await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)", _none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share)) .ConfigureAwait(false); } }, _none).ConfigureAwait(false); // 4,000 € on OKX all to crypto_trend; 6,000 € on Alpaca at 1.10 $/€ = 6,600 $, 75/25 (SPEC 8.6). var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx); await capital.SetAsync(Venues.Okx, 4000m, "test", _none).ConfigureAwait(false); var alpacaCapital = await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false); Assert.AreEqual(6600m, alpacaCapital.Amount); var strategies = await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false); Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == StrategyNames.EquityMomentum).Capital); Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == StrategyNames.EquityMeanrev).Capital); var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx); await book.TakeAsync(_none).ConfigureAwait(false); // A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain. var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, StrategyNames.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false); await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(5)); await book.TakeAsync(_none).ConfigureAwait(false); await capital.SetAsync(Venues.Okx, 8000m, "test", _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(5)); await book.TakeAsync(_none).ConfigureAwait(false); var series = await rig.QueryAsync("SELECT equity, flows, twr_index, drawdown_pct FROM equity_snapshots WHERE scope = 'strategy' AND strategy = @s ORDER BY taken_at", r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", StrategyNames.CryptoTrend)).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { 4000m, 4400m, 8400m }, series.Select(p => p.E).ToArray()); Assert.AreEqual(1.1m, series[^1].I); Assert.AreEqual(0.1m, Returns.TimeWeighted(series.Select(p => (p.E, p.F)).ToList())); // Simulated money (OKX in the simulator) and demo money are both "simulated": real money is a world apart. var totals = await rig.QueryAsync("SELECT world, currency, equity, fx_effect FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC", r => (W: r.Text("world"), C: r.Text("currency"), E: r.Money("equity"), Fx: r.MoneyOrNull("fx_effect"))).ConfigureAwait(false); Assert.IsTrue(totals.All(t => t.W == Worlds.Simulated && t.C == "EUR")); Assert.AreEqual(8400m + 6000m, totals[0].E, "The total in euro: 6,600 $ at 1.10 is 6,000 €."); Assert.AreEqual(0m, totals[0].Fx, "Same rate as the day of the capital: no FX effect."); // Reducing capital below what is invested is refused: the bot never sells to give money back. var error = await Assert.ThrowsExactlyAsync(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false); Assert.Contains("crypto_trend", error.Message); await Assert.ThrowsExactlyAsync(() => capital.SetSharesAsync(Venues.Alpaca, new Dictionary { [StrategyNames.EquityMomentum] = 0.8m, [StrategyNames.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false); } }