An independent review found these, now fixed and tested: - Risk limits could be raised through PUT /api/settings without the phrase and the password. The API now refuses risk keys. - The reference equity counted results twice after reduced to real and after a demotion. Each ledger now keeps a baseline, and carried results stay in the ledger's currency until the reference is computed. - An instrument could be bought by a second strategy in the same account (SPEC 8.6), and purchases under way did not hold their cash, so several purchases sent together could exceed it. Both are refused or shrunk now. - After an automatic trip of the switch there was no way to restart from the interface. Rischio now shows the trip of both worlds and the restart. - The fresh password of SPEC 12.4 could be tried without limit. Five wrong attempts in 15 minutes now lock it. - Observation to simulation skipped the 90 days of live signals. - A new build changed the qualification of a strategy with real money, "Ferma tutto" counted as a critical incident, raising risk ignored demotion conditions in progress, and weekends counted as stock sessions. - The 12.4 confirmation now summarises capital, first purchases and limits, and live strategies show the gap with their simulated twin. The backtest converts each bar with the rate fixed before it opens, the day before, and the report now counts how often correctives and risk changed a decision. crypto_trend is still not passed: the broad universe now falls 32.8%. The outcome file also keeps the qualified parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
17d6b8db38
commit
9ac159a7db
27 files changed
+1015
-532
No files matched your search
@@ -21,18 +21,20 @@ public sealed class ProtocolTests
|
||||
private static FxRate Usd(DateOnly day, decimal rate) => new("EUR", "USD", day, rate, "ecb");
|
||||
|
||||
[TestMethod]
|
||||
public void UsdtPricesBecomeEurosWithTheRateOfTheDayOrTheLastBefore()
|
||||
public void UsdtPricesBecomeEurosWithTheLastRateFixedBeforeTheBarOpens()
|
||||
{
|
||||
var friday = new DateOnly(2024, 3, 1);
|
||||
var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m) };
|
||||
var rates = new[] { Usd(friday, 1.10m), Usd(friday.AddDays(3), 1.25m) };
|
||||
var thursday = new DateOnly(2024, 2, 29);
|
||||
var friday = thursday.AddDays(1);
|
||||
var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m), Bar(friday.AddDays(4), 125m) };
|
||||
var rates = new[] { Usd(thursday, 1.10m), Usd(friday, 1.20m), Usd(friday.AddDays(3), 1.25m) };
|
||||
|
||||
var euro = EuroHistory.Convert(bars, rates);
|
||||
|
||||
Assert.HasCount(3, euro);
|
||||
Assert.AreEqual(100m, euro[0].Close);
|
||||
Assert.AreEqual(109.090909090909m, euro[1].Close); // Saturday: Friday's rate.
|
||||
Assert.AreEqual(80m, euro[2].Close);
|
||||
Assert.HasCount(4, euro);
|
||||
Assert.AreEqual(100m, euro[0].Close, "Friday's bar opens before Friday's rate is fixed: Thursday's");
|
||||
Assert.AreEqual(100m, euro[1].Close); // Saturday: Friday's rate.
|
||||
Assert.AreEqual(83.333333333333m, euro[2].Close); // Monday: still Friday's, Monday's comes in the afternoon.
|
||||
Assert.AreEqual(100m, euro[3].Close); // Tuesday: Monday's.
|
||||
Assert.AreEqual(100m, euro[0].Volume, "the volume is in coins: it does not change");
|
||||
Assert.AreEqual(10_000m, euro[0].QuoteVolume);
|
||||
Assert.AreEqual("BTCEUR", EuroHistory.SymbolOf("BTCUSDT"));
|
||||
@@ -46,8 +48,8 @@ public sealed class ProtocolTests
|
||||
|
||||
var euro = EuroHistory.Convert(bars, [Usd(day, 1m)]);
|
||||
|
||||
Assert.HasCount(EuroHistory.MaxRateAgeDays + 1, euro, "before the first rate and after a week without rates there is no price in euro");
|
||||
Assert.AreEqual(day, DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime));
|
||||
Assert.HasCount(EuroHistory.MaxRateAgeDays, euro, "up to the first rate and after a week without rates there is no price in euro");
|
||||
Assert.AreEqual(day.AddDays(1), DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime));
|
||||
Assert.AreEqual(day.AddDays(EuroHistory.MaxRateAgeDays), DateOnly.FromDateTime(euro[^1].OpensAt.UtcDateTime));
|
||||
}
|
||||
|
||||
@@ -56,7 +58,7 @@ public sealed class ProtocolTests
|
||||
{
|
||||
var day = new DateOnly(2022, 5, 10);
|
||||
var bars = new[] { Bar(day, 1m), Bar(day.AddDays(1), 0.0001m), Bar(day.AddDays(1 + EuroHistory.MaxGapDays + 1), 5m), Bar(day.AddDays(2 + EuroHistory.MaxGapDays + 1), 6m) };
|
||||
var rates = Enumerable.Range(0, 20).Select(i => Usd(day.AddDays(i), 1m)).ToList();
|
||||
var rates = Enumerable.Range(-1, 21).Select(i => Usd(day.AddDays(i), 1m)).ToList();
|
||||
|
||||
var euro = EuroHistory.Convert(bars, rates);
|
||||
|
||||
|
||||
@@ -157,9 +157,10 @@ public sealed class RiskEngineTests
|
||||
Assert.IsTrue(row.Data!.ContainsKey("reference"));
|
||||
|
||||
// No leverage: with the rest of the bot ten times larger the limits allow more, the strategy's own cash does not.
|
||||
// The purchase counts at the highest price its limit may chase to.
|
||||
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 90_000m, "EUR", "test", _none);
|
||||
var poor = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
|
||||
Assert.AreEqual(Math.Round(10_000m / 60_010m, 8), Math.Round(poor.Quantity, 8));
|
||||
Assert.AreEqual(Math.Round(10_000m / (60_010m * (1m + RiskLimits.Default.MaxPriceGap)), 8), Math.Round(poor.Quantity, 8));
|
||||
Assert.AreEqual(RiskReasons.NoLeverage, poor.Reasons[^1]);
|
||||
}
|
||||
|
||||
@@ -251,7 +252,7 @@ public sealed class RiskEngineTests
|
||||
Assert.IsFalse(world.State.Tripped);
|
||||
Assert.AreEqual(0m, world.Measures.Drawdown, "the high starts again from now");
|
||||
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k AND changed_by = 'utente'", r => r.Text("key"), ("k", SettingsStore.BotState.Key)));
|
||||
Assert.AreEqual(RiskSeverities.Info, (await EventsAsync(s.Rig, "restart")).Single(), "the restart is recorded with who confirmed it");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -278,7 +279,8 @@ public sealed class RiskEngineTests
|
||||
await OrdersAsync(1, "exit");
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
|
||||
// A stop is not a critical incident of SPEC 12.3: it must not hold back a promotion for 30 days.
|
||||
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -553,4 +555,110 @@ public sealed class RiskEngineTests
|
||||
Assert.AreEqual(2_500m, exposure.RealEquity);
|
||||
Assert.AreEqual(10_000m, await s.Risk.ReferenceAsync(_none));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheReferenceCountsEachResultOnceAcrossStageChanges()
|
||||
{
|
||||
await using var s = await CreateAsync(Consent());
|
||||
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||
async Task TradeAsync(AccountContext account, decimal quantity, decimal sold)
|
||||
{
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Buy, quantity, 60_000m), _none);
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Sell, quantity, sold), _none);
|
||||
}
|
||||
|
||||
Task<decimal> ResultsAsync(AccountContext account) => s.Rig.Db.ReadAsync(x => StageBook.LedgerResultsAsync(x, account.AccountId, StrategyNames.CryptoTrend), _none);
|
||||
|
||||
// In simulation: the capital and what the simulation made.
|
||||
await TradeAsync(s.Account, 0.1m, 70_000m);
|
||||
var simulated = await ResultsAsync(s.Account);
|
||||
Assert.AreEqual(10_000m + simulated, await s.Risk.ReferenceAsync(_none));
|
||||
|
||||
// Reduced real: the simulation's results stay, the quarter on the real account counts four times.
|
||||
await RequirementsMetAsync(s);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
|
||||
Password, null, "utente"), _none);
|
||||
await TradeAsync(live, 0.01m, 66_000m);
|
||||
var reduced = await ResultsAsync(live);
|
||||
await TradeAsync(s.Account, 0.05m, 50_000m); // the twin's results are not part of the reference
|
||||
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||
|
||||
// Real, on the same ledger: what was made in reduced is counted once, four times, not five.
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 7_500m, "EUR", "test", _none);
|
||||
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Real),
|
||||
Password, null, "utente"), _none);
|
||||
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||
|
||||
// Back to simulation: the simulation's old results are not counted again, nor the twin's.
|
||||
await s.Stages.RevokeAsync(StrategyNames.CryptoTrend, "utente", "user", _none);
|
||||
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnInstrumentBelongsToOneStrategyPerAccountAndPurchasesUnderWayHoldTheirCash()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
|
||||
// SPEC 8.6: another strategy holds BTC in this account, crypto_trend skips the entry.
|
||||
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 10_000m, "EUR", "test", _none);
|
||||
await HoldAsync(s, s.Account, 0.01m, "sma_cross");
|
||||
Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(s.Account, s.Btc, "sma_cross", OrderSide.Sell, 0.01m, 60_000m), _none);
|
||||
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal);
|
||||
|
||||
// A purchase of 9 600 € still under way holds its cash: only what is left can be bought, at the highest price.
|
||||
await s.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', 0.16, 0, 'K1', 1, 0, 60000, @w, @t, @t, @t)", _none,
|
||||
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("s", StrategyNames.CryptoTrend), ("w", ExecutionStates.Working), ("t", s.Rig.Clock.UtcNow)), _none);
|
||||
var highest = 1m + RiskLimits.Default.MaxPriceGap;
|
||||
var result = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
|
||||
Assert.AreEqual(RiskReasons.NoLeverage, result.Reasons[^1]);
|
||||
Assert.IsLessThanOrEqualTo(10_000m - (9_600m * highest) + 0.01m, result.Quantity * 60_010m * highest);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ObservationLastsNinetyDaysBeforeTheSimulation()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation', stage_since = @t", _none, ("t", s.Rig.Clock.UtcNow)), _none);
|
||||
var passed = new Qualification { Passed = true, Verdict = "superato", Report = "docs/backtests/crypto_trend.md" };
|
||||
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, passed with { Passed = false, Verdict = "non superato" }, _none);
|
||||
|
||||
// SPEC 12.3: the protocol passed and 90 days of signals collected live.
|
||||
var refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
|
||||
Assert.AreEqual("backtest", refused.Code);
|
||||
// A new outcome after the first start: written as the first start would, without its automatic move.
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none,
|
||||
("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(passed, Qualification.Json)))), _none);
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(89));
|
||||
refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
|
||||
Assert.AreEqual("observation", refused.Code);
|
||||
var requirement = (await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).Single(r => r.Key == "observation");
|
||||
Assert.IsFalse(requirement.Met);
|
||||
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||
await s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none);
|
||||
Assert.AreEqual(StrategyStages.Simulation, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Stage);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task WithRealMoneyTheQualificationDoesNotMove()
|
||||
{
|
||||
await using var s = await CreateAsync(Consent());
|
||||
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||
await RequirementsMetAsync(s);
|
||||
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
|
||||
Password, null, "utente"), _none);
|
||||
|
||||
// SPEC 12.3: a new build cannot move the figures a strategy with real money is compared with.
|
||||
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification { Passed = true, Verdict = "altro", Report = "altro.md", MaxDrawdown = 0.50m }, _none);
|
||||
Assert.AreEqual(0.20m, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Qualification!.MaxDrawdown);
|
||||
}
|
||||
}
|
||||
@@ -293,4 +293,25 @@ public sealed class AccessTests
|
||||
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
|
||||
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheFreshPasswordOfTheProcedureStopsAfterFiveWrongAttempts()
|
||||
{
|
||||
// SPEC 12.4: a stolen session must not be able to try passwords on the confirmation forms.
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
|
||||
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
||||
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
||||
|
||||
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
||||
{
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("sbagliata-" + i, null).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false), "even the right password waits");
|
||||
clock.Advance(LoginLimiter.Window);
|
||||
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Risk;
|
||||
@@ -95,6 +96,17 @@ public sealed class StrategyScreensTests
|
||||
var services = server.Host.Services!;
|
||||
var daily = RiskSettings.DailyLoss.Key;
|
||||
|
||||
// Not through the API: there the order of the limits and the procedure of SPEC 12.4 would be skipped.
|
||||
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
|
||||
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + RiskSettings.DrawdownStop.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "40" }) })
|
||||
{
|
||||
request.Headers.Add(csrf!["header"], csrf["token"]);
|
||||
using var put = await server.Http.SendAsync(request);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual("15", (await services.Settings.GetAsync(RiskSettings.DrawdownStop.Key, CancellationToken.None)).Value);
|
||||
|
||||
// Out of range, or the halving after the switch: nothing changes.
|
||||
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
|
||||
{
|
||||
@@ -175,5 +187,19 @@ public sealed class StrategyScreensTests
|
||||
}
|
||||
|
||||
Assert.AreEqual("active", await StateAsync());
|
||||
|
||||
// The switch tripped by itself in the simulation: the bot stays "active" elsewhere, and the page offers the restart.
|
||||
await services.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'simulated', @j, @t, @t)",
|
||||
CancellationToken.None, ("id", Guid.NewGuid()), ("j", new DbJson("{\"tripped\":true}")), ("t", DateTimeOffset.UtcNow)), CancellationToken.None);
|
||||
var page = await server.TextAsync("/rischio");
|
||||
StringAssert.Contains(page, "Interruttore scattato nel mondo simulato");
|
||||
StringAssert.Contains(page, "Riparti");
|
||||
using (var again = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
|
||||
{
|
||||
Assert.IsFalse(ServerHarness.Location(again).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(again));
|
||||
}
|
||||
|
||||
Assert.IsFalse(await services.Trading.Risk.AnyTrippedAsync(CancellationToken.None));
|
||||
Assert.AreEqual("active", await StateAsync());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user