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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 22:07:46 +01:00
1 parent 24e20584d4
commit 81d6c5f667
20 files changed
+814 -174

No files matched your search

+127
View File
@@ -202,6 +202,133 @@ public sealed class LedgerTests
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()