Fix the defects found by the Phase 6 review (refs #47 #48 #49 #51 #52 #54)

An independent review of the phase found nine defects. The ones that
could lose money or orders:

- Exits at the close of equity_meanrev are now planned orders written in
  the same transaction that claims the decision, so a restart can neither
  lose them nor send them twice. A sell with a deadline starts aggressive.
- Resume also finds a planned order not yet linked to its execution
  (restart between sending and linking) and closes it before re-planning.
- An account is "ready" only after adopting the guard's stops, checking
  the key, reconciling, resuming and aligning stops. Until then nothing is
  decided on it or sent to it, and the loop retries its startup each
  minute. The guard's note is deleted only when every stop it placed is in
  the ledger.
- Each account's turn is cut after 45 s (60 s for a retried startup), so a
  slow broker no longer silences the heartbeat until the guard kills a
  healthy engine; the beat is also withheld when the scheduler has been
  silent for 30 minutes.

Smaller ones: a stock decision made after the open is marked late; the
Telegram loops survive unexpected errors; a long absence is shown on the
Panoramica until "Ho visto" (SPEC 5.6); plain-http heartbeats are only
accepted to home-network addresses; the soak report gives a daily close
30 minutes to be decided before expecting it.

ADR 0012 point 12 records these choices; #51 and the two screen criteria
are ticked in the roadmap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 21:10:28 +01:00
1 parent 3d174931e9
commit 2185a0b36b
16 files changed
+397 -90

No files matched your search

+7
View File
@@ -56,6 +56,9 @@ internal sealed partial class AnubisHost(
ILogger<AnubisHost> logger,
ServerOverrides? overrides = null) : BackgroundService
{
/// <summary>A scheduler silent this long is stuck: the engine stops beating, so the guard steps in.</summary>
public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30);
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
private readonly Lock _gate = new();
@@ -318,6 +321,10 @@ internal sealed partial class AnubisHost(
// The drill's fault is honored only under a guard, which never passes it to an engine it restarts.
Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable),
// The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take
// minutes), and the guard must hear it (SPEC 9.3).
OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence,
}
: null;
if (_trading is not null)
@@ -17,6 +17,14 @@
var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet();
var v = p.Accounts;
}
@if (_absence is { } away)
{
<div class="notice notice-attention absence" role="status">
<Icon Name="alert" Size="16" />
<span>Sono stato spento per @Anubis.Trading.DiaryText.Duration(away.Length), fino a @Format.ShortDate(away.EndedAt, Shell.Now, Shell.Zone, withTime: false).ToLowerInvariant() alle @TimeZoneInfo.ConvertTime(away.EndedAt, Shell.Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture). Ho ripreso i lavori saltati con le regole del recupero: cosa ho fatto e cosa ho lasciato perdere è nel <a href="/diario?tipo=sistema">diario</a>.</span>
<form method="post" action="/azioni/assenza/@away.Id/vista"><AntiforgeryToken /><button class="btn btn-small" type="submit">Ho visto</button></form>
</div>
}
@if (!o.CapitalSet && !Shell.IsDemo)
{
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>Primo passo: decidi quanto capitale affidare al bot in <a href="/impostazioni#conti">Impostazioni, Conti e chiavi</a>. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.</span></p>
@@ -388,6 +396,7 @@
private string _period = "avvio";
private int? _runningDays;
private decimal? _worst;
private Anubis.Trading.Absence? _absence;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
@@ -406,6 +415,9 @@
_worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null;
using var aggregates = Shell.Aggregates();
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
// SPEC 5.6: an absence longer than a day stays at the top until the user says they have seen it.
_absence = Shell.IsDemo ? null : await new Anubis.Trading.AbsenceBook(services.Db, Host.Clock).DeclaredAsync(ct);
}
private static string Statement(Overview o)
+12
View File
@@ -39,12 +39,24 @@ internal static partial class Forms
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
}
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
private static async Task<IResult> AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct)
{
if (!host.IsDemo && host.Services is { } services)
{
await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false);
}
return Results.Redirect("/");
}
private static string Back(IFormCollection form, string fallback)
{
var back = form["ritorno"].ToString();
+16 -2
View File
@@ -8,7 +8,7 @@ namespace Anubis.Server;
/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the
/// call to the checking service every minute, the morning summary and the optional periodic status.
/// </summary>
internal sealed class TelegramServices : IDisposable
internal sealed partial class TelegramServices : IDisposable
{
/// <summary>The secret that keeps the address of the checking service when the configuration does not give one.</summary>
public const string HeartbeatSecret = "HEARTBEAT_URL";
@@ -22,6 +22,7 @@ internal sealed class TelegramServices : IDisposable
private readonly SettingsStore _settings;
private readonly SecretStore _secrets;
private readonly TimeZoneInfo _zone;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler,
Microsoft.Extensions.Logging.ILogger logger)
@@ -32,6 +33,7 @@ internal sealed class TelegramServices : IDisposable
_settings = settings;
_secrets = secrets;
_zone = host.Config.TimeZone;
_logger = logger;
_http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
// Longer than the wait of the commands' long polling.
@@ -95,7 +97,16 @@ internal sealed class TelegramServices : IDisposable
{
while (!cancellationToken.IsCancellationRequested)
{
await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
try
{
await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// A busy or unreachable database, or anything else: the queue keeps its messages for the next pass.
LogSendFailed(_logger, ex);
}
await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false);
}
}
@@ -156,4 +167,7 @@ internal sealed class TelegramServices : IDisposable
var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
[Microsoft.Extensions.Logging.LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Error, Message = "Sending the Telegram queue failed")]
private static partial void LogSendFailed(Microsoft.Extensions.Logging.ILogger logger, Exception exception);
}
+32 -1
View File
@@ -174,6 +174,12 @@ public sealed partial class TelegramBot(IClock clock, Func<CancellationToken, Ta
LogPollFailed(logger, ex.Message);
pause = ex.RetryAfter is { } after && after > Retry ? after : Retry;
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// The database or the network failed in a way Telegram did not report: the loop goes on after a pause.
LogLoopFailed(logger, ex);
pause = Retry;
}
if (pause is { } wait)
{
@@ -188,6 +194,9 @@ public sealed partial class TelegramBot(IClock clock, Func<CancellationToken, Ta
[LoggerMessage(Level = LogLevel.Warning, Message = "Telegram read failed: {Error}")]
private static partial void LogPollFailed(ILogger logger, string error);
[LoggerMessage(Level = LogLevel.Error, Message = "Reading the Telegram commands failed")]
private static partial void LogLoopFailed(ILogger logger, Exception ex);
[LoggerMessage(Level = LogLevel.Error, Message = "Telegram command failed")]
private static partial void LogCommandFailed(ILogger logger, Exception ex);
}
@@ -248,11 +257,33 @@ public sealed partial class Heartbeat(HttpClient http, IClock clock, Func<Cancel
return "Serve un indirizzo che inizi con https://.";
}
return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || System.Net.IPAddress.TryParse(uri.Host, out _))
return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || IsPrivate(uri.Host))
? "Fuori dalla rete di casa serve https://."
: null;
}
/// <summary>An address of a home network: 10.x, 172.16-31.x, 192.168.x, link-local, or their IPv6 equivalents.</summary>
private static bool IsPrivate(string host)
{
if (!System.Net.IPAddress.TryParse(host.Trim('[', ']'), out var ip))
{
return false;
}
if (ip.IsIPv4MappedToIPv6)
{
ip = ip.MapToIPv4();
}
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
return System.Net.IPAddress.IsLoopback(ip) || ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal;
}
var b = ip.GetAddressBytes();
return b[0] == 10 || b[0] == 127 || (b[0] == 172 && b[1] is >= 16 and <= 31) || (b[0] == 192 && b[1] == 168) || (b[0] == 169 && b[1] == 254);
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")]
private static partial void LogFailed(ILogger logger, string error);
}
+8 -1
View File
@@ -162,9 +162,16 @@ public static class SoakReporter
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>How many crypto daily decisions (00:05 UTC) fall in the window.</summary>
/// <summary>The time a daily decision is given to run and be written before the report expects it.</summary>
public static readonly TimeSpan DecisionTime = TimeSpan.FromMinutes(30);
/// <summary>
/// How many crypto daily decisions (00:05 UTC) fall in the window. A close too near the end of the window is not
/// counted: its decision may still be running when the report is made.
/// </summary>
public static int DailyCloses(DateTimeOffset from, DateTimeOffset to)
{
to -= DecisionTime;
var count = 0;
for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1))
{
+95 -29
View File
@@ -138,6 +138,12 @@ public sealed partial class LiveEngine : IDisposable
/// </summary>
public Func<bool> Ready { get; init; } = () => true;
/// <summary>
/// Whether an account finished its startup (SPEC 9.4): reconciled, its leftovers canceled or resumed, its stops
/// aligned. Until then nothing is decided on it and no planned order is sent to it.
/// </summary>
public Func<Guid, bool> AccountReady { get; init; } = _ => true;
/// <summary>
/// The jobs of SPEC 5.5. The pulse every minute does the work; the others are the same pulse at the times the
/// user reads in "Prossime mosse", so the work starts on time.
@@ -245,11 +251,14 @@ public sealed partial class LiveEngine : IDisposable
return;
}
// SPEC 5.6: the signals are redone after an absence only before the next open; made after it, only the exits
// and the stops of the decision are kept.
var late = now >= next.OpenUtc;
foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev })
{
var ordersDue = next.OpenUtc + Options.OrdersAfterOpen;
var entriesUntil = strategy == StrategyNames.EquityMeanrev ? next.OpenUtc + Options.MeanrevEntryWindow : SecondSessionOfWeek(next).CloseUtc;
await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, false, next.OpenUtc, now, ordersDue,
await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, late, next.OpenUtc, now, ordersDue,
entriesUntil), cancellationToken).ConfigureAwait(false);
}
}
@@ -323,7 +332,7 @@ public sealed partial class LiveEngine : IDisposable
{
var accounts = await _db.ReadAsync(s => s.QueryAsync("SELECT id FROM accounts WHERE broker = @b", r => r.Id("id"), ("b", Venues.Alpaca)), cancellationToken)
.ConfigureAwait(false);
return [.. accounts.Select(_managers).OfType<OrderManager>()];
return [.. accounts.Where(AccountReady).Select(_managers).OfType<OrderManager>()];
}
/// <summary>
@@ -340,12 +349,17 @@ public sealed partial class LiveEngine : IDisposable
}
var stage = await _stages.GetAsync(StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false);
if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is not { } manager)
if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is null)
{
await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false);
return;
}
if (!AccountReady(accountId))
{
return;
}
var book = await BookAsync(accountId, StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false);
if (book.Holdings.Count == 0)
{
@@ -364,16 +378,10 @@ public sealed partial class LiveEngine : IDisposable
var record = BacktestEngine.DecideOnce(strategy, data.Data, book.State, session.Date, options);
var decisionId = Ids.NewId(_clock);
var exits = record.Final.Where(i => i.AtClose && i.TargetWeight == 0m && book.Holdings.ContainsKey(i.Symbol)).ToList();
var submitted = new List<(Intent Intent, Guid? Execution, string? Refusal)>();
foreach (var exit in exits)
{
var held = book.Holdings[exit.Symbol];
var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(held.InstrumentId, StrategyNames.EquityMeanrev, OrderSide.Sell, held.Holding.Quantity, OrderPurpose.Exit,
decisionId)
{ StartAggressive = true }, cancellationToken).ConfigureAwait(false);
submitted.Add((exit, execution, refusal));
}
// The exits are planned in the same transaction as the run key, like every other decision, and leave at once
// from the release below: a restart finds them planned and proposes them again (SPEC 9.4), and a failed
// attempt never sends the same exit twice with two keys. The deadline at the close makes them start aggressive.
await _db.WriteAsync(async s =>
{
if (!await ClaimAsync(s, StrategyNames.EquityMeanrev, key, session.Date, decisionId, DecisionModes.Full, null, null, cancellationToken).ConfigureAwait(false))
@@ -381,13 +389,23 @@ public sealed partial class LiveEngine : IDisposable
return;
}
foreach (var (intent, execution, refusal) in submitted)
foreach (var exit in exits)
{
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed,
[intent.Reason], new Dictionary<string, object?> { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false);
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Order,
refusal is null ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, refusal is null ? [] : [refusal],
new Dictionary<string, object?> { ["execution"] = execution }, now), cancellationToken).ConfigureAwait(false);
var held = book.Holdings[exit.Symbol];
var instrument = data.Data.Instruments.FirstOrDefault(i => i.Symbol == exit.Symbol);
var reference = instrument is null ? 0m : Close(instrument, session.Date) ?? 0m;
var id = Ids.NewId(_clock);
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed,
[exit.Reason], new Dictionary<string, object?> { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " +
"VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, NULL, NULL, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken,
("id", id), ("d", decisionId), ("s", StrategyNames.EquityMeanrev), ("a", accountId), ("i", held.InstrumentId), ("side", Wire.Text(OrderSide.Sell)),
("p", Wire.Text(OrderPurpose.Exit)), ("q", DbValues.Money(held.Holding.Quantity)), ("all", true), ("ref", reference), ("r", exit.Reason), ("due", now),
("until", session.CloseUtc), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false);
await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [],
new Dictionary<string, object?> { ["side"] = Wire.Text(OrderSide.Sell), ["quantity"] = held.Holding.Quantity, ["close"] = reference, ["planned"] = id }, now),
cancellationToken).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
}
@@ -422,6 +440,12 @@ public sealed partial class LiveEngine : IDisposable
return;
}
if (!observation && !AccountReady(account))
{
// Its ledger is not reconciled yet: the decision waits for the next pulse, late if it must (SPEC 5.6).
return;
}
var book = observation ? Book.Empty : await BookAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false);
var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false);
if (loaded.Data is null || loaded.Missing.Count > 0)
@@ -858,7 +882,7 @@ public sealed partial class LiveEngine : IDisposable
return;
}
if (_managers(order.AccountId) is not { } manager)
if (!AccountReady(order.AccountId) || _managers(order.AccountId) is not { } manager)
{
return;
}
@@ -908,8 +932,13 @@ public sealed partial class LiveEngine : IDisposable
}
}
var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) { StopLevel = stopLevel },
cancellationToken).ConfigureAwait(false);
// A sale never expires; one with a deadline (the exits at the close) starts aggressive: there are minutes left.
var aggressive = order.Side == OrderSide.Sell && order.ValidUntil is not null;
var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id)
{
StopLevel = stopLevel,
StartAggressive = aggressive,
}, cancellationToken).ConfigureAwait(false);
var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null;
await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false);
}
@@ -927,23 +956,25 @@ public sealed partial class LiveEngine : IDisposable
var again = 0;
foreach (var execution in canceled)
{
var row = await _db.ReadAsync(s => s.FirstOrDefaultAsync(
"SELECT p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, " +
"p.reference_price, p.reason, p.due_at, p.valid_until, e.filled FROM planned_orders p JOIN executions e ON e.id = p.execution_id WHERE p.execution_id = @e",
r => new Interrupted(new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")),
Wire.Purpose(r.Text("purpose")), r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"),
r.Text("reason"), r.Moment("due_at"), r.MomentOrNull("valid_until")), r.Money("filled")), ("e", execution)), cancellationToken).ConfigureAwait(false);
var row = await InterruptedAsync(execution, cancellationToken).ConfigureAwait(false);
if (row is not { } found || (found.Order.Quantity - found.Filled <= 0m && !found.Order.ExitAll))
{
continue;
}
var (order, filled) = found;
var (order, filled, unlinked) = found;
var symbol = (await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?";
var now = _clock.UtcNow;
var sale = order.Side == OrderSide.Sell;
await _db.WriteAsync(async s =>
{
if (unlinked)
{
// The process stopped between sending it and marking it sent: it is marked now, so it never goes again.
await s.ExecuteAsync("UPDATE planned_orders SET status = @st, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken,
("st", PlannedStates.Submitted), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false);
}
await s.ExecuteAsync(
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, " +
"reason, due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, @reason, " +
@@ -961,7 +992,42 @@ public sealed partial class LiveEngine : IDisposable
return again;
}
private sealed record Interrupted(Planned Order, decimal Filled);
private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked);
private const string PlannedColumns =
"p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until";
private static Planned ReadPlanned(DbRow r) =>
new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")),
r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"),
r.MomentOrNull("valid_until"));
/// <summary>
/// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between
/// sending it and marking it sent, the pending one whose key the execution carries.
/// </summary>
private Task<Interrupted?> InterruptedAsync(Guid execution, CancellationToken cancellationToken) =>
_db.ReadAsync(async s =>
{
var info = await s.FirstOrDefaultAsync("SELECT account_id, instrument_id, order_key, filled FROM executions WHERE id = @e",
r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Key: r.Text("order_key"), Filled: r.Money("filled")), ("e", execution)).ConfigureAwait(false);
if (info.Key is null)
{
return null;
}
var linked = await s.FirstOrDefaultAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.execution_id = @e", ReadPlanned, ("e", execution))
.ConfigureAwait(false);
if (linked is not null)
{
return new Interrupted(linked, info.Filled, false);
}
var pending = await s.QueryAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.account_id = @a AND p.instrument_id = @i AND p.status = @p AND p.execution_id IS NULL",
ReadPlanned, ("a", info.Account), ("i", info.Instrument), ("p", PlannedStates.Pending)).ConfigureAwait(false);
var unlinked = pending.FirstOrDefault(p => ClientOrderIds.Key(p.Id) == info.Key);
return unlinked is null ? (Interrupted?)null : new Interrupted(unlinked, info.Filled, true);
}, cancellationToken);
private static string OrderWords(Planned order, string symbol) =>
(order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol);
+135 -38
View File
@@ -188,6 +188,7 @@ public sealed partial class TradingService : IDisposable
{
WantData = market is null ? null : _ => market.WakeWorker(),
Ready = () => _started,
AccountReady = AccountReady,
};
}
@@ -305,36 +306,12 @@ public sealed partial class TradingService : IDisposable
}
await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
var notes = GuardFiles is null ? [] : Supervision.GuardFiles.ReadNotes(GuardFiles);
foreach (var manager in _managers.Values)
{
await GuardAsync("avvio " + manager.Account.Name, async () =>
{
if (manager.Broker is PaperBroker paper)
{
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
}
else
{
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
}
// The stops the guard put back while the engine was stopped become the engine's own, before anything compares.
foreach (var placed in notes.SelectMany(n => n.Note.Placed).Where(p => p.AccountId == manager.Account.AccountId))
{
await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false);
}
Guard?.Step("riconciliazione " + manager.Account.Name);
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("ordini rimasti aperti " + manager.Account.Name);
await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("stop " + manager.Account.Name);
await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false);
}
await GuardAsync("note della guardia", () => TakeGuardNotesAsync(notes, cancellationToken), cancellationToken).ConfigureAwait(false);
_accountsRetryAt = _clock.UtcNow + AccountRetry;
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false);
@@ -363,14 +340,97 @@ public sealed partial class TradingService : IDisposable
_guardStateAt = _clock.UtcNow;
}
// The guard's notes go in the diary once their stops are adopted; then they are gone.
private async Task TakeGuardNotesAsync(IReadOnlyList<(string Path, GuardNote Note)> notes, CancellationToken cancellationToken)
/// <summary>The accounts whose startup of SPEC 9.4 is done: only these are ticked, decided on and sent orders.</summary>
public bool AccountReady(Guid accountId) => _ready.ContainsKey(accountId);
private readonly ConcurrentDictionary<Guid, bool> _ready = new();
/// <summary>An account whose startup failed (broker unreachable) is tried again this often.</summary>
public TimeSpan AccountRetry { get; init; } = TimeSpan.FromMinutes(1);
private DateTimeOffset _accountsRetryAt;
/// <summary>
/// The startup of one account (SPEC 9.4): the guard's stops adopted first, whatever else fails; then the key, the
/// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again)
/// and every position checked for its stop. Until all of it is done the account is not ready.
/// </summary>
private async Task StartAccountAsync(OrderManager manager, CancellationToken cancellationToken)
{
foreach (var (path, note) in notes)
var name = manager.Account.Name;
await GuardAsync("stop della guardia " + name, () => AdoptGuardStopsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false);
var started = await TryAsync("avvio " + name, async () =>
{
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines),
new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false);
File.Delete(path);
if (manager.Broker is PaperBroker paper)
{
await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false);
}
else
{
await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false);
}
Guard?.Step("riconciliazione " + name);
await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("ordini rimasti aperti " + name);
await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false);
Guard?.Step("stop " + name);
await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (started)
{
_ready[manager.Account.AccountId] = true;
}
}
/// <summary>
/// The stops the guard put back while the engine was stopped become the engine's own, before anything compares
/// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a
/// stop left unknown would be put back a second time.
/// </summary>
private async Task AdoptGuardStopsAsync(OrderManager manager, CancellationToken cancellationToken)
{
if (GuardFiles is null)
{
return;
}
foreach (var (path, note) in Supervision.GuardFiles.ReadNotes(GuardFiles))
{
foreach (var placed in note.Placed.Where(p => p.AccountId == manager.Account.AccountId))
{
await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false);
}
var adopted = true;
foreach (var placed in note.Placed)
{
adopted &= await _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM orders WHERE client_order_id = @c", ("c", placed.ClientOrderId))
.ConfigureAwait(false) > 0, cancellationToken).ConfigureAwait(false);
}
if (adopted)
{
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines),
new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false);
File.Delete(path);
}
}
}
/// <summary>The accounts whose startup failed are tried again, once a minute.</summary>
private async Task RetryAccountsAsync(CancellationToken cancellationToken)
{
if (_clock.UtcNow < _accountsRetryAt)
{
return;
}
_accountsRetryAt = _clock.UtcNow + AccountRetry;
foreach (var manager in _managers.Values.Where(m => !AccountReady(m.Account.AccountId)))
{
await LimitedAsync("nuovo avvio " + manager.Account.Name, RetryLimit, ct => StartAccountAsync(manager, ct), cancellationToken).ConfigureAwait(false);
BeatIfAlive();
}
}
@@ -504,7 +564,7 @@ public sealed partial class TradingService : IDisposable
}
await TickAllAsync(cancellationToken).ConfigureAwait(false);
Guard?.Beat();
BeatIfAlive();
if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery)
{
await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
@@ -550,20 +610,52 @@ public sealed partial class TradingService : IDisposable
public async Task TickAllAsync(CancellationToken cancellationToken)
{
foreach (var manager in _managers.Values)
await RetryAccountsAsync(cancellationToken).ConfigureAwait(false);
// An account not started yet keeps what it left open untouched: its startup cancels or resumes it first.
foreach (var manager in _managers.Values.Where(m => AccountReady(m.Account.AccountId)))
{
await GuardAsync("ordini " + manager.Account.Name, async () =>
await LimitedAsync("ordini " + manager.Account.Name, TickLimit, async ct =>
{
if (manager.Broker is PaperBroker paper)
{
await paper.PumpAsync(cancellationToken).ConfigureAwait(false);
await paper.PumpAsync(ct).ConfigureAwait(false);
}
await manager.TickAsync(cancellationToken).ConfigureAwait(false);
await manager.TickAsync(ct).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
BeatIfAlive();
}
}
/// <summary>
/// The longest one account's turn of the loop may take. A broker that stops answering (timeouts, retries) must
/// not keep the loop from beating for the two minutes after which the guard steps in: the turn is cut, written in
/// the log, and tried again at the next round. A loop that is truly stuck still falls silent.
/// </summary>
public TimeSpan TickLimit { get; init; } = TimeSpan.FromSeconds(45);
/// <summary>The longest an account's startup may take when it is tried again from the loop.</summary>
public TimeSpan RetryLimit { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>Whether the other loops of the engine are alive (the scheduler): without them the beat is withheld.</summary>
public Func<bool>? OthersAlive { get; init; }
private void BeatIfAlive()
{
if (OthersAlive is null || OthersAlive())
{
Guard?.Beat();
}
}
private async Task LimitedAsync(string what, TimeSpan limit, Func<CancellationToken, Task> work, CancellationToken cancellationToken)
{
using var limited = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
limited.CancelAfter(limit);
await GuardAsync(what, () => work(limited.Token), cancellationToken).ConfigureAwait(false);
}
public async Task ReconcileAllAsync(CancellationToken cancellationToken)
{
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
@@ -816,11 +908,15 @@ public sealed partial class TradingService : IDisposable
}
}
private async Task GuardAsync(string what, Func<Task> work, CancellationToken cancellationToken)
private Task<bool> GuardAsync(string what, Func<Task> work, CancellationToken cancellationToken) => TryAsync(what, work, cancellationToken);
/// <summary>Runs a step; a failure is logged and the answer is false. Only the stop of the service passes through.</summary>
private async Task<bool> TryAsync(string what, Func<Task> work, CancellationToken cancellationToken)
{
try
{
await work().ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -829,6 +925,7 @@ public sealed partial class TradingService : IDisposable
catch (Exception ex)
{
LogWorkFailed(_logger, ex, what);
return false;
}
}