Fix the defects found by the Phase 3 review (refs #33 #26 #27 #28 #29 #30 #31 #32)
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
- Splits multiply only the shares held before the ex-date. Old splits in the table no longer inflate positions bought later; the simulator's book follows the same split once, together with the ledger. - Dividends pay the simulator once on the ex-date holdings, and each payment is marked in the same write, so a failure never pays twice. - Positions are marked to market before every equity photograph; until now equity, drawdown and the Conti screen stayed at the last fill. - A sale with no price keeps its broker stops until it can really leave; a purchase with no price is dropped. - A refused sale is retried with pauses of 1, 2, 4, 8 and 15 minutes instead of every tick, and one failing execution no longer stops the stop alignment of the whole account. - On Alpaca a purchase clears the sell stops of every strategy on the symbol and holds them until it ends. - OKX order lookups treat only 51603 as unknown; any other failure is an error, so a lost order is never sent twice. - The reconcile choice and key removal forms now require the antiforgery token; the choice re-runs the comparison and is only offered after the 15 minutes; stale differences are dropped. - A replaced key that cannot withdraw releases the prudent mode. - Re-entering the same euro capital for Alpaca changes nothing; a new amount converts only the euro difference at today's rate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
60d5ebbc05
commit
1a0912e436
17 files changed
+358
-89
No files matched your search
@@ -101,6 +101,15 @@ public sealed class AccountsScreenTests
|
||||
var settings = await server.TextAsync("/impostazioni");
|
||||
Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again.");
|
||||
StringAssert.Contains(settings, "Impostata");
|
||||
|
||||
// Every form needs its antiforgery token, also the ones that send no field.
|
||||
foreach (var path in new[] { "/azioni/chiavi/alpaca/togli", "/azioni/conti/" + Guid.NewGuid() + "/allinea" })
|
||||
{
|
||||
using var forged = await server.Http.PostAsync(new Uri(path, UriKind.Relative), new FormUrlEncodedContent([]));
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, forged.StatusCode, path);
|
||||
}
|
||||
|
||||
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet, "A forged request removes nothing.");
|
||||
// The engine starts in the background after "ready": the paper account appears within moments.
|
||||
var accounts = new List<string>();
|
||||
for (var i = 0; i < 100 && accounts.Count == 0; i++)
|
||||
|
||||
@@ -125,8 +125,11 @@ public sealed class LedgerTests
|
||||
// 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, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false);
|
||||
var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId);
|
||||
Assert.IsTrue(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false));
|
||||
Assert.IsFalse(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false), "Never twice.");
|
||||
// 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, Strategies.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, Strategies.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, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining));
|
||||
|
||||
@@ -111,9 +111,16 @@ public sealed class OrderManagerTests
|
||||
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
|
||||
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
|
||||
|
||||
// No price at all: the sale waits, and the stops stay on the broker until it can really leave.
|
||||
s.Rig.QuotesDown = true;
|
||||
var (execution, _) = await s.Manager.SubmitAsync(Sell(s, held), _none).ConfigureAwait(false);
|
||||
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
|
||||
Assert.AreEqual("working/", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
|
||||
Assert.IsTrue((await OrdersAsync(s.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "stop" && o.Status == "submitted"), "Without a price the stops stay.");
|
||||
s.Rig.QuotesDown = false;
|
||||
|
||||
// Nobody buys near the price: the sale keeps going with a fresh reference and double tolerance.
|
||||
s.Rig.Quote("BTC-EUR", 50000m, 60000m);
|
||||
var (execution, _) = await s.Manager.SubmitAsync(Sell(s, held), _none).ConfigureAwait(false);
|
||||
await s.Rig.TurnsAsync(s.Manager, 12, _minute).ConfigureAwait(false);
|
||||
Assert.AreEqual("working/", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
|
||||
var tolerance = (await s.Rig.QueryAsync("SELECT tolerance FROM executions WHERE id = @id", r => r.Money("tolerance"), ("id", execution)).ConfigureAwait(false)).Single();
|
||||
@@ -239,11 +246,11 @@ public sealed class OrderManagerTests
|
||||
{
|
||||
var first = !applied;
|
||||
applied = true;
|
||||
return Task.FromResult(first ? new CorporateAction(instrument.Symbol, CorporateActionKinds.Split, new DateOnly(2026, 11, 10), "test", "split-msft") { Ratio = 4m } : null);
|
||||
return Task.FromResult(first ? new CorporateAction(instrument.Symbol, CorporateActionKinds.Split, new DateOnly(2026, 11, 11), "test", "split-msft") { Ratio = 4m } : null);
|
||||
}).ConfigureAwait(false);
|
||||
await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false);
|
||||
await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false);
|
||||
await a.Paper.ApplySplitAsync("MSFT", 4m, _none).ConfigureAwait(false);
|
||||
a.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||
a.Rig.Quote("MSFT", 100m, 100.05m);
|
||||
await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, Strategies.EquityMomentum, 380m, _none).ConfigureAwait(false);
|
||||
await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false);
|
||||
@@ -254,6 +261,7 @@ public sealed class OrderManagerTests
|
||||
Assert.IsFalse((await OrdersAsync(a.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "protective"));
|
||||
var stop = (await OrdersAsync(a.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "stop" && o.Status == "submitted");
|
||||
Assert.AreEqual((40m, 95m), (stop.Quantity, stop.Stop));
|
||||
Assert.AreEqual(40m, (await a.Paper.GetPositionsAsync(_none).ConfigureAwait(false)).Single().Quantity, "The simulator's book follows the same split.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -123,6 +123,13 @@ public sealed class ReconcilerTests
|
||||
Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace));
|
||||
Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'account_prudent'", r => r.Id("id")).ConfigureAwait(false));
|
||||
|
||||
// If it clears after the 15 minutes the user still decides, but no old difference is kept: "align" could
|
||||
// otherwise copy numbers that are no longer true. The choice compares again before it acts.
|
||||
s.Broker.Missing.Clear();
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.IsEmpty((await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Differences);
|
||||
s.Broker.Missing["BTC-EUR"] = 0.004m;
|
||||
|
||||
// Align: the ledger takes the account's number with an adjustment, and the account is normal again.
|
||||
await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
|
||||
@@ -202,7 +209,14 @@ public sealed class ReconcilerTests
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none)).ConfigureAwait(false);
|
||||
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'key_can_withdraw'", r => r.Id("id")).ConfigureAwait(false));
|
||||
await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'key_can_withdraw'", r => r.Id("id")).ConfigureAwait(false), "Notified once.");
|
||||
|
||||
// Replaced by a key without withdrawals: the lock ends, and purchases are allowed again.
|
||||
s.Broker.KeyCanWithdraw = false;
|
||||
await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.IsNull((await s.Manager.SubmitAsync(Entry(s), _none).ConfigureAwait(false)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -79,6 +79,29 @@ public sealed class TradingRulesTests
|
||||
Assert.IsFalse(OrderRules.IsUnsellable(btc, 0.001m, 60000m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task OkxCountsAnOrderAsUnknownOnlyWhenItDoesNotExist()
|
||||
{
|
||||
var answer = "{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}";
|
||||
var http = new FakeHttp()
|
||||
.On("/api/v5/public/time", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"ts\":\"1597026383085\"}]}")
|
||||
.On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond(answer));
|
||||
using var client = http.Client();
|
||||
var okx = new OkxTrading(client, new ManualClock(TradingRig.Start), new OkxCredentials("fake-key", "fake-secret", "fake-pass"),
|
||||
new OkxTradingOptions { Environment = TradingEnvironments.Demo }, TradingConsent.None);
|
||||
Assert.IsNull(await okx.GetOrderAsync("ANUX1", "BTC-EUR", CancellationToken.None));
|
||||
|
||||
// A generic failure is not "unknown": taken as such, a lost order could be sent twice.
|
||||
answer = "{\"code\":\"1\",\"msg\":\"Operation failed.\",\"data\":[]}";
|
||||
await Assert.ThrowsAsync<BrokerException>(() => okx.GetOrderAsync("ANUX1", "BTC-EUR", CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ARefusedSaleIsTriedAgainWithGrowingPauses() =>
|
||||
CollectionAssert.AreEqual(new[] { 1, 2, 4, 8, 15, 15 }, Enumerable.Range(1, 6).Select(n => (int)OrderManager.RefusalPause(n).TotalMinutes).ToArray());
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OrderStatesOnlyMoveForward()
|
||||
|
||||
@@ -92,6 +92,12 @@ public sealed class TradingServiceTests
|
||||
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());
|
||||
|
||||
// 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]
|
||||
@@ -107,10 +113,11 @@ public sealed class TradingServiceTests
|
||||
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.
|
||||
// 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") })
|
||||
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") })
|
||||
{
|
||||
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,
|
||||
@@ -122,6 +129,7 @@ public sealed class TradingServiceTests
|
||||
|
||||
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, Strategies.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);
|
||||
@@ -137,5 +145,10 @@ public sealed class TradingServiceTests
|
||||
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);
|
||||
|
||||
// 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, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user