Files
Anubis/tests/Anubis.Tests/LedgerTests.cs
T
Alby96andClaude Opus 5.5 81d6c5f667 Fix what the review of Phase 9 found in accounts, access, capital, health and publication
A position left out together with its stop kept the account prudent for good: the
stop was still asked for shares that no longer exist. The cover required now stops
at what the account holds, the stops are compared again after the choice, and where
one is still missing Align takes the excluded position up again. After the choice
the account waits for the stop with its own reason, so it returns to normal by
itself also past the 15 minutes; a new difference still gets its own 15 minutes.

A right password alone no longer clears the wrong second-factor codes: it takes
back only its own attempt.

Capital and shares are planned and written in one transaction, so overlapping
changes cannot apply twice and an interruption leaves nothing halfway; sending the
same figures again completes what an old one left. The cash that purchases under
way still hold is no longer given away, counted as the risk engine counts it.

/health said healthy when the trading engine had failed to start. It now says so at
once, or after ten minutes of a stalled start, and the host tries the start again
every minute; the guard still sees a start that does not move.

The image of the manual publication says its version and its commit, marked when
the tree is dirty, and publish.sh refuses before any login an image that does not
come from the commit of the tag.

refs #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:07:46 +01:00

393 lines
29 KiB
C#

using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The bot's books (issue #29, SPEC 7.5): append-only rows, lots, trades from zero to zero, equity, returns.</summary>
[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<LedgerException>(() => 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<Guid, decimal> { [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");
}
private static readonly Dictionary<string, decimal> _half = new() { [StrategyNames.EquityMomentum] = 0.5m, [StrategyNames.EquityMeanrev] = 0.5m };
/// <summary>6,000 € on Alpaca at 1.10 $/€: 6,600 $, 4,950 to the momentum and 1,650 to the mean reversion.</summary>
private static async Task<(TradingRig Rig, AccountContext Account, Capital Capital)> EntrustedAsync()
{
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 alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
await rig.Db.WriteAsync(async s =>
{
foreach (var (strategy, share) in new[] { (StrategyNames.EquityMomentum, 0.75m), (StrategyNames.EquityMeanrev, 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", alpaca.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share))
.ConfigureAwait(false);
}
}, _none).ConfigureAwait(false);
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx);
await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
return (rig, alpaca, capital);
}
private static async Task SharesAsync(Capital capital, TradingRig rig, decimal momentum, decimal meanrev)
{
var strategies = (await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false)).ToDictionary(s => s.Strategy);
Assert.AreEqual((momentum, meanrev), (strategies[StrategyNames.EquityMomentum].Capital, strategies[StrategyNames.EquityMeanrev].Capital));
var stored = await rig.QueryAsync("SELECT capital FROM strategy_state ORDER BY strategy DESC", r => r.Money("capital")).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { momentum, meanrev }, stored.ToArray());
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SharesWrittenWithoutTheirMoneyAreCompletedByTheSameSplit()
{
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
await using var owned = rig;
// What an interruption between the two writes left behind: the new shares without the capital flows.
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET share = 0.5", _none), _none).ConfigureAwait(false);
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
await SharesAsync(capital, rig, 3300m, 3300m).ConfigureAwait(false);
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM config_history WHERE key LIKE 'strategy.%'", r => r.Id("id")).ConfigureAwait(false), "No share changed.");
// Complete: the same split again writes nothing.
async Task<int> RowsAsync() => (await rig.QueryAsync("SELECT id FROM cash_ledger", r => r.Id("id")).ConfigureAwait(false)).Count + (await rig.QueryAsync("SELECT id FROM journal", r => r.Id("id")).ConfigureAwait(false)).Count;
var rows = await RowsAsync().ConfigureAwait(false);
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
Assert.AreEqual(rows, await RowsAsync().ConfigureAwait(false));
// The same for the capital: the figure was written, the flows were not.
await rig.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, 'alpaca', 8000, 'USD', 1.1, 8800, 'test', @now)", _none,
("id", Ids.NewId(rig.Clock)), ("now", rig.Clock.UtcNow.AddSeconds(1))), _none).ConfigureAwait(false);
await capital.SetAsync(Venues.Alpaca, 8000m, "test", _none).ConfigureAwait(false);
await SharesAsync(capital, rig, 4400m, 4400m).ConfigureAwait(false);
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM capital_changes", r => r.Id("id")).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task OverlappingChangesMoveTheMoneyOnce()
{
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
await using var owned = rig;
var original = new Dictionary<string, decimal> { [StrategyNames.EquityMomentum] = 0.75m, [StrategyNames.EquityMeanrev] = 0.25m };
for (var round = 0; round < 10; round++)
{
var split = round % 2 == 0 ? _half : original;
using var together = new Barrier(4);
await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Factory.StartNew(() =>
{
together.SignalAndWait();
return capital.SetSharesAsync(Venues.Alpaca, split, "test", _none);
}, _none, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap())).ConfigureAwait(false);
await SharesAsync(capital, rig, 6600m * split[StrategyNames.EquityMomentum], 6600m * split[StrategyNames.EquityMeanrev]).ConfigureAwait(false);
}
Assert.HasCount(10, await rig.QueryAsync("SELECT id FROM journal WHERE code = 'shares_changed'", r => r.Id("id")).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ASplitThatFailsHalfwayLeavesEverythingAsItWas()
{
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
await using var owned = rig;
// The flows cannot be written: the shares must not move either.
await rig.Db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE cash_ledger RENAME COLUMN note TO note_away", _none), _none).ConfigureAwait(false);
await Assert.ThrowsAsync<System.Data.Common.DbException>(() => capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none)).ConfigureAwait(false);
await rig.Db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE cash_ledger RENAME COLUMN note_away TO note", _none), _none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { 0.75m, 0.25m }, (await rig.QueryAsync("SELECT share FROM strategy_state ORDER BY strategy DESC", r => r.Money("share")).ConfigureAwait(false)).ToArray());
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MoneyHeldByAPurchaseUnderWayIsNotGivenAway()
{
var (rig, account, capital) = await EntrustedAsync().ConfigureAwait(false);
await using var owned = rig;
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
// 11 shares at 400 $, 2 of them filled: 9 still to pay, at most 1% dearer, hold 3,636 $ of the 4,950.
await rig.Db.WriteAsync(x => x.ExecuteAsync(
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, @s, 'buy', 'entry', 11, 2, 'K1', 1, 0, 400, @w, @t, @t, @t)", _none,
("id", Ids.NewId(rig.Clock)), ("a", account.AccountId), ("i", msft.Id), ("s", StrategyNames.EquityMomentum), ("w", ExecutionStates.Working), ("t", rig.Clock.UtcNow)), _none)
.ConfigureAwait(false);
var error = await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none)).ConfigureAwait(false);
Assert.Contains("Momentum azioni", error.Message);
Assert.Contains("acquisti in corso", error.Message);
await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetAsync(Venues.Alpaca, 2000m, "test", _none)).ConfigureAwait(false);
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
// 1,314 $ are free: giving the strategy more, or taking no more than that, is fine.
await capital.SetAsync(Venues.Alpaca, 7000m, "test", _none).ConfigureAwait(false);
await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
// The purchase is over: the money is free again.
await rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE executions SET status = 'canceled'", _none), _none).ConfigureAwait(false);
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
await SharesAsync(capital, rig, 3300m, 3300m).ConfigureAwait(false);
}
[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<CapitalException>(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false);
Assert.Contains("Trend crypto", error.Message);
await Assert.ThrowsExactlyAsync<CapitalException>(() =>
capital.SetSharesAsync(Venues.Alpaca, new Dictionary<string, decimal> { [StrategyNames.EquityMomentum] = 0.8m, [StrategyNames.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false);
}
}