Every intent of a strategy now crosses a risk engine that only refuses or shrinks: loss limits per world with the 24-hour block, the weekly halving, the halving and the switch on the fall from the high, the size limits on invested capital, single position, crypto share and trade risk, the technical checks, no short sales and no leverage, the day-trade guard (off by default). The switch, "Ferma tutto", "Ferma e chiudi", the STOP file and the orders-per-minute anomaly stop the bot until the user confirms a restart, and a restart after a trip measures the high from then on. The correctives of SPEC 8.5 (crypto regime, economic calendar) and the risk rules also run inside the backtests of the base strategies, so the reports show what would happen live. Each stage of a decision is written to a new decisions table with reason codes. The stage book is the only way to real money: an order on a real account needs the startup consent, every requirement of SPEC 12.3 met, the typed phrase and a fresh password and second factor. Order managers on real accounts fail closed and ask again before each order leaves. A demoted or revoked strategy keeps its real positions in exit only, with stops, until they are at zero. The simulated twin stays out of totals and of the reference equity. Tests cover each rule of 9.1 and 9.2, with property tests for "never larger than asked" and "never larger after a loss", and both proofs on a fake real account: nothing reaches it without the procedure, and a demoted strategy manages exits and stops down to zero. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
11 KiB
C#
260 lines
11 KiB
C#
using System.Globalization;
|
||
using Anubis.Data;
|
||
|
||
namespace Anubis.Risk;
|
||
|
||
/// <summary>A point of a world's time-weighted index: deposits and withdrawals never look like gains or losses (SPEC 7.5).</summary>
|
||
public sealed record IndexPoint(DateTimeOffset At, decimal Index);
|
||
|
||
/// <summary>The three measures of SPEC 9.2, as changes: −0.03 is a loss of 3%.</summary>
|
||
public sealed record RiskMeasures(decimal DayChange, decimal WeekChange, decimal Drawdown)
|
||
{
|
||
public static RiskMeasures None { get; } = new(0m, 0m, 0m);
|
||
|
||
/// <summary>
|
||
/// The measures at <paramref name="now"/>: the day starts at Italian midnight, the week is the last seven days, the
|
||
/// high is the highest point since <paramref name="peakFrom"/> (the start, or the last confirmed restart).
|
||
/// </summary>
|
||
public static RiskMeasures From(IReadOnlyList<IndexPoint> series, DateTimeOffset now, DateTimeOffset? peakFrom, decimal? knownPeak = null)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(series);
|
||
var last = LastAtOrBefore(series, now);
|
||
if (last < 0)
|
||
{
|
||
return None;
|
||
}
|
||
|
||
var current = series[last].Index;
|
||
var midnight = RiskMonitor.ItalianMidnight(now);
|
||
var dayIndex = LastAtOrBefore(series, midnight.AddTicks(-1));
|
||
var dayBase = series[Math.Max(dayIndex, 0)].Index;
|
||
var weekIndex = LastAtOrBefore(series, now - TimeSpan.FromDays(7));
|
||
var weekBase = series[Math.Max(weekIndex, 0)].Index;
|
||
var peak = Math.Max(current, knownPeak ?? current);
|
||
for (var i = last; i >= 0 && (peakFrom is null || series[i].At >= peakFrom); i--)
|
||
{
|
||
peak = Math.Max(peak, series[i].Index);
|
||
}
|
||
|
||
return new RiskMeasures(Change(current, dayBase), Change(current, weekBase), Change(current, peak)) { Index = current, Peak = peak };
|
||
}
|
||
|
||
/// <summary>The index the measures were taken on.</summary>
|
||
public decimal? Index { get; init; }
|
||
|
||
/// <summary>The high the fall is measured from: kept by the engine between readings, so the series can be short.</summary>
|
||
public decimal? Peak { get; init; }
|
||
|
||
public static decimal Change(decimal current, decimal reference) => reference <= 0m ? 0m : (current / reference) - 1m;
|
||
|
||
private static int LastAtOrBefore(IReadOnlyList<IndexPoint> series, DateTimeOffset at)
|
||
{
|
||
int lo = 0, hi = series.Count - 1, found = -1;
|
||
while (lo <= hi)
|
||
{
|
||
var mid = (lo + hi) / 2;
|
||
if (series[mid].At <= at)
|
||
{
|
||
found = mid;
|
||
lo = mid + 1;
|
||
}
|
||
else
|
||
{
|
||
hi = mid - 1;
|
||
}
|
||
}
|
||
|
||
return found;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// What the risk engine remembers about a world (SPEC 9.2, 9.3): the 24-hour block after a day's loss, the seven
|
||
/// days of halved risk after a week's loss, the moment the high is measured from, the switch tripped by the fall
|
||
/// from the high, and the warnings already sent (one for each crossing).
|
||
/// </summary>
|
||
public sealed record RiskMonitorState
|
||
{
|
||
public DateTimeOffset? DailyBlockUntil { get; init; }
|
||
|
||
public DateTimeOffset? WeeklyHalvingUntil { get; init; }
|
||
|
||
/// <summary>The high counts points from this moment: the start, or the last confirmed restart after a trip.</summary>
|
||
public DateTimeOffset? PeakFrom { get; init; }
|
||
|
||
/// <summary>The highest index seen since <see cref="PeakFrom"/>.</summary>
|
||
public decimal? Peak { get; init; }
|
||
|
||
/// <summary>The fall from the high reached the stop threshold: entries and sales of the strategies stop until the user confirms.</summary>
|
||
public bool Tripped { get; init; }
|
||
|
||
public DateTimeOffset? TrippedAt { get; init; }
|
||
|
||
/// <summary>Measures beyond 80% of their threshold, already warned about; a measure leaves the list when it comes back.</summary>
|
||
public IReadOnlyList<string> Warned { get; init; } = [];
|
||
|
||
public static RiskMonitorState Initial { get; } = new();
|
||
}
|
||
|
||
/// <summary>Something the monitor saw: a limit crossed, a warning at 80% of a threshold.</summary>
|
||
public sealed record RiskAlert(string Kind, string Severity, string Message, decimal Value, decimal Threshold);
|
||
|
||
public static class RiskAlertKinds
|
||
{
|
||
public const string DailyLoss = "daily_loss";
|
||
public const string WeeklyLoss = "weekly_loss";
|
||
public const string DrawdownHalf = "drawdown_half";
|
||
public const string DrawdownStop = "drawdown_stop";
|
||
public const string Warning = "warning";
|
||
}
|
||
|
||
public static class RiskSeverities
|
||
{
|
||
public const string Info = "info";
|
||
public const string Warning = "warning";
|
||
public const string High = "high";
|
||
public const string Critical = "critical";
|
||
}
|
||
|
||
public sealed record RiskReading(RiskMonitorState State, RiskMeasures Measures, IReadOnlyList<RiskAlert> Alerts);
|
||
|
||
/// <summary>
|
||
/// The loss limits of SPEC 9.2 as a pure state machine: the same steps run in the backtest, on the closes of one
|
||
/// strategy, and live, on every photograph of a world's equity. It never raises the risk: the multiplier it gives is
|
||
/// one or less, and lower the larger the losses.
|
||
/// </summary>
|
||
public static class RiskMonitor
|
||
{
|
||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||
|
||
/// <summary>Midnight in Italy of the day <paramref name="at"/> falls on, as a UTC moment.</summary>
|
||
public static DateTimeOffset ItalianMidnight(DateTimeOffset at)
|
||
{
|
||
var local = TimeZoneInfo.ConvertTime(at, Zones.Rome);
|
||
var midnight = local.Date;
|
||
return new DateTimeOffset(midnight, Zones.Rome.GetUtcOffset(midnight));
|
||
}
|
||
|
||
public static RiskReading Step(RiskMonitorState state, RiskMeasures m, DateTimeOffset now, RiskLimits limits)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(state);
|
||
ArgumentNullException.ThrowIfNull(m);
|
||
ArgumentNullException.ThrowIfNull(limits);
|
||
var alerts = new List<RiskAlert>();
|
||
var next = state;
|
||
if (m.DayChange <= -limits.DailyLoss && !(state.DailyBlockUntil > now))
|
||
{
|
||
next = next with { DailyBlockUntil = now + RiskLimits.DailyBlock };
|
||
alerts.Add(new(RiskAlertKinds.DailyLoss, RiskSeverities.High,
|
||
$"Perdita di oggi {Percent(m.DayChange)}, oltre la soglia del {Percent(-limits.DailyLoss)}: niente nuovi ingressi per 24 ore.", m.DayChange, -limits.DailyLoss));
|
||
}
|
||
|
||
if (m.WeekChange <= -limits.WeeklyLoss && !(state.WeeklyHalvingUntil > now))
|
||
{
|
||
next = next with { WeeklyHalvingUntil = now + RiskLimits.WeeklyHalving };
|
||
alerts.Add(new(RiskAlertKinds.WeeklyLoss, RiskSeverities.High,
|
||
$"Perdita degli ultimi sette giorni {Percent(m.WeekChange)}, oltre la soglia del {Percent(-limits.WeeklyLoss)}: rischio dimezzato per sette giorni.",
|
||
m.WeekChange, -limits.WeeklyLoss));
|
||
}
|
||
|
||
if (!state.Tripped && m.Drawdown <= -limits.DrawdownStop)
|
||
{
|
||
next = next with { Tripped = true, TrippedAt = now };
|
||
alerts.Add(new(RiskAlertKinds.DrawdownStop, RiskSeverities.Critical,
|
||
$"Calo dal massimo {Percent(m.Drawdown)}, oltre la soglia del {Percent(-limits.DrawdownStop)}: interruttore scattato, aspetto la tua conferma per ripartire.",
|
||
m.Drawdown, -limits.DrawdownStop));
|
||
}
|
||
|
||
// Warnings at 80% of a threshold: one for each crossing, again only after the measure has come back.
|
||
var warned = new List<string>(state.Warned);
|
||
void Watch(string key, decimal value, decimal threshold, string what)
|
||
{
|
||
var near = value <= -threshold * RiskLimits.WarningShare;
|
||
if (near && !warned.Contains(key))
|
||
{
|
||
warned.Add(key);
|
||
alerts.Add(new(RiskAlertKinds.Warning, RiskSeverities.Warning,
|
||
$"{what} {Percent(value)}: oltre l'80% della soglia del {Percent(-threshold)}. Nessun blocco per ora.", value, -threshold));
|
||
}
|
||
else if (!near)
|
||
{
|
||
warned.Remove(key);
|
||
}
|
||
}
|
||
|
||
Watch("day", m.DayChange, limits.DailyLoss, "Perdita di oggi");
|
||
Watch("week", m.WeekChange, limits.WeeklyLoss, "Perdita degli ultimi sette giorni");
|
||
Watch("drawdown_half", m.Drawdown, limits.DrawdownHalf, "Calo dal massimo");
|
||
Watch("drawdown_stop", m.Drawdown, limits.DrawdownStop, "Calo dal massimo");
|
||
|
||
// The halving for the fall from the high has no duration: it lasts while the fall does, and is said once.
|
||
const string halvingKey = "drawdown_half:on";
|
||
if (m.Drawdown <= -limits.DrawdownHalf)
|
||
{
|
||
if (!warned.Contains(halvingKey))
|
||
{
|
||
warned.Add(halvingKey);
|
||
alerts.Add(new(RiskAlertKinds.DrawdownHalf, RiskSeverities.High,
|
||
$"Calo dal massimo {Percent(m.Drawdown)}, oltre la soglia del {Percent(-limits.DrawdownHalf)}: rischio dimezzato finché non rientra.",
|
||
m.Drawdown, -limits.DrawdownHalf));
|
||
}
|
||
}
|
||
else
|
||
{
|
||
warned.Remove(halvingKey);
|
||
}
|
||
|
||
next = next with { Warned = warned, Peak = m.Peak is { } p ? Math.Max(p, state.Peak ?? p) : state.Peak };
|
||
return new RiskReading(next, m, alerts);
|
||
}
|
||
|
||
/// <summary>No new entries: the 24-hour block after a day's loss, or the switch tripped by the fall from the high.</summary>
|
||
public static bool EntriesBlocked(RiskMonitorState state, DateTimeOffset now)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(state);
|
||
return state.Tripped || state.DailyBlockUntil > now;
|
||
}
|
||
|
||
/// <summary>
|
||
/// The multiplier on purchases: halved for seven days after a week's loss, halved while the fall from the high is
|
||
/// beyond its first threshold, both together a quarter. Never above one (SPEC 9.1 point 5).
|
||
/// </summary>
|
||
public static decimal Multiplier(RiskMonitorState state, RiskMeasures m, DateTimeOffset now, RiskLimits limits)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(state);
|
||
ArgumentNullException.ThrowIfNull(m);
|
||
ArgumentNullException.ThrowIfNull(limits);
|
||
var multiplier = 1m;
|
||
if (state.WeeklyHalvingUntil > now)
|
||
{
|
||
multiplier *= 0.5m;
|
||
}
|
||
|
||
if (m.Drawdown <= -limits.DrawdownHalf)
|
||
{
|
||
multiplier *= 0.5m;
|
||
}
|
||
|
||
return multiplier;
|
||
}
|
||
|
||
/// <summary>
|
||
/// The user's confirmed restart after a trip (SPEC 9.3): the switch is reset and, when the trip came from the fall
|
||
/// from the high, the high starts again from now, or the switch would trip again at once.
|
||
/// </summary>
|
||
public static RiskMonitorState Restart(RiskMonitorState state, DateTimeOffset now)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(state);
|
||
return state with
|
||
{
|
||
Tripped = false,
|
||
TrippedAt = null,
|
||
PeakFrom = state.Tripped ? now : state.PeakFrom,
|
||
Peak = state.Tripped ? null : state.Peak,
|
||
Warned = [.. state.Warned.Where(w => !w.StartsWith("drawdown", StringComparison.Ordinal))],
|
||
};
|
||
}
|
||
|
||
public static string Percent(decimal change) => (change * 100m).ToString("0.0", Italian) + "%";
|
||
}
|