From 8def84e12278c9fe0a9dc3bdeef05b7ad7d2fbfe Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 15:22:35 +0100 Subject: [PATCH] Add the risk engine, correctives and strategy stages (refs #41 #42 #43) 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 --- src/Anubis.Server/AnubisHost.cs | 3 +- src/Anubis/Access/AccessStore.cs | 16 + src/Anubis/Backtest/Engine.cs | 2 +- src/Anubis/Backtest/Laboratory.cs | 5 +- src/Anubis/Backtest/Report.cs | 19 +- src/Anubis/Backtest/RiskStage.cs | 247 ++++++++ src/Anubis/Backtest/Trials.cs | 6 + src/Anubis/Core/Settings.cs | 3 +- src/Anubis/Db/Migrations/0005_risk.sql | 49 ++ src/Anubis/Risk/RiskLimits.cs | 151 +++++ src/Anubis/Risk/RiskMonitor.cs | 259 ++++++++ src/Anubis/Risk/RiskRules.cs | 155 +++++ src/Anubis/Risk/Scenarios.cs | 111 ++++ src/Anubis/Strategies/Correctives.cs | 250 ++++++++ src/Anubis/Strategies/Strategy.cs | 9 + src/Anubis/Trading/Decisions.cs | 74 +++ src/Anubis/Trading/Equity.cs | 5 +- src/Anubis/Trading/OrderManager.cs | 108 ++++ src/Anubis/Trading/RiskEngine.cs | 580 ++++++++++++++++++ src/Anubis/Trading/Stages.cs | 633 ++++++++++++++++++++ src/Anubis/Trading/TradingService.cs | 48 +- tests/Anubis.Tests/LaboratoryScreenTests.cs | 2 +- tests/Anubis.Tests/LaboratoryTests.cs | 2 +- tests/Anubis.Tests/RiskEngineTests.cs | 556 +++++++++++++++++ tests/Anubis.Tests/RiskTests.cs | 455 ++++++++++++++ 25 files changed, 3737 insertions(+), 11 deletions(-) create mode 100644 src/Anubis/Backtest/RiskStage.cs create mode 100644 src/Anubis/Db/Migrations/0005_risk.sql create mode 100644 src/Anubis/Risk/RiskLimits.cs create mode 100644 src/Anubis/Risk/RiskMonitor.cs create mode 100644 src/Anubis/Risk/RiskRules.cs create mode 100644 src/Anubis/Risk/Scenarios.cs create mode 100644 src/Anubis/Strategies/Correctives.cs create mode 100644 src/Anubis/Trading/Decisions.cs create mode 100644 src/Anubis/Trading/RiskEngine.cs create mode 100644 src/Anubis/Trading/Stages.cs create mode 100644 tests/Anubis.Tests/RiskEngineTests.cs create mode 100644 tests/Anubis.Tests/RiskTests.cs diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 56e6b63..f6aa86a 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -292,7 +292,8 @@ internal sealed partial class AnubisHost( : null; _trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file ? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId, - overrides?.MarketHttp, overrides?.MarketSockets, logger) + overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct), + Path.Combine(Config.Data.Root, "STOP")) : null; // The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none. _lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger); diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 6559b0f..62b6e8b 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -306,6 +306,22 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return true; } + /// + /// The fresh re-authentication of SPEC 12.4: the password and, when it is on, a code from the app, checked right + /// now whatever the session. Nothing is written: a wrong attempt only returns false. + /// + public async Task ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default) + { + var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u", + r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false); + if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash)) + { + return false; + } + + return user.Totp is null || AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)), code); + } + /// Turning the second factor off asks for both: the password and a code from the app. public async Task DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default) { diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index a15de41..42101aa 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -111,7 +111,7 @@ public static class BacktestReasons public static class BacktestEngine { /// Changes when the engine computes differently: plans record it, so a report says which engine made it. - public const string Version = "1"; + public const string Version = "2"; public static BacktestRun Run(IStrategy strategy, BacktestDataset data, BacktestOptions? options = null, PortfolioState? start = null) { diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 4787daa..e9a2c63 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -143,7 +143,10 @@ public sealed partial class Laboratory : IDisposable TrialValidation.Default, TrialThresholds.Default, BacktestEngine.Version, - now); + now) + { + ReferenceShare = StrategyPipeline.DefaultShare(family.Id), + }; var variants = ParameterGrid.Of(family, plan.Grid).Count; if (variants == 0) { diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 6cb6f07..f4e627c 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text.Json; using Anubis.Data; using Anubis.Strategies; @@ -116,7 +117,9 @@ public static class TrialRunner throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri."); } - var options = new BacktestOptions { InitialCapital = plan.InitialCapital }; + // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. + var plain = new BacktestOptions { InitialCapital = plan.InitialCapital }; + var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) { @@ -142,7 +145,7 @@ public static class TrialRunner costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } - var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, options); + var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, plain); var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); cancellationToken.ThrowIfCancellationRequested(); @@ -241,10 +244,20 @@ public static class TrialRunner var result = new List { "I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.", - "Il regime di mercato e i limiti di rischio arrivano con la Fase 5: in questo backtest ogni intenzione della strategia passa così com'è.", "Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.", "Sharpe e volatilità sono calcolati senza tasso privo di rischio.", }; + if (StrategyPipeline.IsBase(family.Id)) + { + var share = plan.ReferenceShare ?? StrategyPipeline.DefaultShare(family.Id) ?? 1m; + result.Add(string.Create(CultureInfo.GetCultureInfo("it-IT"), + $"Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo.")); + } + else + { + result.Add("Strategia d'esempio: correttivi e limiti di rischio non si applicano, ogni intenzione passa così com'è."); + } + if (plan.Data.Source == TrialSources.Research) { result.Add("Prezzi dello storico Binance in USDT: passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX."); diff --git a/src/Anubis/Backtest/RiskStage.cs b/src/Anubis/Backtest/RiskStage.cs new file mode 100644 index 0000000..d5cdda9 --- /dev/null +++ b/src/Anubis/Backtest/RiskStage.cs @@ -0,0 +1,247 @@ +using System.Runtime.CompilerServices; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The risk engine of SPEC 9 in the backtest of one strategy (SPEC 12.1): the same loss monitor and size rules as +/// live, measured on the strategy's closes. The strategy is one part of the bot; the rest is counted as cash that +/// does not move, so a loss of the strategy weighs on the world as its share does. Two choices of the backtest +/// (ADR 0011): every close is its own Italian day, and after the switch trips the user is assumed to restart a week +/// later, the high starting again from there. Price age, order price and clock exist only live. +/// +public sealed class BacktestRisk(RiskLimits? limits = null) : IIntentStage +{ + /// When the user is assumed to confirm the restart after the switch tripped. + public static readonly TimeSpan AssumedRestart = TimeSpan.FromDays(7); + + private readonly RiskLimits _limits = limits ?? RiskLimits.Default; + private readonly ConditionalWeakTable, Walker> _walkers = []; + + public string Name => "risk"; + + public RiskLimits Limits => _limits; + + /// Each close as a moment: noon UTC, inside its own Italian day. + public static DateTimeOffset At(DateOnly day) => new(day.ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero); + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + var walker = _walkers.GetValue(context.History, _ => new Walker(_limits)); + var (state, measures, other) = walker.Advance(context); + var now = At(context.Day); + if (state.Tripped) + { + // "Ferma tutto": nothing is bought or sold on the strategy's initiative; stops still follow it (SPEC 9.3). + return [.. intents.Select(i => i.TargetWeight is null ? i : (i with { TargetWeight = null, StopOffset = null }).Adjusted(RiskReasons.SwitchTripped))]; + } + + var blocked = RiskMonitor.EntriesBlocked(state, now); + var multiplier = RiskMonitor.Multiplier(state, measures, now, _limits); + var equity = context.Portfolio.Equity; + var invested = 0m; + var crypto = 0m; + foreach (var (symbol, h) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m)) + { + var value = h.Quantity * BookWeights.Price(context, symbol); + invested += value; + if (context.Spec(symbol)?.AssetClass == AssetClasses.Crypto) + { + crypto += value; + } + } + + var result = new List(intents.Count); + foreach (var intent in intents) + { + if (intent.TargetWeight is not { } target || equity <= 0m) + { + result.Add(intent); + continue; + } + + var current = BookWeights.Current(context, intent.Symbol); + if (target <= current) + { + result.Add(intent); + continue; + } + + if (blocked) + { + result.Add(BookWeights.Reduce(context, intent, 0m, RiskReasons.DailyLossBlock)); + continue; + } + + var price = BookWeights.Price(context, intent.Symbol); + var holding = context.Portfolio.Of(intent.Symbol); + var held = holding?.Quantity ?? 0m; + var stop = intent.Stop ?? holding?.Stop ?? (intent.StopOffset is { } offset ? price - offset : null); + var isCrypto = context.Spec(intent.Symbol)?.AssetClass == AssetClasses.Crypto; + var wanted = (target * equity / price) - held; + var size = RiskRules.SizePurchase(new PurchaseRequest + { + Price = price, + Held = held, + Wanted = wanted, + Stop = stop, + Multiplier = multiplier, + WorldEquity = equity + other, + WorldInvested = invested, + Reference = context.ReferenceEquity, + IsCrypto = isCrypto, + CryptoValue = crypto, + }, _limits); + var bought = size.Reduced ? size.Quantity : wanted; + invested += bought * price; + crypto += isCrypto ? bought * price : 0m; + if (!size.Reduced) + { + result.Add(intent); + continue; + } + + var weight = Math.Round((held + size.Quantity) * price / equity, 6, MidpointRounding.ToZero); + var adjusted = intent; + foreach (var reason in size.Reasons) + { + adjusted = adjusted.Adjusted(reason); + } + + result.Add(weight > current + ? adjusted with { TargetWeight = weight } + : held > 0m ? adjusted with { TargetWeight = null } : adjusted with { TargetWeight = null, Stop = null, StopOffset = null }); + } + + // A position heavier than the threshold comes back to it at the first chance (SPEC 9.2). + foreach (var (symbol, h) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m)) + { + var price = BookWeights.Price(context, symbol); + if (RiskRules.Excess(h.Quantity, price, context.ReferenceEquity, _limits) <= 0m) + { + continue; + } + + var most = Math.Round(_limits.MaxPosition * context.ReferenceEquity / equity, 6, MidpointRounding.ToZero); + var index = result.FindLastIndex(i => i.Symbol == symbol); + if (index >= 0 && result[index].TargetWeight is { } w && w <= most) + { + continue; + } + + if (index >= 0) + { + result[index] = (result[index] with { TargetWeight = most }).Adjusted(RiskReasons.PositionLimit); + } + else + { + result.Add(new Intent(symbol, most, RiskReasons.PositionLimit) { Adjustments = [RiskReasons.PositionLimit] }); + } + } + + return result; + } + + /// The loss monitor walked along one run's closes, one step for each new close. + private sealed class Walker(RiskLimits limits) + { + private readonly Lock _lock = new(); + private readonly List _points = []; + private RiskMonitorState _state = RiskMonitorState.Initial; + private RiskMeasures _measures = RiskMeasures.None; + private decimal _peak; + private decimal? _other; + + public (RiskMonitorState State, RiskMeasures Measures, decimal Other) Advance(StrategyContext context) + { + lock (_lock) + { + var history = context.History; + // The rest of the bot, as cash that does not move: the strategy's first equity times (1 / share − 1). + _other ??= history.Count > 0 && context.Portfolio.Equity > 0m + ? Math.Max(0m, history[0].Equity * ((context.ReferenceEquity / context.Portfolio.Equity) - 1m)) + : 0m; + for (var i = _points.Count; i < history.Count; i++) + { + var at = At(history[i].Day); + var index = history[i].Equity + _other.Value; + if (_state.Tripped && _state.TrippedAt is { } tripped && at >= tripped + AssumedRestart) + { + _state = RiskMonitor.Restart(_state, at); + _peak = 0m; + } + + _points.Add(new IndexPoint(at, index)); + _peak = Math.Max(_peak, index); + var dayBase = i > 0 ? _points[i - 1].Index : index; + var weekBase = _points[WeekBase(at - TimeSpan.FromDays(7))].Index; + _measures = new RiskMeasures(RiskMeasures.Change(index, dayBase), RiskMeasures.Change(index, weekBase), RiskMeasures.Change(index, _peak)); + _state = RiskMonitor.Step(_state, _measures, at, limits).State; + } + + return (_state, _measures, _other.Value); + } + } + + private int WeekBase(DateTimeOffset at) + { + int lo = 0, hi = _points.Count - 1, found = 0; + while (lo <= hi) + { + var mid = (lo + hi) / 2; + if (_points[mid].At <= at) + { + found = mid; + lo = mid + 1; + } + else + { + hi = mid - 1; + } + } + + return found; + } + } +} + +/// +/// The full path of a decision in the backtest (SPEC 5.2): the base strategies go through their correctives and the +/// risk engine, with the share of the bot each one has by default (SPEC 8.6: 40%, 45% and 15% with the example +/// capital). The examples of the laboratory and the buy-and-hold comparison go through as they are. +/// +public static class StrategyPipeline +{ + public static decimal? DefaultShare(string strategy) => strategy switch + { + StrategyNames.CryptoTrend => 0.40m, + StrategyNames.EquityMomentum => 0.45m, + StrategyNames.EquityMeanrev => 0.15m, + _ => null, + }; + + public static bool IsBase(string strategy) => DefaultShare(strategy) is not null; + + public static BacktestOptions For(string strategy, BacktestDataset data, BacktestOptions options, decimal? share = null) + { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(options); + if (!IsBase(strategy)) + { + return options; + } + + IReadOnlyList correctives = []; + if (strategy == StrategyNames.CryptoTrend && data.Tradable.FirstOrDefault(i => Symbols.BaseOf(i.Spec) == "BTC") is { } bitcoin) + { + correctives = [new CryptoRegimeStage(bitcoin.Symbol)]; + } + + return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? DefaultShare(strategy) }; + } +} diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 35260c8..62bdc38 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -51,6 +51,12 @@ public sealed record TrialPlan( string Engine, DateTimeOffset WrittenAt) { + /// + /// The strategy's share of the bot (SPEC 9.2): the reference equity of the backtest is its capital divided by it. + /// Null for the examples, which are not part of the bot. + /// + public decimal? ReferenceShare { get; init; } + public static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index fc66c67..47ddac9 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -41,7 +41,8 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE", Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check); - public static readonly IReadOnlyList All = [Theme, Currency, BotState, CentralBankMeetings]; + public static readonly IReadOnlyList All = + [Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary(); diff --git a/src/Anubis/Db/Migrations/0005_risk.sql b/src/Anubis/Db/Migrations/0005_risk.sql new file mode 100644 index 0000000..0419d6f --- /dev/null +++ b/src/Anubis/Db/Migrations/0005_risk.sql @@ -0,0 +1,49 @@ +-- Phase 5 schema (SPEC 5.2, 9, 12.3, 12.4, ADR 0011): the record of every stage of a decision, the state of the +-- risk engine for each world, and what a strategy needs to reach real money and to leave it. + +-- One row for each stage a decision goes through (SPEC 5.2): strategy, correctives, sizing, risk, order. Reason +-- codes and the numbers used, never free text: the diary and the "why" card are written from these rows with fixed +-- templates. decision_id groups the rows of one decision. +CREATE TABLE decisions ( + id {uuid} PRIMARY KEY, + decision_id {uuid} NOT NULL, + strategy TEXT NOT NULL, + account_id {uuid}, + symbol TEXT, + stage TEXT NOT NULL, + outcome TEXT NOT NULL, + reasons {json} NOT NULL, + data {json}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX decisions_decision ON decisions (decision_id); +CREATE INDEX decisions_strategy ON decisions (strategy, created_at); + +-- What the risk engine remembers for each world (SPEC 9.2, 9.3): blocks with their end, the moment the high is +-- measured from, the switch tripped by a limit and the warnings already sent. One row per world. +CREATE TABLE risk_state ( + id {uuid} PRIMARY KEY, + world TEXT NOT NULL UNIQUE, + state {json} NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +-- Risk events belong to a world (SPEC 9.2: a limit stops only the world where it was crossed). +ALTER TABLE risk_events ADD COLUMN world TEXT; + +CREATE INDEX risk_events_time ON risk_events (occurred_at); + +-- Stages (SPEC 12.3, 12.4, 7.1). account_id stays the account of the simulation (internal simulator or demo); +-- live_account_id is the real account, once the strategy has one. live_confirmed_at is set only by the procedure +-- of 12.4 and cleared by a revocation or a demotion; exit_only keeps a demoted strategy managing its real +-- positions down to zero. stage_since and stage_reason say since when and why the strategy is where it is; +-- qualification is the backtest outcome it qualified with, which the requirements and demotions compare against. +ALTER TABLE strategy_state ADD COLUMN live_account_id {uuid}; +ALTER TABLE strategy_state ADD COLUMN live_confirmed_at {timestamp}; +ALTER TABLE strategy_state ADD COLUMN live_confirmed_by TEXT; +ALTER TABLE strategy_state ADD COLUMN exit_only {bool}; +ALTER TABLE strategy_state ADD COLUMN stage_since {timestamp}; +ALTER TABLE strategy_state ADD COLUMN stage_reason TEXT; +ALTER TABLE strategy_state ADD COLUMN qualification {json}; diff --git a/src/Anubis/Risk/RiskLimits.cs b/src/Anubis/Risk/RiskLimits.cs new file mode 100644 index 0000000..d58ece4 --- /dev/null +++ b/src/Anubis/Risk/RiskLimits.cs @@ -0,0 +1,151 @@ +using System.Globalization; +using Anubis.Core; + +namespace Anubis.Risk; + +/// +/// The limits of SPEC 9.2 with their default values. Only the user changes them, from the settings; a change that +/// raises a limit while a strategy is in the real account needs the procedure of SPEC 12.4. +/// +public sealed record RiskLimits +{ + /// Loss in a day (Italian midnight to now): no new entries for 24 hours. + public decimal DailyLoss { get; init; } = 0.02m; + + /// Loss over the last seven days: risk halved for seven days. + public decimal WeeklyLoss { get; init; } = 0.05m; + + /// Fall from the high at which the risk is halved. + public decimal DrawdownHalf { get; init; } = 0.10m; + + /// Fall from the high at which the emergency switch trips and the bot waits for the user. + public decimal DrawdownStop { get; init; } = 0.15m; + + /// Capital in positions over the world's equity: no other purchase beyond it. + public decimal MaxInvested { get; init; } = 1m; + + /// One position over the reference equity: brought back to the threshold at the first chance. + public decimal MaxPosition { get; init; } = 0.20m; + + /// Crypto over the reference equity: no new crypto purchases beyond it. + public decimal MaxCrypto { get; init; } = 0.40m; + + /// Loss if the stop of a whole position triggered, over the reference equity: the purchase is shrunk. + public decimal MaxTradeRisk { get; init; } = 0.01m; + + /// Purchases and sales really sent to one account in a minute: beyond, the bot stops and warns. + public int OrdersPerMinute { get; init; } = 10; + + /// Age of the last price: no new entry on the instrument beyond it. + public TimeSpan MaxPriceAge { get; init; } = TimeSpan.FromSeconds(60); + + /// Distance of a purchase's limit from the last valid price: refused beyond it. + public decimal MaxPriceGap { get; init; } = 0.01m; + + /// Gap between the bot's clock and the broker's: no new entries beyond it. + public TimeSpan MaxClockSkew { get; init; } = TimeSpan.FromSeconds(2); + + /// Share of a threshold at which a warning starts, without any block (SPEC 9.2). + public const decimal WarningShare = 0.8m; + + public static TimeSpan DailyBlock { get; } = TimeSpan.FromHours(24); + + public static TimeSpan WeeklyHalving { get; } = TimeSpan.FromDays(7); + + public static RiskLimits Default { get; } = new(); + + /// True when allows more risk than this on at least one limit. + public bool RaisedBy(RiskLimits next) + { + ArgumentNullException.ThrowIfNull(next); + return next.DailyLoss > DailyLoss || next.WeeklyLoss > WeeklyLoss || next.DrawdownHalf > DrawdownHalf || next.DrawdownStop > DrawdownStop + || next.MaxInvested > MaxInvested || next.MaxPosition > MaxPosition || next.MaxCrypto > MaxCrypto || next.MaxTradeRisk > MaxTradeRisk + || next.OrdersPerMinute > OrdersPerMinute || next.MaxPriceAge > MaxPriceAge || next.MaxPriceGap > MaxPriceGap || next.MaxClockSkew > MaxClockSkew; + } +} + +/// +/// The limits as settings (SPEC 13.5): percentages and counts written as the user reads them ("2" is 2%). Every +/// change goes to the change log like any other setting. +/// +public static class RiskSettings +{ + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + public static readonly SettingDefinition DailyLoss = Percent("risk.daily_loss", "Perdita in un giorno (%)", RiskLimits.Default.DailyLoss, 0.5m, 10m); + public static readonly SettingDefinition WeeklyLoss = Percent("risk.weekly_loss", "Perdita in una settimana (%)", RiskLimits.Default.WeeklyLoss, 1m, 20m); + public static readonly SettingDefinition DrawdownHalf = Percent("risk.drawdown_half", "Calo dal massimo: rischio dimezzato (%)", RiskLimits.Default.DrawdownHalf, 2m, 30m); + public static readonly SettingDefinition DrawdownStop = Percent("risk.drawdown_stop", "Calo dal massimo: interruttore (%)", RiskLimits.Default.DrawdownStop, 3m, 40m); + public static readonly SettingDefinition MaxInvested = Percent("risk.max_invested", "Capitale investito (%)", RiskLimits.Default.MaxInvested, 10m, 100m); + public static readonly SettingDefinition MaxPosition = Percent("risk.max_position", "Peso di una sola posizione (%)", RiskLimits.Default.MaxPosition, 1m, 50m); + public static readonly SettingDefinition MaxCrypto = Percent("risk.max_crypto", "Crypto sul totale (%)", RiskLimits.Default.MaxCrypto, 0m, 100m); + public static readonly SettingDefinition MaxTradeRisk = Percent("risk.max_trade_risk", "Rischio di una singola operazione (%)", RiskLimits.Default.MaxTradeRisk, 0.1m, 5m); + + public static readonly SettingDefinition OrdersPerMinute = new("risk.orders_per_minute", "Ordini al minuto", "10", Check: v => Whole(v, 1, 60)); + + public static readonly SettingDefinition MaxPriceAge = new("risk.price_age", "Età dei prezzi (secondi)", "60", Check: v => Whole(v, 5, 600)); + + public static readonly SettingDefinition MaxPriceGap = Percent("risk.price_gap", "Prezzo dell'ordine: distanza dall'ultimo prezzo (%)", RiskLimits.Default.MaxPriceGap, 0.1m, 5m); + + public static readonly SettingDefinition MaxClockSkew = new("risk.clock_skew", "Scarto dell'orologio (secondi)", "2", Check: v => Whole(v, 1, 30)); + + /// Day-trade protection (SPEC 9.2, pdt_guard): off by default. + public static readonly SettingDefinition PdtGuard = new("risk.pdt_guard", "Protezione day trade", "off", ["off", "on"]); + + public static readonly IReadOnlyList Limits = + [DailyLoss, WeeklyLoss, DrawdownHalf, DrawdownStop, MaxInvested, MaxPosition, MaxCrypto, MaxTradeRisk, OrdersPerMinute, MaxPriceAge, MaxPriceGap, MaxClockSkew]; + + public static readonly IReadOnlyList All = [.. Limits, PdtGuard]; + + /// The limits from settings: reads a key and returns its text. + public static RiskLimits From(Func value) + { + ArgumentNullException.ThrowIfNull(value); + decimal P(SettingDefinition d) => decimal.Parse(value(d.Key), Invariant) / 100m; + int W(SettingDefinition d) => int.Parse(value(d.Key), Invariant); + return new RiskLimits + { + DailyLoss = P(DailyLoss), + WeeklyLoss = P(WeeklyLoss), + DrawdownHalf = P(DrawdownHalf), + DrawdownStop = P(DrawdownStop), + MaxInvested = P(MaxInvested), + MaxPosition = P(MaxPosition), + MaxCrypto = P(MaxCrypto), + MaxTradeRisk = P(MaxTradeRisk), + OrdersPerMinute = W(OrdersPerMinute), + MaxPriceAge = TimeSpan.FromSeconds(W(MaxPriceAge)), + MaxPriceGap = P(MaxPriceGap), + MaxClockSkew = TimeSpan.FromSeconds(W(MaxClockSkew)), + }; + } + + public static async Task LoadAsync(SettingsStore settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(settings); + var values = new Dictionary(StringComparer.Ordinal); + foreach (var definition in Limits) + { + values[definition.Key] = (await settings.GetAsync(definition.Key, cancellationToken).ConfigureAwait(false)).Value; + } + + return From(k => values[k]); + } + + public static async Task PdtGuardAsync(SettingsStore settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(settings); + return (await settings.GetAsync(PdtGuard.Key, cancellationToken).ConfigureAwait(false)).Value == "on"; + } + + private static SettingDefinition Percent(string key, string label, decimal fraction, decimal min, decimal max) => + new(key, label, (fraction * 100m).ToString("0.##", Invariant), Check: v => Number(v, min, max)); + + private static string? Number(string text, decimal min, decimal max) => + decimal.TryParse(text, NumberStyles.Number, Invariant, out var value) && value >= min && value <= max + ? null + : string.Create(CultureInfo.GetCultureInfo("it-IT"), $"Serve un numero tra {min} e {max}."); + + private static string? Whole(string text, int min, int max) => + int.TryParse(text, NumberStyles.None, Invariant, out var value) && value >= min && value <= max ? null : $"Serve un numero intero tra {min} e {max}."; +} diff --git a/src/Anubis/Risk/RiskMonitor.cs b/src/Anubis/Risk/RiskMonitor.cs new file mode 100644 index 0000000..b95a2a3 --- /dev/null +++ b/src/Anubis/Risk/RiskMonitor.cs @@ -0,0 +1,259 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Risk; + +/// A point of a world's time-weighted index: deposits and withdrawals never look like gains or losses (SPEC 7.5). +public sealed record IndexPoint(DateTimeOffset At, decimal Index); + +/// The three measures of SPEC 9.2, as changes: −0.03 is a loss of 3%. +public sealed record RiskMeasures(decimal DayChange, decimal WeekChange, decimal Drawdown) +{ + public static RiskMeasures None { get; } = new(0m, 0m, 0m); + + /// + /// The measures at : the day starts at Italian midnight, the week is the last seven days, the + /// high is the highest point since (the start, or the last confirmed restart). + /// + public static RiskMeasures From(IReadOnlyList 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 }; + } + + /// The index the measures were taken on. + public decimal? Index { get; init; } + + /// The high the fall is measured from: kept by the engine between readings, so the series can be short. + public decimal? Peak { get; init; } + + public static decimal Change(decimal current, decimal reference) => reference <= 0m ? 0m : (current / reference) - 1m; + + private static int LastAtOrBefore(IReadOnlyList 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; + } +} + +/// +/// 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). +/// +public sealed record RiskMonitorState +{ + public DateTimeOffset? DailyBlockUntil { get; init; } + + public DateTimeOffset? WeeklyHalvingUntil { get; init; } + + /// The high counts points from this moment: the start, or the last confirmed restart after a trip. + public DateTimeOffset? PeakFrom { get; init; } + + /// The highest index seen since . + public decimal? Peak { get; init; } + + /// The fall from the high reached the stop threshold: entries and sales of the strategies stop until the user confirms. + public bool Tripped { get; init; } + + public DateTimeOffset? TrippedAt { get; init; } + + /// Measures beyond 80% of their threshold, already warned about; a measure leaves the list when it comes back. + public IReadOnlyList Warned { get; init; } = []; + + public static RiskMonitorState Initial { get; } = new(); +} + +/// Something the monitor saw: a limit crossed, a warning at 80% of a threshold. +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 Alerts); + +/// +/// 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. +/// +public static class RiskMonitor +{ + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + /// Midnight in Italy of the day falls on, as a UTC moment. + 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(); + 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(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); + } + + /// No new entries: the 24-hour block after a day's loss, or the switch tripped by the fall from the high. + public static bool EntriesBlocked(RiskMonitorState state, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(state); + return state.Tripped || state.DailyBlockUntil > now; + } + + /// + /// 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). + /// + 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; + } + + /// + /// 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. + /// + 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) + "%"; +} diff --git a/src/Anubis/Risk/RiskRules.cs b/src/Anubis/Risk/RiskRules.cs new file mode 100644 index 0000000..b722a09 --- /dev/null +++ b/src/Anubis/Risk/RiskRules.cs @@ -0,0 +1,155 @@ +namespace Anubis.Risk; + +/// Reason codes of the risk engine: every reduction and every refusal leaves one (SPEC 5.2). +public static class RiskReasons +{ + public const string Reduction = "risk_reduction"; + public const string DailyLossBlock = "daily_loss_block"; + public const string SwitchTripped = "switch_tripped"; + public const string BotPaused = "bot_paused"; + public const string BotStopped = "bot_stopped"; + public const string InvestedLimit = "invested_limit"; + public const string PositionLimit = "position_limit"; + public const string CryptoLimit = "crypto_limit"; + public const string TradeRiskLimit = "trade_risk_limit"; + public const string StopAbovePrice = "stop_above_price"; + public const string StalePrice = "stale_price"; + public const string PriceGap = "price_gap"; + public const string ClockSkew = "clock_skew"; + public const string OwnedByOther = "owned_by_other_strategy"; + public const string NoShortSelling = "no_short_selling"; + public const string NoLeverage = "no_leverage"; + public const string NotOwned = "not_owned_by_bot"; + public const string LiveNotConfirmed = "live_not_confirmed"; + public const string ExitOnly = "exit_only"; + public const string NoConsent = "live_not_allowed"; + public const string Observation = "observation"; + public const string OrdersPerMinute = "orders_per_minute"; +} + +/// +/// A purchase as the risk engine sees it, every amount in one currency. is the reference +/// equity of SPEC 9.2 (a quarter of it for a strategy in reduced real); and +/// are those of the world the order belongs to. +/// +public sealed record PurchaseRequest +{ + public required decimal Price { get; init; } + + public required decimal Held { get; init; } + + public required decimal Wanted { get; init; } + + /// The stop of the whole position after the purchase; null means none, and the risk is the whole position. + public decimal? Stop { get; init; } + + /// Product of the reductions in force (correctives and loss limits): one or less. + public decimal Multiplier { get; init; } = 1m; + + public required decimal WorldEquity { get; init; } + + public required decimal WorldInvested { get; init; } + + public required decimal Reference { get; init; } + + public bool IsCrypto { get; init; } + + /// Crypto already held by the bot, on every account of the world. + public decimal CryptoValue { get; init; } +} + +public sealed record PurchaseSize(decimal Quantity, IReadOnlyList Reasons) +{ + public bool Reduced => Reasons.Count > 0; +} + +/// +/// The size rules of SPEC 9.2 on one purchase, in a fixed order. Each can only make the purchase smaller: none of +/// them, nor all together, can make it larger than what the strategy asked (SPEC 9.1 point 6). +/// +public static class RiskRules +{ + public static PurchaseSize SizePurchase(PurchaseRequest r, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(r); + ArgumentNullException.ThrowIfNull(limits); + var reasons = new List(); + var q = Math.Max(0m, r.Wanted); + if (r.Price <= 0m || q == 0m) + { + return new PurchaseSize(0m, reasons); + } + + void Cap(decimal room, string reason) + { + var most = Math.Max(0m, room); + if (q > most) + { + q = most; + reasons.Add(reason); + } + } + + // A reduction multiplies the target, not what is already held: a halved purchase is not completed while the + // halving lasts, and nothing already held is sold for it (SPEC 8.5). + var multiplier = Math.Clamp(r.Multiplier, 0m, 1m); + if (multiplier < 1m) + { + Cap(Math.Max(r.Held, multiplier * (r.Held + r.Wanted)) - r.Held, RiskReasons.Reduction); + } + + Cap(((limits.MaxInvested * r.WorldEquity) - r.WorldInvested) / r.Price, RiskReasons.InvestedLimit); + Cap((limits.MaxPosition * r.Reference / r.Price) - r.Held, RiskReasons.PositionLimit); + if (r.IsCrypto) + { + Cap(((limits.MaxCrypto * r.Reference) - r.CryptoValue) / r.Price, RiskReasons.CryptoLimit); + } + + if (r.Stop is { } stop && stop >= r.Price) + { + Cap(0m, RiskReasons.StopAbovePrice); + } + else + { + // The loss if the stop of the whole position triggered; without a stop, the whole position. + var distance = r.Stop is > 0m and var s ? r.Price - s : r.Price; + Cap((limits.MaxTradeRisk * r.Reference / distance) - r.Held, RiskReasons.TradeRiskLimit); + } + + return new PurchaseSize(q, reasons); + } + + /// What to sell of a position heavier than the threshold, to bring it back to it; zero when it is within. + public static decimal Excess(decimal held, decimal price, decimal reference, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(limits); + if (held <= 0m || price <= 0m || reference <= 0m) + { + return 0m; + } + + return Math.Max(0m, held - (limits.MaxPosition * reference / price)); + } + + /// The technical checks of SPEC 9.2: they stop entries only, never stops and sales (trap 25). + public static string? TechnicalRefusal(DateTimeOffset now, DateTimeOffset? priceAt, decimal? lastPrice, decimal? limitPrice, TimeSpan? clockSkew, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(limits); + if (priceAt is not { } at || now - at > limits.MaxPriceAge || lastPrice is not > 0m) + { + return RiskReasons.StalePrice; + } + + if (clockSkew is { } skew && skew.Duration() > limits.MaxClockSkew) + { + return RiskReasons.ClockSkew; + } + + if (limitPrice is { } limit && Math.Abs((limit / lastPrice.Value) - 1m) > limits.MaxPriceGap) + { + return RiskReasons.PriceGap; + } + + return null; + } +} diff --git a/src/Anubis/Risk/Scenarios.cs b/src/Anubis/Risk/Scenarios.cs new file mode 100644 index 0000000..de8b712 --- /dev/null +++ b/src/Anubis/Risk/Scenarios.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using Anubis.Core; + +namespace Anubis.Risk; + +/// A "what if it happened tomorrow" of SPEC 9.5: price changes of crypto and US stocks, and of the dollar on the euro. +public sealed record Scenario(string Label, decimal Crypto, decimal Stocks, decimal Dollar); + +/// A position of the bot valued in euro, with the value it would have at its stop. +public sealed record ScenarioPosition(bool IsCrypto, decimal ValueEur, decimal? ValueAtStopEur); + +public sealed record ScenarioResult(Scenario Scenario, decimal WithoutStops, decimal WithoutStopsShare, decimal? WithStops, bool SameWithStops); + +/// +/// The scenarios of the Rischio screen (SPEC 9.5): a simple sum on the positions of the moment. "Without stops" +/// applies the change to the whole value of the positions involved; "with the stops" takes for each position the +/// smaller loss between the scenario and the distance from its stop, rounded to 5 € and shown as "about", because a +/// stop does not guarantee the price. The dollar scenario applies to the value of the dollar account, stops do not +/// reduce it. +/// +public static class Scenarios +{ + public static readonly IReadOnlyList Default = + [ + new("Le crypto perdono il 20% in un giorno", -0.20m, 0m, 0m), + new("Le azioni USA perdono il 7%", 0m, -0.07m, 0m), + new("Le due cose insieme", -0.20m, -0.07m, 0m), + new("Il dollaro perde il 5% sull'euro", 0m, 0m, -0.05m), + ]; + + /// The scenarios as a setting, one per line: label; crypto %; stocks %; dollar %. + public static readonly SettingDefinition Setting = new("risk.scenarios", "Scenari \"Se succedesse domani\"", Write(Default), Check: Check); + + public static IReadOnlyList Compute(IReadOnlyList scenarios, IReadOnlyList positions, decimal dollarAccountEur, decimal equityEur) + { + ArgumentNullException.ThrowIfNull(scenarios); + ArgumentNullException.ThrowIfNull(positions); + var result = new List(); + foreach (var s in scenarios) + { + var without = 0m; + var with = 0m; + foreach (var p in positions) + { + var change = p.IsCrypto ? s.Crypto : s.Stocks; + if (change >= 0m) + { + continue; + } + + var loss = p.ValueEur * change; + without += loss; + var toStop = p.ValueAtStopEur is { } atStop ? Math.Min(0m, atStop - p.ValueEur) : loss; + with += Math.Max(loss, toStop); + } + + var dollar = dollarAccountEur * Math.Min(0m, s.Dollar); + without += dollar; + with += dollar; + var sameWithStops = s.Crypto >= 0m && s.Stocks >= 0m; + result.Add(new ScenarioResult(s, Math.Round(without, 2), equityEur > 0m ? without / equityEur : 0m, + sameWithStops ? null : Math.Round(with / 5m, MidpointRounding.AwayFromZero) * 5m, sameWithStops)); + } + + return result; + } + + public static IReadOnlyList Parse(string text) + { + ArgumentNullException.ThrowIfNull(text); + var list = new List(); + foreach (var line in text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parts = line.Split(';', StringSplitOptions.TrimEntries); + if (parts.Length != 4 || parts[0].Length == 0) + { + throw new FormatException("Ogni riga: descrizione; crypto %; azioni %; dollaro %."); + } + + list.Add(new Scenario(parts[0], Number(parts[1]) / 100m, Number(parts[2]) / 100m, Number(parts[3]) / 100m)); + } + + return list; + } + + public static string Write(IReadOnlyList scenarios) + { + ArgumentNullException.ThrowIfNull(scenarios); + return string.Join('\n', scenarios.Select(s => string.Join("; ", s.Label, Text(s.Crypto), Text(s.Stocks), Text(s.Dollar)))); + } + + private static string? Check(string text) + { + try + { + var list = Parse(text); + return list.Count is 0 or > 8 ? "Da uno a otto scenari." : list.Any(s => s.Crypto is < -1m or > 1m || s.Stocks is < -1m or > 1m || s.Dollar is < -1m or > 1m) + ? "Le variazioni vanno da −100 a +100." + : null; + } + catch (FormatException ex) + { + return ex.Message; + } + } + + private static decimal Number(string text) => + decimal.TryParse(text.Replace(',', '.').Replace('−', '-'), NumberStyles.Number, CultureInfo.InvariantCulture, out var v) ? v : throw new FormatException("Numero non valido: " + text); + + private static string Text(decimal fraction) => (fraction * 100m).ToString("0.##", CultureInfo.InvariantCulture); +} diff --git a/src/Anubis/Strategies/Correctives.cs b/src/Anubis/Strategies/Correctives.cs new file mode 100644 index 0000000..a40645b --- /dev/null +++ b/src/Anubis/Strategies/Correctives.cs @@ -0,0 +1,250 @@ +using Anubis.Data; + +namespace Anubis.Strategies; + +/// Reason codes of the correctives (SPEC 8.5): each intervention leaves its own. +public static class CorrectiveReasons +{ + public const string CryptoRegimeAverage = "crypto_regime_below_average"; + public const string CryptoRegimeVolatility = "crypto_regime_high_volatility"; + public const string CalendarEvent = "calendar_event"; +} + +/// Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them. +public static class BookWeights +{ + /// The last price of an instrument: today's close, or the average price when there are no bars. + public static decimal Price(StrategyContext context, string symbol) + { + ArgumentNullException.ThrowIfNull(context); + var bars = context.Bars(symbol); + return bars.Count > 0 ? (decimal)bars.Close(bars.Count - 1) : context.Portfolio.Of(symbol)?.AveragePrice ?? 0m; + } + + public static decimal Current(StrategyContext context, string symbol) + { + ArgumentNullException.ThrowIfNull(context); + var holding = context.Portfolio.Of(symbol); + var equity = context.Portfolio.Equity; + return holding is not { Quantity: > 0m } || equity <= 0m ? 0m : holding.Quantity * Price(context, symbol) / equity; + } + + /// + /// A reduction of SPEC 8.5 on one intent: the multiplier applies to the target, never to what is held, so a + /// halved purchase is not completed while the halving lasts and nothing is sold because of it. Exits, decreases + /// and stop updates pass unchanged. + /// + public static Intent Reduce(StrategyContext context, Intent intent, decimal multiplier, string code) + { + ArgumentNullException.ThrowIfNull(intent); + if (intent.TargetWeight is not { } target || multiplier >= 1m) + { + return intent; + } + + var current = Current(context, intent.Symbol); + if (target <= current) + { + return intent; + } + + var reduced = Math.Max(current, Math.Round(Math.Max(0m, multiplier) * target, 6, MidpointRounding.ToZero)); + if (reduced <= current) + { + // Nothing more to buy: a position stays as it is, its stop still following the strategy; a new entry + // stays in the record with its reason code and does nothing. + return current > 0m + ? (intent with { TargetWeight = null }).Adjusted(code) + : (intent with { TargetWeight = null, Stop = null, StopOffset = null }).Adjusted(code); + } + + return (intent with { TargetWeight = reduced }).Adjusted(code); + } +} + +public sealed record CryptoRegimeSettings +{ + public int AverageDays { get; init; } = 200; + + /// Volatility measured on 30 daily returns, compared with its own values of the last two years. + public int VolatilityDays { get; init; } = 30; + + public int PercentileDays { get; init; } = 730; + + public double Percentile { get; init; } = 0.9; + + /// Fewer values than this and the percentile is not used: a year is the least to call something high. + public int MinPercentileDays { get; init; } = 365; + + public decimal Multiplier { get; init; } = 0.5m; +} + +/// +/// The crypto regime of SPEC 8.5: when Bitcoin closes below its 200-day average, or its volatility is above the 90th +/// percentile of the last two years, new entries of crypto_trend are halved. +/// +public static class CryptoRegime +{ + /// Null when the regime is calm, otherwise the reason code. + public static string? Risky(BarSeries btc, CryptoRegimeSettings settings) + { + ArgumentNullException.ThrowIfNull(btc); + ArgumentNullException.ThrowIfNull(settings); + if (btc.Count == 0) + { + return null; + } + + if (Indicators.Sma(btc, settings.AverageDays) is { } average && btc.Close(btc.Count - 1) < average) + { + return CorrectiveReasons.CryptoRegimeAverage; + } + + var vols = RollingVolatility(btc, settings.VolatilityDays, settings.PercentileDays); + if (vols.Length < settings.MinPercentileDays) + { + return null; + } + + var today = vols[^1]; + var sorted = vols.Order().ToArray(); + var threshold = sorted[(int)Math.Min(sorted.Length - 1, Math.Floor(settings.Percentile * (sorted.Length - 1)))]; + return today > threshold ? CorrectiveReasons.CryptoRegimeVolatility : null; + } + + /// Standard deviation of the last daily log returns, for each of the last days. + public static double[] RollingVolatility(BarSeries bars, int window, int days) + { + ArgumentNullException.ThrowIfNull(bars); + var n = bars.Count; + var available = n - window; + if (available <= 0) + { + return []; + } + + var count = Math.Min(days, available); + var first = n - count - window; + var returns = new double[count + window - 1]; + for (var i = 0; i < returns.Length; i++) + { + returns[i] = Math.Log(bars.Close(first + i + 1) / bars.Close(first + i)); + } + + var result = new double[count]; + double sum = 0, squares = 0; + for (var i = 0; i < returns.Length; i++) + { + sum += returns[i]; + squares += returns[i] * returns[i]; + if (i >= window) + { + sum -= returns[i - window]; + squares -= returns[i - window] * returns[i - window]; + } + + if (i >= window - 1 && i - (window - 1) < count) + { + var mean = sum / window; + result[i - (window - 1)] = Math.Sqrt(Math.Max(0, (squares - (window * mean * mean)) / (window - 1))); + } + } + + return result; + } +} + +/// The crypto regime as a step of the decision: it reduces the entries of the strategy it is given to. +public sealed class CryptoRegimeStage(string bitcoin, CryptoRegimeSettings? settings = null) : IIntentStage +{ + private readonly CryptoRegimeSettings _settings = settings ?? new CryptoRegimeSettings(); + + public string Name => "crypto_regime"; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + if (!intents.Any(i => i.TargetWeight > 0m) || CryptoRegime.Risky(context.Bars(bitcoin), _settings) is not { } code) + { + return intents; + } + + return [.. intents.Select(i => BookWeights.Reduce(context, i, _settings.Multiplier, code))]; + } +} + +/// +/// The calendar of SPEC 8.5: no new entries from 30 minutes before to 30 minutes after a high-impact US figure, and +/// to 60 minutes after a Fed or ECB decision. A blocked entry is tried again at the end of the window in the same +/// session; when the session ends first it is dropped. Crypto has no sessions: the deadline is 12:00 UTC of the day. +/// +public static class CalendarBlocks +{ + public static TimeSpan Before { get; } = TimeSpan.FromMinutes(30); + + public static TimeSpan After { get; } = TimeSpan.FromMinutes(30); + + public static TimeSpan AfterCentralBank { get; } = TimeSpan.FromMinutes(60); + + /// The window of an event that blocks entries, or null for one that does not (low impact, another currency, no time). + public static (DateTimeOffset From, DateTimeOffset To)? Window(CalendarEvent e) + { + ArgumentNullException.ThrowIfNull(e); + if (!e.TimeKnown) + { + return null; + } + + return e.Kind switch + { + CalendarEventKinds.CentralBank => (e.OccursAt - Before, e.OccursAt + AfterCentralBank), + CalendarEventKinds.Economic when e.Currency == "USD" && string.Equals(e.Impact, "High", StringComparison.OrdinalIgnoreCase) => (e.OccursAt - Before, e.OccursAt + After), + _ => null, + }; + } + + /// The end of the block falls in, following windows that overlap; null when there is none. + public static DateTimeOffset? BlockedUntil(DateTimeOffset at, IEnumerable events) + { + ArgumentNullException.ThrowIfNull(events); + var windows = events.Select(Window).OfType<(DateTimeOffset From, DateTimeOffset To)>().OrderBy(w => w.From).ToList(); + DateTimeOffset? until = null; + var moment = at; + foreach (var (from, to) in windows) + { + if (from <= moment && to > moment) + { + until = to; + moment = to; + } + } + + return until; + } + + /// When a blocked entry is tried again; null means it is dropped, with its reason code. + public static DateTimeOffset? RetryAt(DateTimeOffset at, IEnumerable events, DateTimeOffset deadline) => + BlockedUntil(at, events) is { } end ? end <= deadline ? end : null : at; + + /// The deadline of a crypto entry (SPEC 5.6): 12:00 UTC of the same day. + public static DateTimeOffset CryptoDeadline(DateTimeOffset at) => new(at.UtcDateTime.Date.AddHours(12), TimeSpan.Zero); +} + +/// The calendar block as a step of the decision: during a window no intent may increase a position. +public sealed class CalendarStage(Func> events) : IIntentStage +{ + public string Name => "calendar"; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + if (!intents.Any(i => i.TargetWeight > 0m) || CalendarBlocks.BlockedUntil(context.Now, events(context.Now)) is null) + { + return intents; + } + + return [.. intents.Select(i => BookWeights.Reduce(context, i, 0m, CorrectiveReasons.CalendarEvent))]; + } +} diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index d34f3c4..992f172 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -40,6 +40,15 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason) /// public bool AtClose { get; init; } + /// + /// Reason codes of the correctives and of the risk engine that changed this intent after the strategy (SPEC 5.2): + /// empty when it passed as the strategy proposed it. + /// + public IReadOnlyList Adjustments { get; init; } = []; + + /// The same intent with one more adjustment code. + public Intent Adjusted(string code) => this with { Adjustments = [.. Adjustments, code] }; + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Symbol} {(TargetWeight is { } w ? w.ToString(CultureInfo.InvariantCulture) : "keep")} stop {(Stop is { } s ? s.ToString(CultureInfo.InvariantCulture) : "-")} ({Reason})"); } diff --git a/src/Anubis/Trading/Decisions.cs b/src/Anubis/Trading/Decisions.cs new file mode 100644 index 0000000..9473730 --- /dev/null +++ b/src/Anubis/Trading/Decisions.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Stages of a decision (SPEC 5.2), in the order they are crossed. +public static class DecisionStages +{ + public const string Strategy = "strategy"; + public const string Correctives = "correctives"; + public const string Sizing = "sizing"; + public const string Risk = "risk"; + public const string Order = "order"; + + /// The one-step comparison of SPEC 12.3: live intents against the backtest restarted from the recorded state. + public const string OneStep = "one_step"; +} + +public static class DecisionOutcomes +{ + public const string Proposed = "proposed"; + public const string Passed = "passed"; + public const string Reduced = "reduced"; + public const string Refused = "refused"; + public const string Same = "same"; + public const string Different = "different"; +} + +/// A row of the decisions table: a stage, its outcome, its reason codes and the numbers it used. +public sealed record DecisionRow(Guid DecisionId, string Strategy, Guid? AccountId, string? Symbol, string Stage, string Outcome, IReadOnlyList Reasons, + IReadOnlyDictionary? Data, DateTimeOffset At); + +/// +/// The record of every decision (SPEC 5.2): each stage writes one row with reason codes and values, never free text. +/// The diary and the "why" card are built from these rows with fixed templates. +/// +public sealed class DecisionLog(Database db, IClock clock) +{ + public Task WriteAsync(DecisionRow row, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(row); + return db.WriteAsync(s => WriteAsync(s, clock, row, cancellationToken), cancellationToken); + } + + public static Task WriteAsync(DbSession s, IClock clock, DecisionRow row, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(row); + return s.ExecuteAsync( + "INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, @data, @t)", + cancellationToken, ("id", Ids.NewId(clock)), ("d", row.DecisionId), ("s", row.Strategy), ("a", row.AccountId), ("sym", row.Symbol), ("st", row.Stage), ("o", row.Outcome), + ("r", new DbJson(JsonSerializer.Serialize(row.Reasons))), ("data", row.Data is null ? null : new DbJson(JsonSerializer.Serialize(row.Data))), ("t", row.At)); + } + + /// Every stage of one decision, in order. + public Task> OfAsync(Guid decisionId, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at FROM decisions WHERE decision_id = @d ORDER BY created_at, id", + Read, ("d", decisionId)), cancellationToken); + + /// The latest rows of a strategy, or of every strategy, newest first. + public Task> RecentAsync(string? strategy, int limit, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync( + "SELECT decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at FROM decisions" + (strategy is null ? "" : " WHERE strategy = @s") + + " ORDER BY created_at DESC, id DESC LIMIT @n", Read, strategy is null ? [("n", limit)] : [("s", strategy), ("n", limit)]), cancellationToken); + + private static DecisionRow Read(DbRow r) + { + var data = r.TextOrNull("data") is { } json ? JsonSerializer.Deserialize>(json) : null; + return new DecisionRow(r.Id("decision_id"), r.Text("strategy"), r.IdOrNull("account_id"), r.TextOrNull("symbol"), r.Text("stage"), r.Text("outcome"), + JsonSerializer.Deserialize>(r.Text("reasons")) ?? [], data, r.Moment("created_at")); + } +} diff --git a/src/Anubis/Trading/Equity.cs b/src/Anubis/Trading/Equity.cs index 370de17..768dbbf 100644 --- a/src/Anubis/Trading/Equity.cs +++ b/src/Anubis/Trading/Equity.cs @@ -73,7 +73,10 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore } } - foreach (var group in shots.GroupBy(s => s.AccountId)) + // The simulated twin of a strategy with real money is photographed, but stays out of the totals (SPEC 12.3). + var twins = (await db.ReadAsync(s => s.QueryAsync("SELECT strategy, account_id FROM strategy_state WHERE stage IN ('reduced', 'real') AND account_id IS NOT NULL", + r => (Strategy: r.Text("strategy"), Account: r.Id("account_id"))), cancellationToken).ConfigureAwait(false)).ToHashSet(); + foreach (var group in shots.Where(s => !twins.Contains((s.Strategy!, s.AccountId!.Value))).GroupBy(s => s.AccountId)) { var first = group.First(); shots.Add(new Shot("account", first.World, first.AccountId, null, first.Currency, group.Sum(s => s.Equity), group.Sum(s => s.Cash), group.Sum(s => s.Invested), diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index a72cece..ae01c7f 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -15,6 +15,14 @@ public sealed record TradeIntent(Guid InstrumentId, string Strategy, OrderSide S public decimal? StopLevel { get; init; } } +/// What the risk engine says of an intent: the quantity allowed (never more than asked), or why it is refused. +public sealed record GateResult(decimal Quantity, string? Refusal, IReadOnlyList Reasons) +{ + public static GateResult Pass(decimal quantity) => new(quantity, null, []); + + public static GateResult Refuse(string reason) => new(0m, reason, [reason]); +} + /// The account an order manager works on. public sealed record AccountContext(Guid AccountId, string Name, string Broker, string Environment, string Currency); @@ -127,6 +135,21 @@ public sealed partial class OrderManager : IDisposable /// Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5). public Func? AfterFills { get; init; } + /// + /// The risk engine (SPEC 9): every intent crosses it before it becomes an execution, and it may refuse it or + /// make it smaller. Protection always passes. + /// + public Func>? Gate { get; init; } + + /// + /// The permission of SPEC 12.4 for a real account, asked again right before every order leaves. Without it an + /// order manager on a real account sends nothing but protection: it fails closed. + /// + public Func>? LivePermit { get; init; } + + /// The technical check of a purchase's limit against the last valid price (SPEC 9.2): a reason refuses it. + public Func? PurchasePriceCheck { get; init; } + public AccountContext Account => _account; public IBrokerAccount Broker => _broker; @@ -155,6 +178,29 @@ public sealed partial class OrderManager : IDisposable return (null, OrderReasons.PrudentMode); } + if (await LiveRefusalAsync(intent, cancellationToken).ConfigureAwait(false) is { } live) + { + return (null, live); + } + + if (Gate is not null && intent.Purpose != OrderPurpose.Protective) + { + var verdict = await Gate(intent, _account, cancellationToken).ConfigureAwait(false); + if (verdict.Refusal is { } refusal) + { + return (null, refusal); + } + + if (verdict.Quantity < intent.Quantity) + { + intent = intent with { Quantity = verdict.Quantity }; + if (intent.Quantity <= 0m) + { + return (null, OrderReasons.ZeroQuantity); + } + } + } + var id = Ids.NewId(_clock); var now = _clock.UtcNow; await _db.WriteAsync(s => s.ExecuteAsync( @@ -327,6 +373,55 @@ public sealed partial class OrderManager : IDisposable _db.ReadAsync>(async s => (await s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)).ConfigureAwait(false)).Select(o => (o.ClientOrderId, o.InstrumentId, o.Purpose)).ToList(), cancellationToken); + /// + /// Cancels the executions under way, except protective sales (SPEC 9.3, "Ferma tutto"): the open order of each is + /// canceled with the broker, and the stops it had removed come back at once for the quantity held. + /// + public async Task CancelWorkingAsync(string reason, Func? strategy = null, CancellationToken cancellationToken = default) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var count = 0; + foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false)) + { + if (exec.Purpose == OrderPurpose.Protective || (strategy is not null && !strategy(exec.Strategy))) + { + continue; + } + + var instrument = await _instruments(exec.InstrumentId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("Unknown instrument " + exec.InstrumentId); + var orders = await ExecutionOrdersAsync(exec.Id, cancellationToken).ConfigureAwait(false); + if (orders.LastOrDefault() is { } current && !OrderStates.IsFinal(current.Status)) + { + await CancelAndReadAsync(current, instrument, reason, cancellationToken).ConfigureAwait(false); + } + + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false); + count++; + } + + return count; + } + finally + { + _gate.Release(); + } + } + + // A real account sends only what the procedure of SPEC 12.4 allows; protection of what the bot holds always goes. + private async Task LiveRefusalAsync(TradeIntent intent, CancellationToken cancellationToken) + { + if (_account.Environment != TradingEnvironments.Live || intent.Purpose == OrderPurpose.Protective) + { + return null; + } + + return LivePermit is null ? Risk.RiskReasons.LiveNotConfirmed : await LivePermit(intent, _account, cancellationToken).ConfigureAwait(false); + } + public Task IsPrudentAsync(CancellationToken cancellationToken) => _db.ReadAsync(async s => await s.FirstOrDefaultAsync("SELECT mode FROM account_status WHERE account_id = @a", r => r.Text("mode"), ("a", _account.AccountId)).ConfigureAwait(false) == AccountModes.Prudent, cancellationToken); @@ -500,6 +595,19 @@ public sealed partial class OrderManager : IDisposable return; } + // Asked again right before the order leaves: a revocation or a demotion meanwhile stops it here. + if (await LiveRefusalAsync(new TradeIntent(exec.InstrumentId, exec.Strategy, exec.Side, remaining, exec.Purpose, Guid.Empty), cancellationToken).ConfigureAwait(false) is { } live) + { + await FinishAsync(exec, ExecutionStates.Canceled, live, instrument, cancellationToken).ConfigureAwait(false); + return; + } + + if (exec.Side == OrderSide.Buy && rounded.LimitPrice is { } price && PurchasePriceCheck?.Invoke(price, quote) is { } gap) + { + await FinishAsync(exec, ExecutionStates.Canceled, gap, instrument, cancellationToken).ConfigureAwait(false); + return; + } + var sequence = exec.Sequence + 1; var clientId = ClientOrderIds.Build(_installation, _account.Environment, exec.Strategy, exec.Purpose, exec.Key, sequence); var now = _clock.UtcNow; diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs new file mode 100644 index 0000000..bb68abf --- /dev/null +++ b/src/Anubis/Trading/RiskEngine.cs @@ -0,0 +1,580 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Risk; + +namespace Anubis.Trading; + +/// A world as the risk engine sees it now: what it remembers, the three measures, the multiplier on purchases. +public sealed record WorldRisk(string World, RiskMonitorState State, RiskMeasures Measures, decimal Multiplier, bool EntriesBlocked); + +/// Exposure of the bot in euro, from the ledgers: equity and invested per world, crypto everywhere. Twins are left out. +public sealed record RiskExposure(decimal SimulatedEquity, decimal SimulatedInvested, decimal RealEquity, decimal RealInvested, decimal Crypto) +{ + public decimal Equity(string world) => world == Worlds.Real ? RealEquity : SimulatedEquity; + + public decimal Invested(string world) => world == Worlds.Real ? RealInvested : SimulatedInvested; +} + +/// What the bot as a whole remembers: a "stop and close all" still waiting for markets to open. +public sealed record BotRiskState +{ + public bool CloseAll { get; init; } + + public DateTimeOffset? CloseAllSince { get; init; } +} + +/// +/// The risk engine (SPEC 9): every intent of a strategy crosses it before it becomes an order, and nothing gets +/// around it. It refuses or shrinks, never enlarges (9.1 point 6). It watches the losses of each world, trips the +/// switch of the world that crossed a limit (9.2), stops the bot on an anomaly of orders per minute or on the file +/// /data/STOP, and restarts only on the user's confirmation (9.3). Protection always passes. +/// +public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBook stages, SettingsStore settings, FxStore fx, + Func> instruments, Func> quotes) +{ + public const string BotRow = "bot"; + public const string PdtReason = "pdt_guard"; + public const string UnknownInstrument = "unknown_instrument"; + public const string NoRate = "no_fx_rate"; + public const int PdtMaxDayTrades = 3; + + private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + /// The file that stops the bot (SPEC 9.3): /data/STOP in Docker, the data folder on desktop. + public string? StopFile { get; init; } + + /// The clock skew measured with a broker, when known (SPEC 9.2): beyond the limit no new entries. + public Func? ClockSkew { get; init; } + + public bool StopRequested => StopFile is { } path && File.Exists(path); + + /// The gate of the order manager: the verdict on an intent, written to the decisions table (SPEC 5.2). + public async Task GateAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(intent); + ArgumentNullException.ThrowIfNull(account); + if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop) + { + return GateResult.Pass(intent.Quantity); + } + + var (result, data) = await DecideAsync(intent, account, cancellationToken).ConfigureAwait(false); + var outcome = result.Refusal is not null ? DecisionOutcomes.Refused : result.Quantity < intent.Quantity ? DecisionOutcomes.Reduced : DecisionOutcomes.Passed; + var instrument = await instruments(intent.InstrumentId, cancellationToken).ConfigureAwait(false); + data["asked"] = intent.Quantity; + data["allowed"] = result.Quantity; + await db.WriteAsync(s => DecisionLog.WriteAsync(s, clock, new DecisionRow(intent.DecisionId, intent.Strategy, account.AccountId, instrument?.Symbol, DecisionStages.Risk, outcome, + result.Reasons, data, clock.UtcNow), cancellationToken), cancellationToken).ConfigureAwait(false); + return result; + } + + private async Task<(GateResult Result, Dictionary Data)> DecideAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken) + { + var data = new Dictionary(StringComparer.Ordinal); + var now = clock.UtcNow; + var botState = (await settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; + if (botState == "stopped" || StopRequested) + { + return (GateResult.Refuse(RiskReasons.BotStopped), data); + } + + var stage = await stages.GetAsync(intent.Strategy, cancellationToken).ConfigureAwait(false); + var world = WorldOf(account, stage); + data["world"] = world; + var risk = await WorldAsync(world, cancellationToken).ConfigureAwait(false); + if (risk.State.Tripped) + { + return (GateResult.Refuse(RiskReasons.SwitchTripped), data); + } + + if (await instruments(intent.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + return (GateResult.Refuse(UnknownInstrument), data); + } + + var position = await ledger.PositionAsync(account.AccountId, intent.InstrumentId, intent.Strategy, cancellationToken).ConfigureAwait(false); + var held = position?.Quantity ?? 0m; + data["held"] = held; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + var pdt = account.Broker == Venues.Alpaca && await RiskSettings.PdtGuardAsync(settings, cancellationToken).ConfigureAwait(false); + if (intent.Side == OrderSide.Sell) + { + // Only what this strategy bought, never more than it holds (SPEC 9.1 points 1 and 3). + if (held <= 0m) + { + var others = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.InstrumentId == intent.InstrumentId); + return (GateResult.Refuse(others ? RiskReasons.OwnedByOther : RiskReasons.NotOwned), data); + } + + if (pdt && intent.Strategy == StrategyNames.EquityMeanrev && NewYorkDay(position!.OpenedAt) == NewYorkDay(now)) + { + // With the guard on, mean reversion never leaves on the day it entered: the stop protects it (SPEC 9.2). + return (GateResult.Refuse(PdtReason), data); + } + + return intent.Quantity > held ? (new GateResult(held, null, [RiskReasons.NoShortSelling]), data) : (GateResult.Pass(intent.Quantity), data); + } + + if (intent.Purpose != OrderPurpose.Entry) + { + return (GateResult.Refuse(RiskReasons.NoShortSelling), data); + } + + if (botState == "paused") + { + return (GateResult.Refuse(RiskReasons.BotPaused), data); + } + + if (stage?.Stage == StrategyStages.Observation) + { + return (GateResult.Refuse(RiskReasons.Observation), data); + } + + if (RiskMonitor.EntriesBlocked(risk.State, now)) + { + return (GateResult.Refuse(RiskReasons.DailyLossBlock), data); + } + + var quote = await quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (RiskRules.TechnicalRefusal(now, quote?.At, quote?.Mid, null, ClockSkew?.Invoke(account.Broker), limits) is { } technical) + { + return (GateResult.Refuse(technical), data); + } + + if (pdt && await PdtRoomAsync(account.AccountId, cancellationToken).ConfigureAwait(false) <= 0) + { + return (GateResult.Refuse(PdtReason), data); + } + + var rate = account.Currency == "EUR" ? 1m : await UsdRateAsync(cancellationToken).ConfigureAwait(false); + if (rate is not > 0m) + { + return (GateResult.Refuse(NoRate), data); + } + + var exposure = await ExposureAsync(cancellationToken).ConfigureAwait(false); + var reference = await ReferenceAsync(cancellationToken).ConfigureAwait(false); + + // A strategy in reduced real works on a quarter: its limits apply on a quarter of the reference (SPEC 9.2). + var quarter = stage?.Stage == StrategyStages.Reduced && account.Environment == TradingEnvironments.Live ? StrategyStages.ReducedShare : 1m; + var price = quote!.Ask > 0m ? quote.Ask : quote.Mid; + var request = new PurchaseRequest + { + Price = price, + Held = held, + Wanted = intent.Quantity, + Stop = intent.StopLevel ?? position?.StopPrice, + Multiplier = risk.Multiplier, + WorldEquity = exposure.Equity(world) * rate.Value, + WorldInvested = exposure.Invested(world) * rate.Value, + Reference = reference * rate.Value * quarter, + IsCrypto = instrument.IsCrypto, + CryptoValue = exposure.Crypto * rate.Value * quarter, + }; + data["price"] = price; + data["multiplier"] = risk.Multiplier; + data["reference"] = request.Reference; + data["world_equity"] = request.WorldEquity; + var size = RiskRules.SizePurchase(request, limits); + var quantity = size.Quantity; + var reasons = size.Reasons.ToList(); + + // No leverage, and a strategy never goes beyond its own capital (SPEC 9.1 point 1, 8.6). + var cash = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(e => e.AccountId == account.AccountId && e.Strategy == intent.Strategy)?.Cash ?? 0m; + data["cash"] = cash; + if (quantity * price > cash) + { + quantity = Math.Max(0m, cash / price); + reasons.Add(RiskReasons.NoLeverage); + } + + quantity = Math.Min(quantity, intent.Quantity); + if (quantity <= 0m) + { + var reason = reasons.Count > 0 ? reasons[^1] : RiskReasons.Reduction; + return (new GateResult(0m, reason, reasons.Count > 0 ? reasons : [reason]), data); + } + + return (new GateResult(quantity, null, reasons), data); + } + + /// + /// The world an order counts in (SPEC 7.1, 12.3): real accounts in the real world, the rest in simulation; the + /// twin of a strategy with real money follows the blocks of the real strategy. + /// + public static string WorldOf(AccountContext account, StrategyStage? stage) + { + ArgumentNullException.ThrowIfNull(account); + if (account.Environment == TradingEnvironments.Live) + { + return Worlds.Real; + } + + return stage is { HasTwin: true } && stage.AccountId == account.AccountId ? Worlds.Real : Worlds.Simulated; + } + + /// The state of a world with its measures now. + public async Task WorldAsync(string world, CancellationToken cancellationToken) + { + var state = await LoadAsync(world, cancellationToken).ConfigureAwait(false) ?? RiskMonitorState.Initial; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + var now = clock.UtcNow; + var measures = RiskMeasures.From(await SeriesAsync(world, cancellationToken).ConfigureAwait(false), now, state.PeakFrom, state.Peak); + return new WorldRisk(world, state, measures, RiskMonitor.Multiplier(state, measures, now, limits), RiskMonitor.EntriesBlocked(state, now)); + } + + /// + /// The periodic check (SPEC 9.2, 9.3): the measures of each world with its blocks, warnings and switch; the + /// orders per minute of each account; the file /data/STOP; a "stop and close all" waiting for the open. + /// + public async Task> CheckAsync(IReadOnlyCollection managers, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + var alerts = new List(); + var now = clock.UtcNow; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + foreach (var world in new[] { Worlds.Simulated, Worlds.Real }) + { + var state = await LoadAsync(world, cancellationToken).ConfigureAwait(false) ?? RiskMonitorState.Initial with { PeakFrom = now }; + var series = await SeriesAsync(world, cancellationToken).ConfigureAwait(false); + if (series.Count == 0) + { + continue; + } + + var reading = RiskMonitor.Step(state, RiskMeasures.From(series, now, state.PeakFrom, state.Peak), now, limits); + await SaveAsync(world, reading.State, cancellationToken).ConfigureAwait(false); + foreach (var alert in reading.Alerts) + { + await RecordAsync(world, alert.Kind, alert.Severity, alert.Message, new { alert.Value, alert.Threshold }, cancellationToken).ConfigureAwait(false); + } + + if (reading.State.Tripped && !state.Tripped) + { + // The switch stops only the world that crossed the limit (SPEC 9.2). + await CancelAsync(managers, world, "switch_tripped", cancellationToken).ConfigureAwait(false); + } + + alerts.AddRange(reading.Alerts); + } + + var from = now - TimeSpan.FromMinutes(1); + var sent = await db.ReadAsync(s => s.QueryAsync( + "SELECT account_id, COUNT(*) AS n FROM orders WHERE submitted_at >= @f AND purpose IN ('entry', 'exit') GROUP BY account_id", + r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", from)), cancellationToken).ConfigureAwait(false); + if (sent.FirstOrDefault(x => x.Count >= limits.OrdersPerMinute) is { Count: > 0 } burst) + { + var message = $"{burst.Count} ordini inviati in un minuto su un conto, oltre il limite di {limits.OrdersPerMinute}: fermo il bot, può essere un guasto."; + await StopAllAsync(managers, "automatico", RiskReasons.OrdersPerMinute, message, cancellationToken).ConfigureAwait(false); + alerts.Add(new RiskAlert(RiskReasons.OrdersPerMinute, RiskSeverities.Critical, message, burst.Count, limits.OrdersPerMinute)); + } + + if (StopRequested && (await settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value != "stopped") + { + await StopAllAsync(managers, "file STOP", "stop_file", "Ho trovato il file STOP nella cartella dei dati: fermo tutto. Per ripartire toglilo e conferma dall'interfaccia.", + cancellationToken).ConfigureAwait(false); + } + + await ContinueCloseAllAsync(managers, cancellationToken).ConfigureAwait(false); + return alerts; + } + + /// + /// "Ferma tutto" (SPEC 9.3): no new entries and no sales of the strategies, the orders under way canceled except + /// protection; the stops stay and are put back where a canceled sale had removed them. + /// + public async Task StopAllAsync(IReadOnlyCollection managers, string by, string reason, string message, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + await settings.SetAsync(SettingsStore.BotState.Key, "stopped", by, cancellationToken).ConfigureAwait(false); + await RecordAsync(null, reason, RiskSeverities.Critical, message, new { by }, cancellationToken).ConfigureAwait(false); + foreach (var manager in managers) + { + await manager.CancelWorkingAsync(reason, cancellationToken: cancellationToken).ConfigureAwait(false); + } + } + + /// + /// "Ferma e chiudi tutte le posizioni" (SPEC 9.3), after the user's confirmation: everything stops, then + /// everything the bot holds is sold at market. A position's stop goes only when its sale leaves; what belongs to a + /// closed market leaves at the open and keeps its stop until then. + /// + public async Task CloseAllAsync(IReadOnlyCollection managers, string by, CancellationToken cancellationToken) + { + await StopAllAsync(managers, by, "close_all", "Fermo tutto e vendo a mercato ogni posizione del bot: ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop.", + cancellationToken).ConfigureAwait(false); + await SaveAsync(BotRow, new BotRiskState { CloseAll = true, CloseAllSince = clock.UtcNow }, cancellationToken).ConfigureAwait(false); + await ContinueCloseAllAsync(managers, cancellationToken).ConfigureAwait(false); + } + + /// Sends the sales of a "stop and close all" whose market is now open. Returns how many positions are still waiting. + public async Task ContinueCloseAllAsync(IReadOnlyCollection managers, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + if (await LoadAsync(BotRow, cancellationToken).ConfigureAwait(false) is not { CloseAll: true }) + { + return 0; + } + + var waiting = 0; + foreach (var manager in managers) + { + foreach (var position in await ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)) + { + if (await instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + continue; + } + + if (manager.MarketOpen is not null && !await manager.MarketOpen(instrument, cancellationToken).ConfigureAwait(false)) + { + waiting++; + continue; + } + + var selling = await db.ReadAsync(s => s.CountAsync( + "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w AND side = 'sell'", + ("a", position.AccountId), ("i", position.InstrumentId), ("s", position.Strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + if (selling == 0) + { + await manager.SubmitAsync(new TradeIntent(position.InstrumentId, position.Strategy, OrderSide.Sell, position.Quantity, OrderPurpose.Protective, Ids.NewId(clock)), + cancellationToken).ConfigureAwait(false); + } + } + } + + if (waiting == 0 && (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Count == 0) + { + await SaveAsync(BotRow, new BotRiskState(), cancellationToken).ConfigureAwait(false); + } + + return waiting; + } + + /// + /// The restart after "Ferma tutto" or a tripped switch, confirmed by the user in the interface (SPEC 9.3): never by + /// itself, never from Telegram. When the trip came from the fall from the high, the high starts again from now. + /// + public async Task RestartAsync(string by, CancellationToken cancellationToken) + { + if (StopRequested) + { + throw new InvalidOperationException("Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire."); + } + + var now = clock.UtcNow; + foreach (var world in new[] { Worlds.Simulated, Worlds.Real }) + { + if (await LoadAsync(world, cancellationToken).ConfigureAwait(false) is { Tripped: true } state) + { + await SaveAsync(world, RiskMonitor.Restart(state, now), cancellationToken).ConfigureAwait(false); + await RecordAsync(world, "restart", RiskSeverities.Info, "Ripartenza confermata: il massimo di riferimento riparte dal patrimonio di adesso.", new { by }, cancellationToken) + .ConfigureAwait(false); + } + } + + await SaveAsync(BotRow, new BotRiskState(), cancellationToken).ConfigureAwait(false); + await settings.SetAsync(SettingsStore.BotState.Key, "active", by, cancellationToken).ConfigureAwait(false); + } + + /// + /// Exposure from the ledgers, in euro (SPEC 9.2). The twin of a strategy with real money is left out of every + /// total (SPEC 12.3). + /// + public async Task ExposureAsync(CancellationToken cancellationToken) + { + var rate = await UsdRateAsync(cancellationToken).ConfigureAwait(false); + var accounts = await AccountsAsync(cancellationToken).ConfigureAwait(false); + var twins = await TwinsAsync(cancellationToken).ConfigureAwait(false); + decimal Eur(Guid account, decimal value) => accounts.TryGetValue(account, out var a) && a.Currency == "USD" ? (rate is > 0m ? value / rate.Value : 0m) : value; + decimal simEquity = 0m, simInvested = 0m, realEquity = 0m, realInvested = 0m; + foreach (var e in await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)) + { + if (twins.Contains((e.AccountId, e.Strategy)) || !accounts.TryGetValue(e.AccountId, out var account)) + { + continue; + } + + if (account.Environment == TradingEnvironments.Live) + { + realEquity += Eur(e.AccountId, e.Equity); + realInvested += Eur(e.AccountId, e.Invested); + } + else + { + simEquity += Eur(e.AccountId, e.Equity); + simInvested += Eur(e.AccountId, e.Invested); + } + } + + var crypto = 0m; + foreach (var p in await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)) + { + if (!twins.Contains((p.AccountId, p.Strategy)) && await instruments(p.InstrumentId, cancellationToken).ConfigureAwait(false) is { IsCrypto: true }) + { + crypto += Eur(p.AccountId, p.Value); + } + } + + return new RiskExposure(simEquity, simInvested, realEquity, realInvested, crypto); + } + + /// + /// The reference equity of SPEC 9.2, in euro: the capital entrusted plus what the strategies produced, twins left + /// out. The ledger of a strategy in reduced real counts four times; results of ledgers it left stay in. While + /// everything is in simulation it is the equity. + /// + public async Task ReferenceAsync(CancellationToken cancellationToken) + { + var rate = await UsdRateAsync(cancellationToken).ConfigureAwait(false); + var accounts = await AccountsAsync(cancellationToken).ConfigureAwait(false); + var all = await stages.AllAsync(cancellationToken).ConfigureAwait(false); + var counted = new HashSet<(Guid, string)>(); + var total = 0m; + var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + decimal Eur(Guid account, decimal value) => accounts.TryGetValue(account, out var a) && a.Currency == "USD" ? (rate is > 0m ? value / rate.Value : 0m) : value; + foreach (var stage in all) + { + var carried = await CarriedAsync(stage.Strategy, cancellationToken).ConfigureAwait(false); + total += carried; + // In observation the ledger still holds the strategy's share of the capital entrusted. + var ledgerAccount = stage.OrdersAccount ?? (stage.Stage == StrategyStages.Observation ? stage.AccountId : null); + if (ledgerAccount is { } account && equities.FirstOrDefault(e => e.AccountId == account && e.Strategy == stage.Strategy) is { } ledgerEquity) + { + var factor = stage.Stage == StrategyStages.Reduced ? 1m / StrategyStages.ReducedShare : 1m; + total += Eur(account, ledgerEquity.Equity) * factor; + counted.Add((account, stage.Strategy)); + } + + // The twin's ledger and an exit-only real ledger are not part of the reference beyond what was carried. + if (stage.AccountId is { } sim) + { + counted.Add((sim, stage.Strategy)); + } + + if (stage.LiveAccountId is { } live) + { + counted.Add((live, stage.Strategy)); + } + } + + // Ledgers of strategies without a stage row (examples, tests) count as they are. + total += equities.Where(e => !counted.Contains((e.AccountId, e.Strategy))).Sum(e => Eur(e.AccountId, e.Equity)); + return total; + } + + /// The risk events, newest first, for the Rischio screen. + public Task> EventsAsync(int limit, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT occurred_at, kind, severity, message, world FROM risk_events ORDER BY occurred_at DESC, id DESC LIMIT @n", + r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("severity"), r.Text("message"), r.TextOrNull("world")), ("n", limit)), cancellationToken); + + /// + /// Room for new stock positions today with the day-trade guard on (SPEC 9.2): three minus the day trades of the + /// last five sessions minus the positions opened today, so not even a day of stops goes beyond. + /// + public async Task PdtRoomAsync(Guid accountId, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var fills = await db.ReadAsync(s => s.QueryAsync("SELECT instrument_id, side, executed_at FROM fills WHERE account_id = @a AND executed_at >= @f AND reverses_id IS NULL", + r => (Instrument: r.Id("instrument_id"), Side: r.Text("side"), At: r.Moment("executed_at")), ("a", accountId), ("f", now - TimeSpan.FromDays(8))), cancellationToken) + .ConfigureAwait(false); + + // Five sessions back, counted on weekdays; a holiday only makes the window longer, which is the prudent side. + var today = NewYorkDay(now); + var start = today; + for (var sessions = 1; sessions < 5;) + { + start = start.AddDays(-1); + if (start.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + sessions++; + } + } + + var dayTrades = fills.Where(f => NewYorkDay(f.At) >= start).GroupBy(f => (f.Instrument, Day: NewYorkDay(f.At))) + .Count(g => g.Any(f => f.Side == "buy") && g.Any(f => f.Side == "sell")); + var openedToday = fills.Where(f => f.Side == "buy" && NewYorkDay(f.At) == today).Select(f => f.Instrument).Distinct().Count(); + var buying = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE account_id = @a AND side = 'buy' AND status = @w", + ("a", accountId), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + return PdtMaxDayTrades - dayTrades - openedToday - (int)buying; + } + + private static DateOnly NewYorkDay(DateTimeOffset at) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(at, NewYork).DateTime); + + private async Task CancelAsync(IReadOnlyCollection managers, string world, string reason, CancellationToken cancellationToken) + { + var all = await stages.AllAsync(cancellationToken).ConfigureAwait(false); + foreach (var manager in managers) + { + bool InWorld(string strategy) => WorldOf(manager.Account, all.FirstOrDefault(s => s.Strategy == strategy)) == world; + await manager.CancelWorkingAsync(reason, InWorld, cancellationToken).ConfigureAwait(false); + } + } + + private Task> SeriesAsync(string world, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND taken_at >= @f AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world), ("f", clock.UtcNow - TimeSpan.FromDays(8))), cancellationToken); + + private async Task> AccountsAsync(CancellationToken cancellationToken) => + (await db.ReadAsync(s => s.QueryAsync("SELECT id, environment, base_currency FROM accounts", r => (Id: r.Id("id"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), + cancellationToken).ConfigureAwait(false)).ToDictionary(a => a.Id, a => (a.Environment, a.Currency)); + + private async Task> TwinsAsync(CancellationToken cancellationToken) => + [.. (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.HasTwin && s.AccountId is not null).Select(s => (s.AccountId!.Value, s.Strategy))]; + + private async Task CarriedAsync(string strategy, CancellationToken cancellationToken) + { + var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.Text("state"), ("s", strategy)), cancellationToken) + .ConfigureAwait(false); + if (json is null) + { + return 0m; + } + + using var doc = JsonDocument.Parse(json); + return doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("carried_results", out var carried) && carried.TryGetDecimal(out var value) ? value : 0m; + } + + private async Task UsdRateAsync(CancellationToken cancellationToken) => + (await fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate; + + private async Task LoadAsync(string world, CancellationToken cancellationToken) + where T : class + { + var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Text("state"), ("w", world)), cancellationToken).ConfigureAwait(false); + return json is null ? null : JsonSerializer.Deserialize(json, Json); + } + + private Task SaveAsync(string world, T state, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var json = new DbJson(JsonSerializer.Serialize(state, Json)); + var now = clock.UtcNow; + if (await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken, ("j", json), ("t", now), ("w", world)).ConfigureAwait(false) == 0) + { + await s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, @w, @j, @t, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("w", world), ("j", json), ("t", now)).ConfigureAwait(false); + } + }, cancellationToken); + + private Task RecordAsync(string? world, string kind, string severity, string message, object? data, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var now = clock.UtcNow; + await s.ExecuteAsync("INSERT INTO risk_events (id, occurred_at, kind, severity, message, data, created_at, world) VALUES (@id, @t, @k, @sev, @m, @d, @t, @w)", cancellationToken, + ("id", Ids.NewId(clock)), ("t", now), ("k", kind), ("sev", severity), ("m", message), ("d", data is null ? null : new DbJson(JsonSerializer.Serialize(data))), ("w", world)) + .ConfigureAwait(false); + if (severity is RiskSeverities.Info) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, kind, message, data, cancellationToken).ConfigureAwait(false); + } + else + { + await Diary.NotifyAsync(s, clock, kind, message, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken); +} diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs new file mode 100644 index 0000000..668265b --- /dev/null +++ b/src/Anubis/Trading/Stages.cs @@ -0,0 +1,633 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Anubis.Core; +using Anubis.Db; +using Anubis.Risk; + +namespace Anubis.Trading; + +/// The stages of SPEC 12.3. The stage decides where a strategy's orders go (SPEC 7.1). +public static class StrategyStages +{ + public const string Observation = "observation"; + public const string Simulation = "simulation"; + public const string Reduced = "reduced"; + public const string Real = "real"; + + public static readonly IReadOnlyList All = [Observation, Simulation, Reduced, Real]; + + public static bool IsLive(string stage) => stage is Reduced or Real; + + public static string Label(string stage) => stage switch + { + Observation => "osservazione", + Simulation => "simulazione", + Reduced => "reale ridotto", + Real => "reale", + _ => stage, + }; + + /// A strategy in reduced real works with a quarter of its capital (SPEC 12.3). + public const decimal ReducedShare = 0.25m; +} + +/// +/// The backtest outcome a strategy qualified with (SPEC 12.3): it travels with the code in docs/backtests/ +/// and the requirements and demotions compare against it. It does not move when estimates are updated (11.6). +/// +public sealed record Qualification +{ + public required bool Passed { get; init; } + + /// Why it passed or not, in plain Italian. + public required string Verdict { get; init; } + + /// The report it comes from: a file of docs/backtests/ and the plan's hash. + public required string Report { get; init; } + + public string? PlanHash { get; init; } + + /// Largest fall of the backtest, as a fraction of the capital used: 0.18 is −18%. + public decimal MaxDrawdown { get; init; } + + /// Slippage the backtest assumed, in basis points of the price. + public decimal ExpectedSlippageBp { get; init; } + + /// Estimated round-trip cost, as a fraction of the value traded (fees and slippage, both ways). + public decimal RoundTripCost { get; init; } + + /// + /// The 5th percentile of the cumulative result after each day from the promotion (SPEC 12.3), from a block + /// bootstrap of the backtest's daily returns: −0.05 is −5%. + /// + public IReadOnlyList ExpectedPathP5 { get; init; } = []; + + public static readonly JsonSerializerOptions Json = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; +} + +/// A strategy where it stands: stage, accounts, capital, and whether it is only closing real positions. +public sealed record StrategyStage( + string Strategy, + Guid? AccountId, + Guid? LiveAccountId, + string Stage, + bool ExitOnly, + DateTimeOffset? LiveConfirmedAt, + DateTimeOffset? StageSince, + string? StageReason, + decimal Share, + decimal Capital, + Qualification? Qualification) +{ + /// Where the orders of a new decision go: nowhere in observation, the simulation account in simulation, the real one in reduced and real. + public Guid? OrdersAccount => Stage switch + { + StrategyStages.Observation => null, + StrategyStages.Simulation => AccountId, + _ => LiveAccountId, + }; + + /// A strategy with real money keeps running in simulation too: the simulated twin (SPEC 12.3). + public bool HasTwin => StrategyStages.IsLive(Stage); +} + +/// One requirement of SPEC 12.3, checked automatically and shown in the interface. +public sealed record Requirement(string Key, string Label, string Value, string Target, bool Met); + +/// A condition of automatic demotion in progress (SPEC 12.3). +public sealed record DemotionCondition(string Key, string Message); + +/// What the user confirms with the procedure of SPEC 12.4. +public sealed record LiveConfirmation(string Strategy, Guid LiveAccountId, string Phrase, string Password, string? Code, string By); + +public sealed class LiveConfirmationException(string code, string message) : InvalidOperationException(message) +{ + public string Code { get; } = code; +} + +/// +/// Stages of the strategies (SPEC 12.3, 12.4, 7.1). The only way to real money is : +/// the startup consent, every requirement met, the confirmation phrase, the password and the second factor checked +/// right then. Every confirmation, revocation and demotion goes to the stage history and to the change log. A +/// strategy that leaves real money keeps its real positions in exit only until they are at zero. +/// +public sealed class StageBook(Database db, IClock clock, TradingConsent consent, Func> reauthenticate) +{ + public const int SimulationDays = 60; + public const int ReducedDays = 30; + public const int IncidentDays = 30; + public const decimal MaxOneStepDifference = 0.02m; + + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + public static int MinClosedTrades(string strategy) => strategy switch + { + StrategyNames.CryptoTrend => 8, + StrategyNames.EquityMomentum => 10, + StrategyNames.EquityMeanrev => 30, + _ => 30, + }; + + /// The phrase the user types to confirm (SPEC 12.4): it names the strategy and the stage. + public static string Phrase(string strategy, string stage) => + $"confermo soldi veri per {strategy} in {StrategyStages.Label(stage)}"; + + public async Task> AllAsync(CancellationToken cancellationToken) => + await db.ReadAsync(s => s.QueryAsync(Select + " ORDER BY strategy", Read), cancellationToken).ConfigureAwait(false); + + public Task GetAsync(string strategy, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync(Select + " WHERE strategy = @s", Read, ("s", strategy)), cancellationToken); + + /// + /// The permission on a real account (SPEC 12.4), asked by the order manager when an intent arrives and again right + /// before the order leaves. Null allows it. Protection of what the bot holds there always goes; an exit-only + /// strategy may only sell; everything else needs reduced or real with a confirmation, on that very account. + /// + public async Task LiveRefusalAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(intent); + ArgumentNullException.ThrowIfNull(account); + if (account.Environment != TradingEnvironments.Live) + { + return null; + } + + if (!consent.AllowLive) + { + return RiskReasons.NoConsent; + } + + var stage = await GetAsync(intent.Strategy, cancellationToken).ConfigureAwait(false); + if (stage is null || stage.LiveAccountId != account.AccountId) + { + return RiskReasons.LiveNotConfirmed; + } + + if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop) + { + return null; + } + + if (stage.ExitOnly) + { + return intent.Purpose == OrderPurpose.Exit && intent.Side == OrderSide.Sell ? null : RiskReasons.ExitOnly; + } + + return StrategyStages.IsLive(stage.Stage) && stage.LiveConfirmedAt is not null ? null : RiskReasons.LiveNotConfirmed; + } + + /// + /// The backtest outcome loaded at first start (SPEC 12.3): a base strategy that passed starts in simulation, one + /// that did not stays in observation and the interface says why. A strategy that already moved keeps its stage. + /// + public async Task ApplyQualificationAsync(string strategy, Qualification qualification, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(qualification); + var json = new DbJson(JsonSerializer.Serialize(qualification, Qualification.Json)); + await db.WriteAsync(async s => + { + var current = await s.FirstOrDefaultAsync("SELECT stage, stage_since FROM strategy_state WHERE strategy = @s", + r => (Stage: r.Text("stage"), Since: r.MomentOrNull("stage_since")), ("s", strategy)).ConfigureAwait(false); + if (current == default) + { + return; + } + + await s.ExecuteAsync("UPDATE strategy_state SET qualification = @q, updated_at = @t WHERE strategy = @s", cancellationToken, + ("q", json), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + var moved = await s.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) > 0; + if (moved || current.Stage != StrategyStages.Observation) + { + return; + } + + if (qualification.Passed) + { + await MoveCoreAsync(s, strategy, current.Stage, StrategyStages.Simulation, "backtest_passed", "primo avvio", cancellationToken).ConfigureAwait(false); + } + else + { + await s.ExecuteAsync("UPDATE strategy_state SET stage_reason = @r, stage_since = COALESCE(stage_since, @t), updated_at = @t WHERE strategy = @s", cancellationToken, + ("r", "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// Moves a strategy between observation and simulation (the user's choice from the interface). Real money is + /// never reached this way: only does it. + /// + public async Task MoveAsync(string strategy, string to, string reason, string by, CancellationToken cancellationToken) + { + if (to is not (StrategyStages.Observation or StrategyStages.Simulation)) + { + throw new LiveConfirmationException("procedure", "Per i soldi veri serve la procedura di conferma."); + } + + var current = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + if (StrategyStages.IsLive(current.Stage)) + { + await RevokeAsync(strategy, by, reason, cancellationToken).ConfigureAwait(false); + current = (await GetAsync(strategy, cancellationToken).ConfigureAwait(false))!; + } + + if (current.Stage == to) + { + return; + } + + await db.WriteAsync(s => MoveCoreAsync(s, strategy, current.Stage, to, reason, by, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// The requirements of SPEC 12.3 for the next step towards real money, with their values now. + public async Task> RequirementsAsync(string strategy, CancellationToken cancellationToken) + { + var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + var now = clock.UtcNow; + var since = stage.StageSince ?? now; + var list = new List(); + var q = stage.Qualification; + list.Add(new("backtest", "Protocollo di verifica sui dati storici", q is null ? "mancante" : q.Passed ? "superato" : "non superato", "superato", q?.Passed == true)); + if (stage.Stage == StrategyStages.Reduced) + { + var days = (int)(now - since).TotalDays; + list.Add(new("days", "Giorni in reale ridotto", days.ToString(Italian), $"almeno {ReducedDays}", days >= ReducedDays)); + } + else + { + var days = stage.Stage == StrategyStages.Simulation ? (int)(now - since).TotalDays : 0; + list.Add(new("days", "Giorni in simulazione", days.ToString(Italian), $"almeno {SimulationDays}", days >= SimulationDays)); + var trades = await ClosedTradesAsync(strategy, stage.AccountId, since, cancellationToken).ConfigureAwait(false); + var minimum = MinClosedTrades(strategy); + list.Add(new("trades", "Operazioni chiuse", trades.Count.ToString(Italian), $"almeno {minimum}", trades.Count >= minimum)); + var oneStep = await OneStepAsync(strategy, since, cancellationToken).ConfigureAwait(false); + list.Add(new("one_step", "Coerenza con il backtest (confronto a un passo)", + oneStep is { } share ? Format.Percent(share * 100m, 1) : "da misurare", "sotto il 2%", oneStep is { } d && d < MaxOneStepDifference)); + var slippage = await SlippageAsync(stage.AccountId, since, cancellationToken).ConfigureAwait(false); + var simulator = await EnvironmentOfAsync(stage.AccountId, cancellationToken).ConfigureAwait(false) == TradingEnvironments.Simulation; + var expected = q?.ExpectedSlippageBp ?? 0m; + list.Add(new("slippage", "Prezzi ottenuti rispetto al previsto", + simulator ? "uguali per costruzione (simulatore interno)" : slippage is { } bp ? Format.Quantity(Math.Round(bp, 1)) + " punti base" : "nessuna esecuzione", + $"al massimo {Format.Quantity(expected * 2m)} punti base", simulator || (slippage is { } b && b <= expected * 2m))); + if (strategy == StrategyNames.EquityMeanrev) + { + list.Add(MeanrevEdge(trades, q?.RoundTripCost ?? 0m)); + } + } + + var incidents = await CriticalIncidentsAsync(now - TimeSpan.FromDays(IncidentDays), cancellationToken).ConfigureAwait(false); + list.Add(new("incidents", "Incidenti critici negli ultimi 30 giorni", incidents.ToString(Italian), "nessuno", incidents == 0)); + var demotions = StrategyStages.IsLive(stage.Stage) ? await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false) : []; + list.Add(new("demotion", "Condizioni di retrocessione in corso", demotions.Count == 0 ? "nessuna" : string.Join("; ", demotions.Select(d => d.Message)), "nessuna", + demotions.Count == 0)); + return list; + } + + /// + /// The procedure of SPEC 12.4: from simulation to reduced real, or from reduced to real. It is refused unless the + /// startup configuration allows real money, the account is a real account of the strategy's broker, every + /// requirement is met, the phrase is typed as shown and the password and second factor are right now. + /// + public async Task ConfirmLiveAsync(LiveConfirmation c, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(c); + if (!consent.AllowLive) + { + throw new LiveConfirmationException(RiskReasons.NoConsent, + $"La configurazione d'avvio non consente i soldi veri ({consent.Source}): la procedura non può partire."); + } + + var stage = await GetAsync(c.Strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + c.Strategy, nameof(c)); + var to = stage.Stage switch + { + StrategyStages.Simulation => StrategyStages.Reduced, + StrategyStages.Reduced => StrategyStages.Real, + _ => throw new LiveConfirmationException("stage", $"Da {StrategyStages.Label(stage.Stage)} non si passa ai soldi veri."), + }; + var account = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT broker, environment FROM accounts WHERE id = @id", + r => (Broker: r.Text("broker"), Environment: r.Text("environment")), ("id", c.LiveAccountId)), cancellationToken).ConfigureAwait(false); + if (account == default || account.Environment != TradingEnvironments.Live || account.Broker != StrategyNames.BrokerOf(c.Strategy)) + { + throw new LiveConfirmationException("account", "Il conto scelto non è il conto reale del broker di questa strategia."); + } + + if (stage.Stage == StrategyStages.Reduced && stage.LiveAccountId != c.LiveAccountId) + { + throw new LiveConfirmationException("account", "Il passaggio a reale avviene sullo stesso conto del reale ridotto."); + } + + var unmet = (await RequirementsAsync(c.Strategy, cancellationToken).ConfigureAwait(false)).Where(r => !r.Met).ToList(); + if (unmet.Count > 0) + { + throw new LiveConfirmationException("requirements", "Requisiti non ancora soddisfatti: " + string.Join(", ", unmet.Select(r => r.Label.ToLowerInvariant())) + "."); + } + + if (!string.Equals(c.Phrase.Trim(), Phrase(c.Strategy, to), StringComparison.Ordinal)) + { + throw new LiveConfirmationException("phrase", "La frase di conferma non corrisponde: scrivila esattamente come appare."); + } + + if (!await reauthenticate(c.Password, c.Code, cancellationToken).ConfigureAwait(false)) + { + throw new LiveConfirmationException("password", "Password o codice a due fattori non corretti."); + } + + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await CarryResultsAsync(s, stage, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, live_confirmed_at = @t, live_confirmed_by = @by, exit_only = @no, updated_at = @t WHERE strategy = @s", + cancellationToken, ("a", c.LiveAccountId), ("t", now), ("by", c.By), ("no", false), ("s", c.Strategy)).ConfigureAwait(false); + await MoveCoreAsync(s, c.Strategy, stage.Stage, to, "confirmed_12_4", c.By, cancellationToken).ConfigureAwait(false); + await LogChangeAsync(s, c.Strategy, stage.Stage, to, c.By, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// The user takes real money away from a strategy (SPEC 12.3, 12.4): back to simulation, and the real positions, + /// if any, stay in exit only until they are at zero. + /// + public Task RevokeAsync(string strategy, string by, string reason, CancellationToken cancellationToken) => + LeaveLiveAsync(strategy, by, reason, automatic: false, cancellationToken); + + /// Automatic demotion (SPEC 12.3): like a revocation, with an alert and a risk event. + public Task DemoteAsync(string strategy, string reason, CancellationToken cancellationToken) => + LeaveLiveAsync(strategy, "automatico", reason, automatic: true, cancellationToken); + + /// Demotes every strategy with real money that has a condition of SPEC 12.3 in progress. Returns those demoted. + public async Task> CheckDemotionsAsync(CancellationToken cancellationToken) + { + var demoted = new List(); + foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => StrategyStages.IsLive(s.Stage))) + { + var conditions = await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false); + if (conditions.Count > 0) + { + await DemoteAsync(stage.Strategy, conditions[0].Key, cancellationToken).ConfigureAwait(false); + demoted.Add(stage.Strategy); + } + } + + return demoted; + } + + /// An exit-only strategy whose real positions are all at zero goes back to normal: nothing is left to close. + public async Task ReleaseExitOnlyAsync(Ledger ledger, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(ledger); + var released = 0; + foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null)) + { + var open = (await ledger.PositionsAsync(stage.LiveAccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.Strategy == stage.Strategy && p.Quantity > 0m); + if (open) + { + continue; + } + + await db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @no, updated_at = @t WHERE strategy = @s", cancellationToken, + ("no", false), ("t", clock.UtcNow), ("s", stage.Strategy)).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "exit_only_done", + $"{StrategyNames.Label(stage.Strategy, withMarket: true)}: tutte le posizioni reali sono chiuse, la sola uscita è finita.", null, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + released++; + } + + return released; + } + + /// The conditions of automatic demotion of SPEC 12.3 in progress for a strategy with real money. + public async Task> DemotionConditionsAsync(StrategyStage stage, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(stage); + var list = new List(); + if (stage.LiveAccountId is not { } account || stage.Qualification is not { } q) + { + return list; + } + + var since = stage.StageSince ?? clock.UtcNow; + var points = await db.ReadAsync(s => s.QueryAsync( + "SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND taken_at >= @f ORDER BY taken_at", + r => (At: r.Moment("taken_at"), Index: r.MoneyOrNull("twr_index") ?? 1m), ("a", account), ("s", stage.Strategy), ("f", since)), cancellationToken).ConfigureAwait(false); + if (points.Count > 1) + { + var peak = points[0].Index; + var worst = 0m; + foreach (var p in points) + { + peak = Math.Max(peak, p.Index); + worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m); + } + + if (q.MaxDrawdown > 0m && -worst > 1.5m * q.MaxDrawdown) + { + list.Add(new("drawdown", $"calo {Format.Percent(worst * 100m, 1)}, oltre 1,5 volte quello del backtest ({Format.Percent(-q.MaxDrawdown * 100m, 1)})")); + } + + // Sessions below the 5th percentile of the expected path, counted back from the last day. + var daily = points.GroupBy(p => DateOnly.FromDateTime(p.At.UtcDateTime)).Select(g => g.Last().Index).ToList(); + var start = points[0].Index; + var below = 0; + for (var day = daily.Count - 1; day >= 1 && day - 1 < q.ExpectedPathP5.Count; day--) + { + if ((double)((daily[day] / start) - 1m) < q.ExpectedPathP5[day - 1]) + { + below++; + } + else + { + break; + } + } + + if (below >= 20) + { + list.Add(new("expected_path", $"{below} sedute di fila sotto il 5º percentile del percorso atteso")); + } + } + + var slippage = await SlippageAsync(account, since, cancellationToken).ConfigureAwait(false); + if (slippage is { } bp && q.ExpectedSlippageBp > 0m && bp > 3m * q.ExpectedSlippageBp) + { + list.Add(new("slippage", $"scostamento medio {Format.Quantity(Math.Round(bp, 1))} punti base, oltre il triplo del previsto")); + } + + return list; + } + + private async Task LeaveLiveAsync(string strategy, string by, string reason, bool automatic, CancellationToken cancellationToken) + { + var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + if (!StrategyStages.IsLive(stage.Stage)) + { + return; + } + + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + // The real ledger stays: its positions are closed by the strategy in exit only, and come back under normal + // management if the strategy is promoted again (SPEC 7.1). + var open = stage.LiveAccountId is { } live && (await s.QueryAsync("SELECT quantity FROM positions WHERE account_id = @a AND strategy = @s", + r => r.Money("quantity"), ("a", live), ("s", strategy)).ConfigureAwait(false)).Any(q => q > 0m); + await CarryResultsAsync(s, stage, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE strategy_state SET live_confirmed_at = NULL, live_confirmed_by = NULL, exit_only = @x, updated_at = @t WHERE strategy = @s", cancellationToken, + ("x", open), ("t", now), ("s", strategy)).ConfigureAwait(false); + await MoveCoreAsync(s, strategy, stage.Stage, StrategyStages.Simulation, reason, by, cancellationToken).ConfigureAwait(false); + await LogChangeAsync(s, strategy, stage.Stage, StrategyStages.Simulation, by, cancellationToken).ConfigureAwait(false); + if (automatic) + { + var message = $"{StrategyNames.Label(strategy, withMarket: true)} torna in simulazione ({reason})" + + (open ? ": le posizioni reali restano in sola uscita finché non sono a zero." : "."); + await s.ExecuteAsync("INSERT INTO risk_events (id, occurred_at, kind, severity, message, data, created_at, world) VALUES (@id, @t, @k, @sev, @m, @d, @t, @w)", cancellationToken, + ("id", Ids.NewId(clock)), ("t", now), ("k", "demotion"), ("sev", RiskSeverities.High), ("m", message), + ("d", new DbJson(JsonSerializer.Serialize(new { strategy, reason }))), ("w", Worlds.Real)).ConfigureAwait(false); + await Diary.NotifyAsync(s, clock, "strategy_demoted", message, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + private async Task MoveCoreAsync(DbSession s, string strategy, string from, string to, string reason, string by, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + await s.ExecuteAsync("UPDATE strategy_state SET stage = @to, stage_since = @t, stage_reason = @r, updated_at = @t WHERE strategy = @s", cancellationToken, + ("to", to), ("t", now), ("r", reason), ("s", strategy)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @to, @r, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", strategy), ("f", from), ("to", to), ("r", reason + " · " + by), ("t", now)).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "stage_changed", + $"{StrategyNames.Label(strategy, withMarket: true)}: da {StrategyStages.Label(from)} a {StrategyStages.Label(to)} ({by}).", new { strategy, from, to, reason }, cancellationToken) + .ConfigureAwait(false); + } + + private Task LogChangeAsync(DbSession s, string strategy, string from, string to, string by, CancellationToken cancellationToken) => + s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", "strategy." + strategy + ".stage"), ("o", new DbJson(JsonSerializer.Serialize(from))), ("n", new DbJson(JsonSerializer.Serialize(to))), + ("by", by), ("t", clock.UtcNow)); + + // The results of the ledger a strategy leaves stay in the reference equity (SPEC 9.2): they are carried in its + // state, multiplied by four when they come from reduced real. + private static async Task CarryResultsAsync(DbSession s, StrategyStage stage, CancellationToken cancellationToken) + { + if (stage.OrdersAccount is not { } account) + { + return; + } + + var rows = await s.QueryAsync("SELECT kind, amount FROM cash_ledger WHERE account_id = @a AND strategy = @s", + r => (Kind: r.Text("kind"), Amount: r.Money("amount")), ("a", account), ("s", stage.Strategy)).ConfigureAwait(false); + var positions = await s.QueryAsync("SELECT quantity, average_price, last_price FROM positions WHERE account_id = @a AND strategy = @s", + r => r.Money("quantity") * (r.MoneyOrNull("last_price") ?? r.Money("average_price")), ("a", account), ("s", stage.Strategy)).ConfigureAwait(false); + var results = rows.Where(r => !LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount) + positions.Sum(); + if (stage.Stage == StrategyStages.Reduced) + { + results *= 1m / StrategyStages.ReducedShare; + } + + var state = await s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.Text("state"), ("s", stage.Strategy)).ConfigureAwait(false) ?? "{}"; + var node = System.Text.Json.Nodes.JsonNode.Parse(state)?.AsObject() ?? []; + var carried = node["carried_results"]?.GetValue() ?? 0m; + node["carried_results"] = DbValues.Money(carried + results); + await s.ExecuteAsync("UPDATE strategy_state SET state = @j WHERE strategy = @s", cancellationToken, ("j", new DbJson(node.ToJsonString())), ("s", stage.Strategy)).ConfigureAwait(false); + } + + private Task> ClosedTradesAsync(string strategy, Guid? account, DateTimeOffset since, CancellationToken cancellationToken) => + account is not { } a + ? Task.FromResult(new List<(decimal, decimal, decimal)>()) + : db.ReadAsync(s => s.QueryAsync("SELECT realized, bought_value, fees FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed' AND closed_at >= @f ORDER BY closed_at", + r => (r.Money("realized"), r.Money("bought_value"), r.Money("fees")), ("a", a), ("s", strategy), ("f", since)), cancellationToken); + + private async Task OneStepAsync(string strategy, DateTimeOffset since, CancellationToken cancellationToken) + { + var outcomes = await db.ReadAsync(s => s.QueryAsync("SELECT outcome FROM decisions WHERE strategy = @s AND stage = @st AND created_at >= @f", + r => r.Text("outcome"), ("s", strategy), ("st", DecisionStages.OneStep), ("f", since)), cancellationToken).ConfigureAwait(false); + return outcomes.Count == 0 ? null : outcomes.Count(o => o == DecisionOutcomes.Different) / (decimal)outcomes.Count; + } + + private async Task SlippageAsync(Guid? account, DateTimeOffset since, CancellationToken cancellationToken) + { + if (account is not { } a) + { + return null; + } + + var values = await db.ReadAsync(s => s.QueryAsync("SELECT slippage_bp FROM fills WHERE account_id = @a AND executed_at >= @f AND slippage_bp IS NOT NULL", + r => r.Money("slippage_bp"), ("a", a), ("f", since)), cancellationToken).ConfigureAwait(false); + return values.Count == 0 ? null : values.Average(); + } + + private Task EnvironmentOfAsync(Guid? account, CancellationToken cancellationToken) => + account is not { } a ? Task.FromResult(null) : db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT environment FROM accounts WHERE id = @id", r => r.Text("environment"), ("id", a)), cancellationToken); + + private Task CriticalIncidentsAsync(DateTimeOffset since, CancellationToken cancellationToken) => + db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM risk_events WHERE severity = @c AND occurred_at >= @f", ("c", RiskSeverities.Critical), ("f", since)), cancellationToken); + + // equity_meanrev only (SPEC 12.3): the average gain at least twice the round-trip cost, and distinguishable from + // chance at 90%, checked at 30, 60, 120 and 240 closed trades, then every 120. + private static Requirement MeanrevEdge(List<(decimal Realized, decimal Value, decimal Fees)> trades, decimal roundTrip) + { + var checkpoint = Checkpoint(trades.Count); + if (checkpoint == 0) + { + return new("edge", "Guadagno medio contro il costo stimato", "servono 30 operazioni chiuse", "almeno il doppio del costo, intervallo al 90% sopra zero", false); + } + + var sample = trades.Take(checkpoint).ToList(); + var mean = sample.Average(t => t.Realized); + var cost = sample.Average(t => (t.Value * roundTrip) + t.Fees); + var deviation = Math.Sqrt(sample.Sum(t => Math.Pow((double)(t.Realized - mean), 2)) / Math.Max(1, sample.Count - 1)); + var lower = (double)mean - (1.645 * deviation / Math.Sqrt(sample.Count)); + var met = mean >= 2m * cost && lower > 0; + return new("edge", "Guadagno medio contro il costo stimato", + $"{Format.Quantity(Math.Round(mean, 2))} a operazione, costo {Format.Quantity(Math.Round(cost, 2))}, limite basso al 90% {Format.Quantity(Math.Round((decimal)lower, 2))}", + "almeno il doppio del costo, intervallo al 90% sopra zero", met); + } + + /// The last checkpoint of the statistical test reached: 30, 60, 120, 240, then every 120. + public static int Checkpoint(int trades) + { + if (trades < 30) + { + return 0; + } + + if (trades < 60) + { + return 30; + } + + if (trades < 120) + { + return 60; + } + + if (trades < 240) + { + return 120; + } + + return 240 + ((trades - 240) / 120 * 120); + } + + private const string Select = + "SELECT strategy, account_id, live_account_id, stage, exit_only, live_confirmed_at, stage_since, stage_reason, share, capital, qualification FROM strategy_state"; + + private static StrategyStage Read(DbRow r) => new( + r.Text("strategy"), + r.IdOrNull("account_id"), + r.IdOrNull("live_account_id"), + r.Text("stage"), + !r.IsNull("exit_only") && r.Bool("exit_only"), + r.MomentOrNull("live_confirmed_at"), + r.MomentOrNull("stage_since"), + r.TextOrNull("stage_reason"), + r.MoneyOrNull("share") ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Text("strategy")).Share, + r.Money("capital"), + r.TextOrNull("qualification") is { } json ? JsonSerializer.Deserialize(json, Qualification.Json) : null); +} diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 6db06f5..48ee059 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -3,6 +3,7 @@ using Anubis.Brokers; using Anubis.Core; using Anubis.Data; using Anubis.Db; +using Anubis.Risk; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -152,9 +153,11 @@ public sealed partial class TradingService : IDisposable private readonly BarStore _bars; private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new(); private readonly ConcurrentDictionary _managers = new(); + private RiskLimits _limits = RiskLimits.Default; public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId, - HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null) + HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null, SettingsStore? settings = null, + Func>? reauthenticate = null, string? stopFile = null) { _db = db ?? throw new ArgumentNullException(nameof(db)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); @@ -175,8 +178,20 @@ public sealed partial class TradingService : IDisposable Capital = new Capital(db, clock, Ledger, fx); Equity = new EquityBook(db, clock, Ledger, fx); Quotes = new QuoteBook(clock, FetchQuoteAsync); + + // Real money only through the procedure of SPEC 12.4: without a way to check the password it never passes. + Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false))); + Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile }; + _settings = settings; } + private readonly SettingsStore? _settings; + + public StageBook Stages { get; } + + /// The risk engine every intent crosses (SPEC 9). Null only without settings, in tests of the order manager alone. + public RiskEngine? Risk { get; } + public string InstallationCode { get; } public Ledger Ledger { get; } @@ -202,6 +217,7 @@ public sealed partial class TradingService : IDisposable 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 RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); + await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); foreach (var account in accounts) { var broker = Build(account, alpaca, okx); @@ -217,6 +233,9 @@ public sealed partial class TradingService : IDisposable MarketOpen = MarketOpenAsync, PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false), + Gate = Risk is null ? null : Risk.GateAsync, + LivePermit = Stages.LiveRefusalAsync, + PurchasePriceCheck = (limit, quote) => RiskRules.TechnicalRefusal(_clock.UtcNow, quote.At, quote.Mid, limit, null, _limits), }; } @@ -246,8 +265,35 @@ public sealed partial class TradingService : IDisposable new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync), new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), PhotographAsync), new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), + new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync), + new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync), ]; + /// The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file. + public async Task CheckRiskAsync(CancellationToken cancellationToken) + { + await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); + if (Risk is not null) + { + await Risk.CheckAsync(Managers, cancellationToken).ConfigureAwait(false); + } + } + + /// Automatic demotions (SPEC 12.3) and the end of exit only once real positions are at zero. + public async Task CheckStagesAsync(CancellationToken cancellationToken) + { + await Stages.CheckDemotionsAsync(cancellationToken).ConfigureAwait(false); + await Stages.ReleaseExitOnlyAsync(Ledger, cancellationToken).ConfigureAwait(false); + } + + private async Task RefreshLimitsAsync(CancellationToken cancellationToken) + { + if (_settings is not null) + { + _limits = await RiskSettings.LoadAsync(_settings, cancellationToken).ConfigureAwait(false); + } + } + /// The working loop: quotes from the stream, order updates from the brokers, a turn of every account every few seconds. public async Task RunAsync(CancellationToken cancellationToken) { diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs index b096892..d030fb7 100644 --- a/tests/Anubis.Tests/LaboratoryScreenTests.cs +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -52,7 +52,7 @@ public sealed class LaboratoryScreenTests "Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)", "Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano", "K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera", - "Fase 5", "Impronta dei dati", "Vedi i numeri in una tabella", + "esempio: correttivi e limiti di rischio non si applicano", "Impronta dei dati", "Vedi i numeri in una tabella", }) { StringAssert.Contains(report, part, $"Missing \"{part}\" in the report."); diff --git a/tests/Anubis.Tests/LaboratoryTests.cs b/tests/Anubis.Tests/LaboratoryTests.cs index a39937f..2ddfcc7 100644 --- a/tests/Anubis.Tests/LaboratoryTests.cs +++ b/tests/Anubis.Tests/LaboratoryTests.cs @@ -68,7 +68,7 @@ public sealed class LaboratoryTests Assert.IsNotNull(report.Combinatorial); Assert.IsNotNull(report.Overfitting); Assert.IsTrue(report.Curve.Count is > 100 and <= TrialRunner.MaxCurvePoints + 1); - Assert.IsTrue(report.Limitations.Any(l => l.Contains("Fase 5", StringComparison.Ordinal))); + Assert.IsTrue(report.Limitations.Any(l => l.Contains("Strategia d'esempio", StringComparison.Ordinal))); // A second trial of the same strategy deflates for the variants of both. var second = await lab.PlanAsync(Request() with { Grid = new Dictionary> { ["fast"] = [10m], ["slow"] = [30m] } }, diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs new file mode 100644 index 0000000..4c19abc --- /dev/null +++ b/tests/Anubis.Tests/RiskEngineTests.cs @@ -0,0 +1,556 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Risk; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The risk engine at work on the database (issues #42, #43; SPEC 9, 12.3, 12.4): the gate of every order, the switch +/// of each world, the STOP file, the orders per minute, the day-trade guard, and the only way to real money, tested +/// against a fake real account (a simulator that says "live"). +/// +[TestClass] +public sealed class RiskEngineTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60); + private const string Password = "password-giusta"; + + private sealed class Setup : IAsyncDisposable + { + public required TradingRig Rig { get; init; } + + public required SettingsStore Settings { get; init; } + + public required StageBook Stages { get; init; } + + public required RiskEngine Risk { get; init; } + + public required AccountContext Account { get; init; } + + public required Instrument Btc { get; init; } + + public List Owned { get; } = []; + + public string? Folder { get; init; } + + public async ValueTask DisposeAsync() + { + foreach (var owned in Owned) + { + owned.Dispose(); + } + + if (Folder is not null) + { + TempFolder.Delete(Folder); + } + + await Rig.DisposeAsync().ConfigureAwait(false); + } + } + + /// A real-money consent as the startup configuration would give it: only for the fake real account of these tests. + private static TradingConsent Consent() => TradingConsent.From(DockerPlatform.Load(new Dictionary + { + ["ANUBIS_DB_ENGINE"] = "sqlite", + ["ANUBIS_SECRET_KEY"] = new string('k', 40), + ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1", + ["ANUBIS_ALLOW_LIVE"] = "1", + })); + + /// crypto_trend in simulation on the OKX simulator with 10 000 €, BTC at 60 000. + private static async Task CreateAsync(TradingConsent? consent = null, bool stopFile = false) + { + var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus()); + var stages = new StageBook(rig.Db, rig.Clock, consent ?? TradingConsent.None, (password, _, _) => Task.FromResult(password == Password)); + var folder = stopFile ? TempFolder.Create("stop") : null; + var risk = new RiskEngine(rig.Db, rig.Clock, rig.Ledger, stages, settings, new FxStore(rig.Db, rig.Clock), rig.FindAsync, rig.QuoteAsync) + { + StopFile = folder is null ? null : Path.Combine(folder, "STOP"), + }; + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + rig.Quote(btc.Symbol, 60_000m, 60_010m); + await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false); + await StageRowAsync(rig, StrategyNames.CryptoTrend, account.AccountId, StrategyStages.Simulation, rig.Clock.UtcNow).ConfigureAwait(false); + return new Setup { Rig = rig, Settings = settings, Stages = stages, Risk = risk, Account = account, Btc = btc, Folder = folder }; + } + + private static Task StageRowAsync(TradingRig rig, string strategy, Guid account, string stage, DateTimeOffset since) => + rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 1, @since)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow), ("since", since)), _none); + + private static TradeIntent Buy(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) => + new((instrument ?? s.Btc).Id, strategy, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StopLevel = 57_000m }; + + private static TradeIntent Sell(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, OrderPurpose purpose = OrderPurpose.Exit, Instrument? instrument = null) => + new((instrument ?? s.Btc).Id, strategy, OrderSide.Sell, quantity, purpose, Ids.NewId(s.Rig.Clock)); + + private static Task HoldAsync(Setup s, AccountContext account, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) => + s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, instrument ?? s.Btc, strategy, OrderSide.Buy, quantity, 60_000m), _none); + + private static Task SnapshotAsync(TradingRig rig, string world, DateTimeOffset at, decimal index) => + rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index) " + + "VALUES (@id, @t, 'total', NULL, NULL, @e, @e, 0, 0, @t, @w, 'EUR', 10000, @x, @x)", _none, + ("id", Ids.NewId(rig.Clock)), ("t", at), ("e", 10_000m * index), ("w", world), ("x", index)), _none); + + private static Task> EventsAsync(TradingRig rig, string kind) => + rig.QueryAsync("SELECT severity FROM risk_events WHERE kind = @k", r => r.Text("severity"), ("k", kind)); + + // ---- The gate: stop, pause, ownership, sizes ---- + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task PauseStopsEntriesAndStopStopsEverythingButProtection() + { + await using var s = await CreateAsync(); + await HoldAsync(s, s.Account, 0.01m); + Assert.AreEqual(0.01m, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Quantity); + + await s.Settings.SetAsync(SettingsStore.BotState.Key, "paused", "test"); + Assert.AreEqual(RiskReasons.BotPaused, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "exits go on in pause"); + + await s.Settings.SetAsync(SettingsStore.BotState.Key, "stopped", "test"); + Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "no sales on the strategy's initiative"); + Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m, purpose: OrderPurpose.Protective), s.Account, _none)).Refusal, "protection always passes"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task NoShortSalesAndNothingThatTheStrategyDidNotBuy() + { + await using var s = await CreateAsync(); + Assert.AreEqual(RiskReasons.NotOwned, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "a position the bot did not open is never touched"); + + await HoldAsync(s, s.Account, 0.01m); + Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Sell(s, 0.01m, StrategyNames.EquityMomentum), s.Account, _none)).Refusal); + var more = await s.Risk.GateAsync(Sell(s, 0.05m), s.Account, _none); + Assert.AreEqual(0.01m, more.Quantity); + CollectionAssert.Contains(more.Reasons.ToList(), RiskReasons.NoShortSelling); + Assert.AreEqual(RiskReasons.NoShortSelling, (await s.Risk.GateAsync(Buy(s, 0.01m) with { Purpose = OrderPurpose.Exit }, s.Account, _none)).Refusal); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task APurchaseIsShrunkAndTheDecisionRecordsWhy() + { + await using var s = await CreateAsync(); + var intent = Buy(s, 0.5m); + var result = await s.Risk.GateAsync(intent, s.Account, _none); + + // 0.5 BTC is three times the equity; 20% of it at 60 010 is 0.0333 BTC; the risk to the stop, 1% of 10 000 over 3 010, a little less. + Assert.IsNull(result.Refusal); + Assert.AreEqual(Math.Round(100m / 3_010m, 8), Math.Round(result.Quantity, 8)); + CollectionAssert.AreEqual(new[] { RiskReasons.InvestedLimit, RiskReasons.PositionLimit, RiskReasons.TradeRiskLimit }, result.Reasons.ToList(), string.Join(",", result.Reasons)); + var row = (await new DecisionLog(s.Rig.Db, s.Rig.Clock).OfAsync(intent.DecisionId, _none)).Single(); + Assert.AreEqual(DecisionStages.Risk, row.Stage); + Assert.AreEqual(DecisionOutcomes.Reduced, row.Outcome); + CollectionAssert.Contains(row.Reasons.ToList(), RiskReasons.TradeRiskLimit); + 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. + 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(RiskReasons.NoLeverage, poor.Reasons[^1]); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task OldPricesStopEntriesButNotExits() + { + await using var s = await CreateAsync(); + await HoldAsync(s, s.Account, 0.01m); + s.Rig.Clock.Advance(TimeSpan.FromSeconds(61)); + Assert.AreEqual(RiskReasons.StalePrice, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal); + + s.Rig.Refresh(); + var skewed = new RiskEngine(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, s.Stages, s.Settings, new FxStore(s.Rig.Db, s.Rig.Clock), s.Rig.FindAsync, s.Rig.QuoteAsync) + { + ClockSkew = _ => TimeSpan.FromSeconds(3), + }; + Assert.AreEqual(RiskReasons.ClockSkew, (await skewed.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStrategyInObservationNeverBuys() + { + await using var s = await CreateAsync(); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none); + Assert.AreEqual(RiskReasons.Observation, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + } + + // ---- 9.2: the limits of each world ---- + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ADayOfLossesBlocksEntriesOfThatWorldOnly() + { + await using var s = await CreateAsync(); + var now = s.Rig.Clock.UtcNow; + await SnapshotAsync(s.Rig, Worlds.Simulated, now - TimeSpan.FromHours(10), 1.00m); + await SnapshotAsync(s.Rig, Worlds.Simulated, now, 0.975m); + await SnapshotAsync(s.Rig, Worlds.Real, now - TimeSpan.FromHours(10), 1.00m); + await SnapshotAsync(s.Rig, Worlds.Real, now, 1.01m); + + var alerts = await s.Risk.CheckAsync([], _none); + Assert.IsTrue(alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss)); + Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss)).Single()); + Assert.AreEqual(RiskReasons.DailyLossBlock, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).EntriesBlocked, "the real world goes on"); + Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", RiskAlertKinds.DailyLoss)), "the diary says it"); + + // A second check does not repeat the alert; after 24 hours entries are back. + await s.Risk.CheckAsync([], _none); + Assert.HasCount(1, await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss)); + s.Rig.Clock.Advance(TimeSpan.FromHours(24) + _minute); + s.Rig.Refresh(); + Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSwitchTripsAtFifteenPercentAndOnlyTheUserRestartsIt() + { + await using var s = await CreateAsync(); + await HoldAsync(s, s.Account, 0.01m); + await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m); + await s.Risk.CheckAsync([], _none); + s.Rig.Clock.Advance(TimeSpan.FromDays(5)); + await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.20m); + await s.Risk.CheckAsync([], _none); + + // The high of ten days ago is outside the series read now, but remembered. + s.Rig.Clock.Advance(TimeSpan.FromDays(10)); + s.Rig.Refresh(); + await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m); + await s.Risk.CheckAsync([], _none); + var world = await s.Risk.WorldAsync(Worlds.Simulated, _none); + Assert.IsTrue(world.State.Tripped); + Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskAlertKinds.DrawdownStop)).Single()); + Assert.AreEqual(RiskReasons.SwitchTripped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal); + Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).State.Tripped); + + // Days pass: nothing rearms by itself. + s.Rig.Clock.Advance(TimeSpan.FromDays(3)); + await s.Risk.CheckAsync([], _none); + Assert.IsTrue((await s.Risk.WorldAsync(Worlds.Simulated, _none)).State.Tripped); + + await s.Risk.RestartAsync("utente", _none); + world = await s.Risk.WorldAsync(Worlds.Simulated, _none); + 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))); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TenOrdersInAMinuteStopTheBot() + { + await using var s = await CreateAsync(); + async Task OrdersAsync(int count, string purpose) + { + for (var i = 0; i < count; i++) + { + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync( + "INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose, submitted_at) " + + "VALUES (@id, @a, @i, 'crypto_trend', @c, 'buy', 'limit', 1, 'submitted', @t, @t, @p, @t)", _none, + ("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("c", "T" + Ids.NewId(s.Rig.Clock).ToString("N")), ("t", s.Rig.Clock.UtcNow), ("p", purpose)), _none); + } + } + + await OrdersAsync(9, "entry"); + await OrdersAsync(5, "stop"); + await s.Risk.CheckAsync([], _none); + Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value, "stops do not count"); + + 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()); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheStopFileStopsEverythingAndBlocksTheRestart() + { + await using var s = await CreateAsync(stopFile: true); + await File.WriteAllTextAsync(s.Risk.StopFile!, ""); + Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "at once, before the check"); + await s.Risk.CheckAsync([], _none); + Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + await Assert.ThrowsExactlyAsync(() => s.Risk.RestartAsync("utente", _none)); + + File.Delete(s.Risk.StopFile!); + Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "removing the file does not restart"); + await s.Risk.RestartAsync("utente", _none); + Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task StopEverythingCancelsWorkOrdersButKeepsTheStops() + { + await using var s = await CreateAsync(); + var paper = s.Rig.Paper(PaperOptions.Okx(), s.Account.AccountId); + await paper.DepositAsync(100_000m, "EUR", _none); + var manager = s.Rig.Manager(paper, s.Account); + await manager.SubmitAsync(Buy(s, 0.01m) with { StartAggressive = true }, _none); + await s.Rig.TurnsAsync(manager, 2, _minute); + var stops = await paper.GetOpenOrdersAsync(_none); + Assert.HasCount(1, stops, "the stop of the position"); + + // A sale far from the price stays working; "Ferma tutto" cancels it and puts the stop back. + s.Rig.Quote(s.Btc.Symbol, 60_000m, 60_010m); + var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + await manager.SubmitAsync(Sell(s, held), _none); + await s.Risk.StopAllAsync([manager], "utente", "stop_all", "Fermo tutto.", _none); + await s.Rig.TurnsAsync(manager, 1, _minute); + Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + Assert.AreEqual(held, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity, "the position stays"); + var open = await paper.GetOpenOrdersAsync(_none); + Assert.IsTrue(open.Any(o => o.Kind == OrderKind.Stop || o.StopPrice is not null), "the stop is there"); + Assert.IsEmpty(await s.Rig.QueryAsync("SELECT id FROM executions WHERE status = 'working'", r => r.Id("id"))); + } + + // ---- 9.2: the day-trade guard ---- + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDayTradeGuardKeepsMeanReversionInAndCountsTheDay() + { + await using var s = await CreateAsync(); + var alpaca = await s.Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation); + var stocks = new List(); + foreach (var symbol in new[] { "AAA", "BBB", "CCC", "DDD" }) + { + var stock = await s.Rig.InstrumentAsync(TradingRig.Stock(symbol)); + s.Rig.Quote(symbol, 99.99m, 100m); + stocks.Add(stock); + } + + await new FxStore(s.Rig.Db, s.Rig.Clock).UpsertAsync([new FxRate("EUR", "USD", DateOnly.FromDateTime(s.Rig.Clock.UtcNow.UtcDateTime), 1.10m, "test")], _none); + await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMeanrev, 5_000m, "USD", "test", _none); + await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 5_000m, "USD", "test", _none); + await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[0], StrategyNames.EquityMeanrev, OrderSide.Buy, 1m, 100m), _none); + await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[1], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none); + + // Off by default: mean reversion may leave on the day it entered. + Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal); + + await s.Settings.SetAsync(RiskSettings.PdtGuard.Key, "on", "test"); + Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal); + Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMomentum, instrument: stocks[1]), alpaca, _none)).Refusal); + + // Two positions opened today: one more allowed, then none. + Assert.AreEqual(1, await s.Risk.PdtRoomAsync(alpaca.AccountId, _none)); + Assert.IsNull((await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[2]) with { StopLevel = 99m }, alpaca, _none)).Refusal); + await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[2], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none); + Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[3]) with { StopLevel = 99m }, alpaca, _none)).Refusal); + + // Crypto is not touched by it. + Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal); + } + + // ---- 12.4: real money only with the procedure ---- + + private sealed record Live(FaultyBroker Broker, PaperBroker Paper, AccountContext Account, OrderManager Manager); + + /// A fake real account: the simulator behind a broker that says "live", and its order manager wired as in the service. + private static async Task FakeRealAccountAsync(Setup s, bool permit = true) + { + var account = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)"); + var paper = s.Rig.Paper(PaperOptions.Okx(), account.AccountId); + await paper.DepositAsync(100_000m, "EUR", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Live); + var manager = new OrderManager(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, broker, account, TradingRig.Installation, s.Rig.FindAsync, s.Rig.QuoteAsync) + { + ConfirmPrice = s.Rig.QuoteAsync, + MarketOpen = (_, _) => Task.FromResult(true), + Gate = s.Risk.GateAsync, + LivePermit = permit ? s.Stages.LiveRefusalAsync : null, + }; + s.Owned.Add(manager); + return new Live(broker, paper, account, manager); + } + + /// Everything SPEC 12.3 asks before reduced real: 60 days, 8 closed trades, the one-step comparison, the backtest passed. + private static async Task RequirementsMetAsync(Setup s) + { + var since = s.Rig.Clock.UtcNow - TimeSpan.FromDays(61); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage_since = @t", _none, ("t", since)), _none); + await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification + { + Passed = true, + Verdict = "superato", + Report = "docs/backtests/crypto_trend.md", + MaxDrawdown = 0.20m, + ExpectedSlippageBp = 5m, + RoundTripCost = 0.004m, + }, _none); + for (var i = 0; i < 8; i++) + { + var closed = since + TimeSpan.FromDays(5 + (i * 6)); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync( + "INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, created_at, updated_at) " + + "VALUES (@id, @a, @i, 'crypto_trend', 'closed', @o, @c, 0.01, 600, 0.01, 620, 1, 19, @c, @c)", _none, + ("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("o", closed - TimeSpan.FromDays(3)), ("c", closed)), _none); + await new DecisionLog(s.Rig.Db, s.Rig.Clock).WriteAsync(new DecisionRow(Ids.NewId(s.Rig.Clock), StrategyNames.CryptoTrend, s.Account.AccountId, null, DecisionStages.OneStep, + DecisionOutcomes.Same, [], null, closed), _none); + } + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task NoOrderReachesARealAccountWithoutTheProcedure() + { + // Without the startup consent: nothing, however the strategy stands. + await using (var s = await CreateAsync()) + { + var live = await FakeRealAccountAsync(s); + var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m), _none); + Assert.IsNull(id); + Assert.AreEqual(RiskReasons.NoConsent, refusal); + await RequirementsMetAsync(s); + var refused = await Assert.ThrowsExactlyAsync(() => s.Stages.ConfirmLiveAsync( + new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none)); + Assert.AreEqual(RiskReasons.NoConsent, refused.Code); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + Assert.IsEmpty(live.Broker.Sent); + } + + // An order manager without the permission check sends nothing on a real account: it fails closed. + await using (var s = await CreateAsync(Consent())) + { + var bare = await FakeRealAccountAsync(s, permit: false); + Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await bare.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + Assert.IsEmpty(bare.Broker.Sent); + } + + // With the consent, step by step: every part of the procedure is needed. + await using (var s = await CreateAsync(Consent())) + { + var live = await FakeRealAccountAsync(s); + await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal, "simulation is not real money"); + await Assert.ThrowsExactlyAsync(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Reduced, "test", "utente", _none), + "no shortcut to real money"); + + var phrase = StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced); + LiveConfirmation Ask(string text, string password) => new(StrategyNames.CryptoTrend, live.Account.AccountId, text, password, null, "utente"); + Assert.AreEqual("requirements", (await Assert.ThrowsExactlyAsync(() => s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none))).Code); + + await RequirementsMetAsync(s); + Assert.IsTrue((await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).All(r => r.Met)); + Assert.AreEqual("phrase", (await Assert.ThrowsExactlyAsync(() => s.Stages.ConfirmLiveAsync(Ask("confermo", Password), _none))).Code); + Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync(() => s.Stages.ConfirmLiveAsync(Ask(phrase, "sbagliata"), _none))).Code); + await s.Rig.TurnsAsync(live.Manager, 2, _minute); + Assert.IsEmpty(live.Broker.Sent, "nothing reached the real account before the confirmation"); + + s.Rig.Refresh(); + await s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none); + var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual(StrategyStages.Reduced, stage.Stage); + Assert.AreEqual(live.Account.AccountId, stage.LiveAccountId); + Assert.IsNotNull(stage.LiveConfirmedAt); + Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage"))); + Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT to_stage FROM strategy_stage_history WHERE to_stage = 'reduced'", r => r.Text("to_stage"))); + + var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m) with { StartAggressive = true }, _none); + Assert.IsNull(refusal); + Assert.IsNotNull(id); + await s.Rig.TurnsAsync(live.Manager, 2, _minute); + Assert.IsNotEmpty(live.Broker.Sent, "after the procedure the order reaches the account"); + + // Another strategy on the same account is still refused: the confirmation is for one strategy and one account. + Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m, StrategyNames.EquityMomentum), _none)).Refusal); + } + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero() + { + await using var s = await CreateAsync(Consent()); + var live = await FakeRealAccountAsync(s); + await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + await RequirementsMetAsync(s); + await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, + StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none); + s.Rig.Refresh(); + await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + Assert.IsTrue(held is > 0.0019m and <= 0.002m, "bought, less the fee in bitcoin"); + Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account"); + + await s.Stages.DemoteAsync(StrategyNames.CryptoTrend, "drawdown", _none); + var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual(StrategyStages.Simulation, stage.Stage); + Assert.IsTrue(stage.ExitOnly); + Assert.IsNull(stage.LiveConfirmedAt); + Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, "demotion")).Single()); + + // Nothing new, nothing bigger. + var sent = live.Broker.Sent.Count; + Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + + // The stops are kept and put back every day: one moved by hand comes back. + foreach (var order in await live.Paper.GetOpenOrdersAsync(_none)) + { + await live.Paper.CancelOrderAsync(order.ClientOrderId, order.Symbol, _none); + } + + await s.Rig.TurnsAsync(live.Manager, 2, _minute); + Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop is put back on the real account"); + + // The exit goes: half, then the rest. + Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, 0.001m) with { StartAggressive = true }, _none)).Refusal); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + var rest = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + Assert.AreEqual(held - 0.001m, rest); + Assert.AreEqual(0, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none), "a real position is still open"); + Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, rest) with { StartAggressive = true }, _none)).Refusal); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none) is { Quantity: > 0m } p ? p : null); + Assert.IsTrue(live.Broker.Sent.Count > sent); + + // At zero the exit only ends, and the real account is closed to it again. + Assert.AreEqual(1, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none)); + Assert.IsFalse((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.ExitOnly); + Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheTwinIsPhotographedButLeftOutOfTheTotals() + { + await using var s = await CreateAsync(Consent()); + var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)"); + await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced', live_account_id = @a, live_confirmed_at = @t", _none, + ("a", live.AccountId), ("t", s.Rig.Clock.UtcNow)), _none); + await new EquityBook(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, new FxStore(s.Rig.Db, s.Rig.Clock)).TakeAsync(_none); + var totals = await s.Rig.QueryAsync("SELECT world, equity FROM equity_snapshots WHERE scope = 'total'", r => (World: r.Text("world"), Equity: r.Money("equity"))); + Assert.AreEqual(2_500m, totals.Single(t => t.World == Worlds.Real).Equity); + Assert.IsFalse(totals.Any(t => t.World == Worlds.Simulated), "the twin is the only simulated ledger"); + Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM equity_snapshots WHERE scope = 'strategy'", r => r.Id("id"))); + + // In the risk engine too: the twin's ten thousand are not exposure, and the reference counts the quarter four times. + var exposure = await s.Risk.ExposureAsync(_none); + Assert.AreEqual(0m, exposure.SimulatedEquity); + Assert.AreEqual(2_500m, exposure.RealEquity); + Assert.AreEqual(10_000m, await s.Risk.ReferenceAsync(_none)); + } +} diff --git a/tests/Anubis.Tests/RiskTests.cs b/tests/Anubis.Tests/RiskTests.cs new file mode 100644 index 0000000..695223a --- /dev/null +++ b/tests/Anubis.Tests/RiskTests.cs @@ -0,0 +1,455 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Strategies; + +namespace Anubis.Tests; + +/// +/// The rules of the risk engine without a database (issues #41, #42; SPEC 8.5, 9.1, 9.2, 9.5): every size rule, the +/// monitor of losses with its blocks, warnings and switch, the scenarios, the correctives. +/// +[TestClass] +public sealed class RiskTests +{ + private static readonly RiskLimits _limits = RiskLimits.Default; + + // A Wednesday in November: 11:00 in Rome. + private static readonly DateTimeOffset _now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero); + + private static PurchaseRequest Request(decimal wanted, decimal price = 100m, decimal held = 0m, decimal? stop = 95m, decimal reference = 10_000m) => new() + { + Price = price, + Held = held, + Wanted = wanted, + Stop = stop, + WorldEquity = reference, + WorldInvested = 0m, + Reference = reference, + }; + + // ---- 9.2: each limit on the size of a purchase ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheInvestedCapitalLimitStopsPurchasesAtTheEquity() + { + var size = RiskRules.SizePurchase(Request(10m) with { WorldInvested = 9_700m }, _limits); + Assert.AreEqual(3m, size.Quantity); + CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.InvestedLimit); + Assert.AreEqual(0m, RiskRules.SizePurchase(Request(10m) with { WorldInvested = 10_000m }, _limits).Quantity); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void OnePositionNeverWeighsMoreThanTwentyPercentOfTheReference() + { + // 20% of 10 000 at 100 is 20 shares: 15 held, 5 more allowed. + var size = RiskRules.SizePurchase(Request(10m, held: 15m, stop: 99.5m), _limits); + Assert.AreEqual(5m, size.Quantity); + CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.PositionLimit); + + // Heavier than the threshold: the excess goes at the first chance. + Assert.AreEqual(10m, RiskRules.Excess(30m, 100m, 10_000m, _limits)); + Assert.AreEqual(0m, RiskRules.Excess(20m, 100m, 10_000m, _limits)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CryptoNeverGoesBeyondFortyPercentOfTheReference() + { + var size = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { IsCrypto = true, CryptoValue = 3_900m }, _limits); + Assert.AreEqual(1m, size.Quantity); + CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.CryptoLimit); + + // The same purchase of a stock is not touched by the crypto share. + Assert.AreEqual(10m, RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { CryptoValue = 3_900m }, _limits).Quantity); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheRiskOfOneTradeIsAtMostOnePercentOnTheWholePosition() + { + // 1% of 10 000 is 100; with the stop 10 below the price that is 10 shares for the whole position. + var size = RiskRules.SizePurchase(Request(15m, stop: 90m), _limits); + Assert.AreEqual(10m, size.Quantity); + CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.TradeRiskLimit); + Assert.AreEqual(6m, RiskRules.SizePurchase(Request(15m, held: 4m, stop: 90m), _limits).Quantity); + + // Without a stop the whole value is at risk; a stop at or above the price buys nothing. + Assert.AreEqual(1m, RiskRules.SizePurchase(Request(15m, stop: null), _limits).Quantity); + var above = RiskRules.SizePurchase(Request(15m, stop: 100m), _limits); + Assert.AreEqual(0m, above.Quantity); + CollectionAssert.Contains(above.Reasons.ToList(), RiskReasons.StopAbovePrice); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AReductionMultipliesTheTargetAndNeverSellsWhatIsHeld() + { + var halved = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { Multiplier = 0.5m }, _limits); + Assert.AreEqual(5m, halved.Quantity); + CollectionAssert.Contains(halved.Reasons.ToList(), RiskReasons.Reduction); + + // 6 held towards a target of 10, halved to 5: nothing more is bought, nothing is sold. + Assert.AreEqual(0m, RiskRules.SizePurchase(Request(4m, held: 6m, stop: 99.5m) with { Multiplier = 0.5m }, _limits).Quantity); + } + + // ---- 9.1 points 5 and 6, as properties ---- + + private sealed record Case(PurchaseRequest Request, decimal Loss, decimal Cut) + { + public override string ToString() => $"{Request} loss {Loss} cut {Cut}"; + } + + private static Case Generate(Gen g) + { + var price = (decimal)Math.Round(1 + (g.Double() * 1000), 2); + var reference = (decimal)Math.Round(1_000 + (g.Double() * 100_000), 2); + var request = new PurchaseRequest + { + Price = price, + Held = g.Bool() ? 0m : (decimal)Math.Round(g.Double() * 50, 4), + Wanted = (decimal)Math.Round(g.Double() * 100, 4), + Stop = g.Int(0, 4) switch + { + 0 => null, + 1 => price * 1.01m, + _ => Math.Round(price * (decimal)(0.5 + (g.Double() * 0.49)), 2), + }, + Multiplier = g.Bool() ? 1m : (decimal)Math.Round(g.Double(), 2), + WorldEquity = reference, + WorldInvested = (decimal)Math.Round(g.Double() * (double)reference, 2), + Reference = reference, + IsCrypto = g.Bool(), + CryptoValue = (decimal)Math.Round(g.Double() * 0.5 * (double)reference, 2), + }; + return new Case(request, (decimal)Math.Round(g.Double() * 0.5, 4), (decimal)Math.Round(g.Double(), 4)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoRuleEverEnlargesWhatTheStrategyAsked() => + Property.ForAll(Generate, c => + { + var size = RiskRules.SizePurchase(c.Request, _limits); + Assert.IsTrue(size.Quantity >= 0m && size.Quantity <= c.Request.Wanted, $"{size.Quantity} for {c.Request.Wanted}"); + }); + + [TestMethod] + [TestCategory(Category.Unit)] + public void AfterALossNoPurchaseIsLarger() => + Property.ForAll(Generate, c => + { + // The same purchase after a loss: less equity, a lower reference, a multiplier no higher. No doubling, no recovery. + var before = RiskRules.SizePurchase(c.Request, _limits).Quantity; + var factor = 1m - c.Loss; + var after = RiskRules.SizePurchase(c.Request with + { + WorldEquity = c.Request.WorldEquity * factor, + Reference = c.Request.Reference * factor, + Multiplier = c.Request.Multiplier * (1m - (c.Cut / 2m)), + }, _limits).Quantity; + Assert.IsTrue(after <= before, $"{after} after the loss, {before} before"); + }); + + [TestMethod] + [TestCategory(Category.Unit)] + public void NoCorrectiveRaisesAWeight() + { + var holdings = new Dictionary { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) }; + var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100])); + var context = new StrategyContext(StrategyData.Start.AddDays(2), default, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null); + Property.ForAll(g => (Symbol: g.Bool() ? "AAA" : "BBB", Target: (decimal)Math.Round(g.Double() * 0.5, 4), Multiplier: (decimal)Math.Round(g.Double() * 1.5, 4)), c => + { + var intent = new Intent(c.Symbol, c.Target, "test") { Stop = 90m }; + var reduced = BookWeights.Reduce(context, intent, c.Multiplier, CorrectiveReasons.CalendarEvent); + Assert.IsTrue(reduced.TargetWeight is null || reduced.TargetWeight <= c.Target, reduced.ToString()); + }); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCodeCallsNoWithdrawalOrTransferEndpoint() + { + // SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form. + var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw", + System.Text.RegularExpressions.RegexOptions.IgnoreCase); + var offenders = Repo.Files() + .Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) + .Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName))) + .Select(Repo.Relative) + .ToList(); + Assert.IsEmpty(offenders, string.Join(", ", offenders)); + Assert.IsTrue(Repo.Files().Count(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) > 50, "the scan sees the code"); + } + + // ---- 9.2: the monitor of losses ---- + + private static List Points(params (double HoursAgo, decimal Index)[] points) => + [.. points.Select(p => new IndexPoint(_now - TimeSpan.FromHours(p.HoursAgo), p.Index)).OrderBy(p => p.At)]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheDayStartsAtMidnightInItaly() + { + Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 23, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(_now)); + Assert.AreEqual(new DateTimeOffset(2026, 7, 10, 22, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(new DateTimeOffset(2026, 7, 11, 8, 0, 0, TimeSpan.Zero))); + + // A fall at 23:30 in Rome of the day before belongs to yesterday. + var m = RiskMeasures.From(Points((24, 1.00m), (11.5, 0.97m), (0, 0.97m)), _now, null); + Assert.AreEqual(0m, m.DayChange); + Assert.AreEqual(-0.03m, m.Drawdown); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ALossOfTwoPercentInADayBlocksEntriesForTwentyFourHours() + { + var m = RiskMeasures.From(Points((12, 1.00m), (0, 0.975m)), _now, null); + var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits); + Assert.AreEqual(_now + TimeSpan.FromHours(24), reading.State.DailyBlockUntil); + Assert.IsTrue(reading.Alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss)); + Assert.IsTrue(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(23)), "24 hours, not until midnight"); + Assert.IsFalse(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(25))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ALossOfFivePercentInAWeekHalvesRiskForSevenDays() + { + var m = RiskMeasures.From(Points((24 * 7.5, 1.00m), (24 * 6, 0.96m), (12, 0.95m), (0, 0.948m)), _now, null); + Assert.IsTrue(m.WeekChange <= -0.05m); + var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits); + Assert.IsNull(reading.State.DailyBlockUntil); + Assert.AreEqual(0.5m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(6), _limits)); + Assert.AreEqual(1m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(7.1), _limits)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFallFromTheHighHalvesAtTenAndTripsTheSwitchAtFifteen() + { + var half = RiskMonitor.Step(RiskMonitorState.Initial, new RiskMeasures(0m, 0m, -0.11m), _now, _limits); + Assert.AreEqual(0.5m, RiskMonitor.Multiplier(half.State, half.Measures, _now, _limits)); + Assert.IsFalse(half.State.Tripped); + Assert.AreEqual(1, half.Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf)); + Assert.AreEqual(0, RiskMonitor.Step(half.State, half.Measures, _now, _limits).Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf), "said once"); + + var stop = RiskMonitor.Step(half.State, new RiskMeasures(0m, 0m, -0.16m), _now, _limits); + Assert.IsTrue(stop.State.Tripped); + Assert.IsTrue(RiskMonitor.EntriesBlocked(stop.State, _now + TimeSpan.FromDays(30)), "only the user restarts it"); + Assert.AreEqual(RiskSeverities.Critical, stop.Alerts.Single(a => a.Kind == RiskAlertKinds.DrawdownStop).Severity); + + // With the week's halving too the purchases are a quarter. + var both = half.State with { WeeklyHalvingUntil = _now + TimeSpan.FromDays(3) }; + Assert.AreEqual(0.25m, RiskMonitor.Multiplier(both, half.Measures, _now, _limits)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AtEightyPercentOfAThresholdOneWarningAndNoBlock() + { + var near = new RiskMeasures(-0.017m, 0m, -0.017m); + var first = RiskMonitor.Step(RiskMonitorState.Initial, near, _now, _limits); + Assert.AreEqual(1, first.Alerts.Count(a => a.Kind == RiskAlertKinds.Warning), "the day's loss; the fall is far from 8%"); + Assert.IsFalse(RiskMonitor.EntriesBlocked(first.State, _now)); + Assert.AreEqual(1m, RiskMonitor.Multiplier(first.State, near, _now, _limits)); + Assert.AreEqual(0, RiskMonitor.Step(first.State, near, _now, _limits).Alerts.Count, "one for each crossing"); + + var back = RiskMonitor.Step(first.State, RiskMeasures.None, _now, _limits); + Assert.AreEqual(1, RiskMonitor.Step(back.State, near, _now, _limits).Alerts.Count, "a new crossing warns again"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ARestartAfterATripMeasuresTheHighFromNow() + { + var series = Points((48, 1.00m), (0, 0.84m)); + var tripped = RiskMonitor.Step(RiskMonitorState.Initial, RiskMeasures.From(series, _now, null), _now, _limits).State; + Assert.IsTrue(tripped.Tripped); + Assert.AreEqual(1.00m, tripped.Peak); + + var restarted = RiskMonitor.Restart(tripped, _now); + Assert.IsFalse(restarted.Tripped); + Assert.IsNull(restarted.Peak); + var later = _now + TimeSpan.FromHours(1); + var after = RiskMeasures.From([.. series, new IndexPoint(later, 0.84m)], later, restarted.PeakFrom, restarted.Peak); + Assert.AreEqual(0m, after.Drawdown, "otherwise the switch would trip again at once"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheHighIsRememberedBeyondTheSeriesRead() => + Assert.AreEqual(Math.Round((1.0m / 1.2m) - 1m, 6), Math.Round(RiskMeasures.From(Points((1, 1.0m), (0, 1.0m)), _now, null, knownPeak: 1.2m).Drawdown, 6)); + + // ---- 9.2: technical checks ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void TechnicalChecksStopEntriesOnOldPricesFarLimitsAndAWrongClock() + { + Assert.IsNull(RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(59), 100m, 100.9m, TimeSpan.FromSeconds(1), _limits)); + Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(61), 100m, null, null, _limits)); + Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, null, null, null, null, _limits)); + Assert.AreEqual(RiskReasons.PriceGap, RiskRules.TechnicalRefusal(_now, _now, 100m, 101.5m, null, _limits)); + Assert.AreEqual(RiskReasons.ClockSkew, RiskRules.TechnicalRefusal(_now, _now, 100m, null, TimeSpan.FromSeconds(-3), _limits)); + } + + // ---- Settings of the limits ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void LimitsComeFromSettingsAndRaisingOneIsRecognised() + { + var values = RiskSettings.Limits.ToDictionary(d => d.Key, d => d.Default); + Assert.AreEqual(RiskLimits.Default, RiskSettings.From(k => values[k])); + values[RiskSettings.DailyLoss.Key] = "3"; + var looser = RiskSettings.From(k => values[k]); + Assert.AreEqual(0.03m, looser.DailyLoss); + Assert.IsTrue(RiskLimits.Default.RaisedBy(looser)); + Assert.IsFalse(looser.RaisedBy(RiskLimits.Default), "lowering a limit needs no confirmation"); + Assert.IsNotNull(RiskSettings.DailyLoss.Check!("50")); + Assert.AreEqual("off", RiskSettings.PdtGuard.Default, "the day-trade guard is off by default"); + } + + // ---- 9.5: scenarios ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void ScenariosWithAndWithoutStops() + { + var positions = new[] + { + new ScenarioPosition(true, 2_000m, 1_800m), + new ScenarioPosition(false, 3_000m, 2_700m), + new ScenarioPosition(false, 1_000m, null), + }; + var result = Scenarios.Compute(Scenarios.Default, positions, dollarAccountEur: 4_000m, equityEur: 10_000m); + Assert.AreEqual(-400m, result[0].WithoutStops); + Assert.AreEqual(-0.04m, result[0].WithoutStopsShare); + Assert.AreEqual(-200m, result[0].WithStops, "the stop limits the loss"); + Assert.AreEqual(-280m, result[1].WithoutStops); + Assert.AreEqual(-280m, result[1].WithStops, "a 7% fall stays above the stop; without a stop the whole loss"); + Assert.AreEqual(-680m, result[2].WithoutStops); + Assert.AreEqual(-200m, result[3].WithoutStops); + Assert.IsTrue(result[3].SameWithStops); + Assert.IsNull(result[3].WithStops, "stops do not reduce the dollar"); + + // Rounded to 5 euro. + Assert.AreEqual(-25m, Scenarios.Compute([new("x", -0.2m, 0m, 0m)], [new ScenarioPosition(true, 113m, null)], 0m, 1_000m)[0].WithStops); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ScenariosAreASettingTheUserCanWrite() + { + CollectionAssert.AreEqual(Scenarios.Default.ToList(), Scenarios.Parse(Scenarios.Setting.Default).ToList(), "round trip"); + Assert.AreEqual(Scenarios.Default.Count, Scenarios.Parse(Scenarios.Setting.Default).Count); + var custom = Scenarios.Parse("Crollo; −30; −10,5; 0"); + Assert.AreEqual(-0.105m, custom[0].Stocks); + Assert.IsNotNull(Scenarios.Setting.Check!("solo testo")); + Assert.IsNotNull(Scenarios.Setting.Check!("x; -200; 0; 0")); + Assert.IsNull(Scenarios.Setting.Check!(Scenarios.Setting.Default)); + } + + // ---- 8.5: correctives ---- + + private static CalendarEvent Event(string kind, DateTimeOffset at, string impact = "High", string currency = "USD") => + new(kind, "evento", at, true, "test", kind + at.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) { Currency = currency, Impact = impact }; + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCalendarBlocksAroundImportantEvents() + { + var cpi = Event(CalendarEventKinds.Economic, _now); + Assert.AreEqual((_now - TimeSpan.FromMinutes(30), _now + TimeSpan.FromMinutes(30)), CalendarBlocks.Window(cpi)); + Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, impact: "Medium"))); + Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, currency: "EUR"))); + Assert.AreEqual(_now + TimeSpan.FromMinutes(60), CalendarBlocks.Window(Event(CalendarEventKinds.CentralBank, _now, currency: "EUR"))!.Value.To); + + // Two windows that overlap make one block; outside it the entry goes now. + var fed = Event(CalendarEventKinds.CentralBank, _now + TimeSpan.FromMinutes(45)); + Assert.AreEqual(_now + TimeSpan.FromMinutes(105), CalendarBlocks.BlockedUntil(_now - TimeSpan.FromMinutes(10), [cpi, fed])); + Assert.IsNull(CalendarBlocks.BlockedUntil(_now - TimeSpan.FromHours(2), [cpi, fed])); + + // Tried again at the end of the window, or dropped when the deadline comes first. + Assert.AreEqual(_now + TimeSpan.FromMinutes(30), CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromHours(1))); + Assert.IsNull(CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromMinutes(10))); + Assert.AreEqual(new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero), CalendarBlocks.CryptoDeadline(_now)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCalendarStageTurnsEntriesIntoNothingButKeepsStops() + { + var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100])); + var holdings = new Dictionary { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) }; + var context = new StrategyContext(StrategyData.Start.AddDays(2), _now, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null); + var stage = new CalendarStage(_ => [Event(CalendarEventKinds.Economic, _now)]); + var result = stage.Apply(context, [new Intent("AAA", 0.3m, "more") { Stop = 92m }, new Intent("BBB", 0.1m, "new") { Stop = 90m }, new Intent("CCC", 0m, "exit")]); + Assert.IsNull(result[0].TargetWeight); + Assert.AreEqual(92m, result[0].Stop, "the stop of a held position still follows the strategy"); + Assert.IsNull(result[1].TargetWeight); + Assert.IsNull(result[1].Stop); + CollectionAssert.Contains(result[1].Adjustments.ToList(), CorrectiveReasons.CalendarEvent); + Assert.AreEqual(0m, result[2].TargetWeight, "exits pass"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCryptoRegimeIsRiskyBelowTheAverageOrWithHighVolatility() + { + var settings = new CryptoRegimeSettings(); + Assert.IsNull(CryptoRegime.Risky(StrategyData.Series(StrategyData.SteadyRise(400)), settings)); + + var falling = StrategyData.FromCloses([.. Enumerable.Range(0, 260).Select(i => i < 230 ? 100.0 + i : 330.0 - (5 * (i - 229)))]); + Assert.AreEqual(CorrectiveReasons.CryptoRegimeAverage, CryptoRegime.Risky(StrategyData.Series(falling), settings)); + + // Calm for two years, then a week of large swings while the price stays above its average. + var closes = Enumerable.Range(0, 800).Select(i => 100.0 * Math.Pow(1.002, i) * (1 + (0.002 * (i % 2)))).ToList(); + for (var i = 790; i < 800; i++) + { + closes[i] = closes[789] * (i % 2 == 0 ? 1.08 : 1.0); + } + + Assert.AreEqual(CorrectiveReasons.CryptoRegimeVolatility, CryptoRegime.Risky(StrategyData.Series(StrategyData.FromCloses(closes)), settings)); + } + + // ---- The risk engine inside the backtest ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void InTheBacktestAPositionTooHeavyComesBackToTheThreshold() + { + var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100])); + var holdings = new Dictionary { ["AAA"] = new(30m, 100m, 90m, StrategyData.Start) }; + var day = StrategyData.Start.AddDays(2); + var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(7_000m, 10_000m, holdings), _ => bars, _ => StrategyData.Share("AAA")) + { + History = [new EquityMark(day, 10_000m, 3_000m)], + }; + var result = new BacktestRisk().Apply(context, []); + var cut = result.Single(); + Assert.AreEqual("AAA", cut.Symbol); + Assert.AreEqual(0.2m, cut.TargetWeight); + CollectionAssert.Contains(cut.Adjustments.ToList(), RiskReasons.PositionLimit); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void InTheBacktestNewEntriesStopAfterADayOfLosses() + { + var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100])); + var day = StrategyData.Start.AddDays(2); + var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(9_700m, 9_700m, new Dictionary()), _ => bars, + _ => StrategyData.Share("AAA")) + { + History = [new EquityMark(day.AddDays(-1), 10_000m, 0m), new EquityMark(day, 9_700m, 0m)], + }; + var risk = new BacktestRisk(); + var result = risk.Apply(context, [new Intent("AAA", 0.1m, "entry") { Stop = 95m }]); + Assert.IsNull(result[0].TargetWeight); + CollectionAssert.Contains(result[0].Adjustments.ToList(), RiskReasons.DailyLossBlock); + } +}