Fase 5 — Strategie, portafoglio e rischio #91

Merged
Alby96 merged 8 commits from fase-5 into main 2026-11-11 17:30:11 +01:00
5 changed files with 74 additions and 41 deletions
Showing only changes of commit fc5df0146e - Show all commits

No files matched your search

+9 -1
View File
@@ -298,7 +298,15 @@ internal sealed partial class AnubisHost(
if (_trading is not null)
{
// Before "ready": the Strategie page must never show a strategy without its backtest outcome (SPEC 12.3).
await _trading.LoadOutcomesAsync(cancellationToken).ConfigureAwait(false);
// A failure here is logged and left to the trading start, which repeats it: the interface still opens.
try
{
await _trading.PrepareAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogTradingFailed(logger, ex);
}
}
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
+14 -2
View File
@@ -210,13 +210,25 @@ public sealed partial class TradingService : IDisposable
public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId);
/// <summary>Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled.</summary>
public async Task StartAsync(CancellationToken cancellationToken)
/// <summary>
/// Accounts, strategies and their backtest outcomes, in the database only: the host runs it before it is ready, so no
/// page ever shows a strategy without its outcome. Repeating it changes nothing.
/// </summary>
public async Task<IReadOnlyList<AccountContext>> PrepareAsync(CancellationToken cancellationToken)
{
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
var accounts = await AccountSetup.EnsureAsync(_db, _clock, alpaca is not null, okx is not null, cancellationToken).ConfigureAwait(false);
await LoadOutcomesAsync(cancellationToken).ConfigureAwait(false);
return accounts;
}
/// <summary>Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled.</summary>
public async Task StartAsync(CancellationToken cancellationToken)
{
var accounts = await PrepareAsync(cancellationToken).ConfigureAwait(false);
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false);
foreach (var account in accounts)
+3 -1
View File
@@ -12,7 +12,7 @@ public sealed class AccountsScreenTests
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTheFiguresOfTheMockup()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
@@ -58,6 +58,8 @@ public sealed class AccountsScreenTests
}
finally
{
// The server first: on Windows a database still open cannot be deleted.
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
+45 -36
View File
@@ -147,18 +147,23 @@ public sealed class ServerTests
[TestMethod]
public async Task ComputerOnlyModesRefuseForeignHostNames()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
using (var mine = await server.GetAsync("/api/me"))
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
string demoRoot;
{
Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode);
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
demoRoot = server.Host.Config.Data.Root;
using (var mine = await server.GetAsync("/api/me"))
{
Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode);
}
// DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host.
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative));
request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
using var foreign = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
}
// DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host.
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative));
request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
using var foreign = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
TempFolder.Delete(demoRoot);
}
@@ -368,34 +373,38 @@ public sealed class ServerTests
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var before = Snapshot(configured);
Assert.IsTrue(before.Keys.Any(k => k.EndsWith(".sqlite3", StringComparison.Ordinal)));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]);
// Its own folder under the temporary directory, the configured one untouched.
var demoRoot = server.Host.Config.Data.Root;
StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo"));
// Appendix F on screen, frozen clock, signed in by itself, the footer says it.
var html = await server.TextAsync("/");
StringAssert.Contains(html, "+412,46 €");
StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21");
StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop.");
StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.");
// The live status arrives over the WebSocket.
using var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None);
var buffer = new byte[4096];
var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, received.Count);
StringAssert.Contains(message, "\"type\":\"status\"");
StringAssert.Contains(message, "\"bot\":\"active\"");
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
var after = Snapshot(configured);
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
foreach (var (name, hash) in before)
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
string demoRoot;
{
Assert.AreEqual(hash, after[name], name + " changed");
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]);
// Its own folder under the temporary directory, the configured one untouched.
demoRoot = server.Host.Config.Data.Root;
StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo"));
// Appendix F on screen, frozen clock, signed in by itself, the footer says it.
var html = await server.TextAsync("/");
StringAssert.Contains(html, "+412,46 €");
StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21");
StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop.");
StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.");
// The live status arrives over the WebSocket.
using var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None);
var buffer = new byte[4096];
var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, received.Count);
StringAssert.Contains(message, "\"type\":\"status\"");
StringAssert.Contains(message, "\"bot\":\"active\"");
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
var after = Snapshot(configured);
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
foreach (var (name, hash) in before)
{
Assert.AreEqual(hash, after[name], name + " changed");
}
}
TempFolder.Delete(demoRoot);
+3 -1
View File
@@ -17,7 +17,7 @@ public sealed class StrategyScreensTests
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
@@ -63,6 +63,8 @@ public sealed class StrategyScreensTests
}
finally
{
// The server first: on Windows a database still open cannot be deleted.
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}