From 2409e74b268daf22702241b04ed30477586d064b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 14:43:19 +0100 Subject: [PATCH 1/8] Add the three base strategies and their indicators (refs #38 #39 #40) crypto_trend follows nine breakout periods with Donchian-middle stops, volatility-targeted weights under the 35%/20% caps and a monthly top-10 universe. equity_momentum reviews on the last close of each week with the SPY filter, inverse-volatility weights and an ATR trailing stop. equity_meanrev buys RSI(2) dips above the 200-session average, sized for a fixed risk, and exits at the close. The engine gains what the rules need: exits at the same close, a stop set at a distance from the price obtained, data-only instruments such as SPY, the trading calendar, the reference equity of the strategy's share and the equity history. Every strategy passes the look-ahead check. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/Dataset.cs | 62 ++- src/Anubis/Backtest/Engine.cs | 46 +- src/Anubis/Backtest/LookAhead.cs | 2 +- src/Anubis/Backtest/Report.cs | 2 +- src/Anubis/Strategies/CryptoTrend.cs | 478 ++++++++++++++++++ src/Anubis/Strategies/EquityStrategies.cs | 546 +++++++++++++++++++++ src/Anubis/Strategies/Indicators.cs | 264 ++++++++++ src/Anubis/Strategies/Research.cs | 5 +- src/Anubis/Strategies/Strategy.cs | 103 +++- tests/Anubis.Tests/StrategyTests.cs | 562 ++++++++++++++++++++++ 10 files changed, 2051 insertions(+), 19 deletions(-) create mode 100644 src/Anubis/Strategies/CryptoTrend.cs create mode 100644 src/Anubis/Strategies/EquityStrategies.cs create mode 100644 src/Anubis/Strategies/Indicators.cs create mode 100644 tests/Anubis.Tests/StrategyTests.cs diff --git a/src/Anubis/Backtest/Dataset.cs b/src/Anubis/Backtest/Dataset.cs index 1d2247e..5749727 100644 --- a/src/Anubis/Backtest/Dataset.cs +++ b/src/Anubis/Backtest/Dataset.cs @@ -102,14 +102,20 @@ public sealed class BacktestDataset { private readonly Dictionary _bySymbol; - public BacktestDataset(IEnumerable instruments, string currency) + /// Every instrument, the tradable ones and those used only as data. + /// The one currency of the backtest. + /// The market's sessions, which may go beyond the bars; null means the days with bars. + /// Instruments the strategy reads but never trades, such as SPY for the market filter. + public BacktestDataset(IEnumerable instruments, string currency, IEnumerable? calendar = null, IEnumerable? dataOnly = null) { ArgumentNullException.ThrowIfNull(instruments); Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)]; Currency = currency; _bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal); Sessions = [.. Instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Distinct().Order()]; - var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency); + Calendar = [.. (calendar ?? []).Concat(Sessions).Distinct().Order()]; + DataOnly = new SortedSet(dataOnly ?? [], StringComparer.Ordinal); + var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency && !DataOnly.Contains(i.Symbol)); if (wrong is not null) { throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments)); @@ -118,11 +124,47 @@ public sealed class BacktestDataset public IReadOnlyList Instruments { get; } + /// The instruments the strategy may trade: every one but those used only as data. + public IEnumerable Tradable => Instruments.Where(i => !DataOnly.Contains(i.Symbol)); + + public IReadOnlySet DataOnly { get; } + public string Currency { get; } public IReadOnlyList Sessions { get; } - public bool IsCrypto => Instruments.Count > 0 && Instruments.All(i => i.Spec.AssetClass == AssetClasses.Crypto); + /// + /// The market calendar: the sessions with bars and, when given, the later ones. Cutting the data keeps it whole, + /// because a calendar is known in advance. + /// + public IReadOnlyList Calendar { get; } + + /// The next session after : every day for crypto, the calendar for stocks. + public DateOnly? NextSession(DateOnly day) + { + if (IsCrypto) + { + return day.AddDays(1); + } + + int lo = 0, hi = Calendar.Count; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (Calendar[mid] <= day) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo < Calendar.Count ? Calendar[lo] : null; + } + + public bool IsCrypto => Instruments.Count > 0 && Tradable.All(i => i.Spec.AssetClass == AssetClasses.Crypto); /// Sessions in a year, to annualise: crypto trades every day, stocks about 252 days. public int PeriodsPerYear => IsCrypto ? 365 : 252; @@ -130,13 +172,15 @@ public sealed class BacktestDataset public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol); /// The same data cut after : what was known on that day (SPEC 12.2, step 2). - public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency); + public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency, Calendar, DataOnly); /// The same data between two days, both included. public BacktestDataset Between(DateOnly from, DateOnly to) => new( Instruments.Select(i => new BacktestInstrument(i.Spec, [.. i.Bars.Where(b => b.Day >= from && b.Day <= to)], [.. i.Actions.Where(a => a.ExDate > from && a.ExDate <= to)], i.Source)) .Where(i => i.Bars.Count > 0), - Currency); + Currency, + Calendar.Where(d => d >= from), + DataOnly); /// /// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were @@ -146,10 +190,16 @@ public sealed class BacktestDataset { var text = new StringBuilder(); text.Append(Currency).Append('\n'); + if (Calendar.Count > Sessions.Count) + { + text.Append(CultureInfo.InvariantCulture, $"calendar {Calendar.Count} {Calendar[^1]:yyyy-MM-dd}\n"); + } + foreach (var i in Instruments) { var s = i.Spec; - text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}\n"); + text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}"); + text.Append(DataOnly.Contains(i.Symbol) ? "|data\n" : "\n"); foreach (var b in i.Bars) { text.Append(CultureInfo.InvariantCulture, $"{b.Day:yyyy-MM-dd},{b.Open:R},{b.High:R},{b.Low:R},{b.Close:R},{b.Volume:R}\n"); diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index 4c24d5f..a15de41 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -22,6 +22,12 @@ public sealed record BacktestOptions /// The risk engine of SPEC 9. Until Phase 5 it lets everything through. public IIntentStage Risk { get; init; } = PassThroughStage.Risk; + + /// + /// The strategy's share of the bot's total capital (SPEC 8.6, 9.2): the reference equity is the strategy's equity + /// divided by it. Null means the strategy is the whole bot. + /// + public decimal? ReferenceShare { get; init; } } /// A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3. @@ -203,7 +209,10 @@ public static class BacktestEngine public decimal Fees { get; set; } } - private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason); + private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason) + { + public decimal? StopOffset { get; init; } + } private sealed class Simulation { @@ -216,6 +225,7 @@ public static class BacktestEngine private readonly Dictionary _lastClose = new(StringComparer.Ordinal); private readonly Dictionary _actionsDoneThrough = new(StringComparer.Ordinal); private readonly List _equity = []; + private readonly List _history = []; private readonly List _fills = []; private readonly List _trades = []; private readonly List _decisions = []; @@ -358,19 +368,36 @@ public static class BacktestEngine MarkOn(day); var invested = Invested(); _equity.Add(new EquityPoint(day, _cash + invested, _cash, invested)); + _history.Add(new EquityMark(day, _cash + invested, invested)); var record = Decide(day, at); _decisions.Add(record); - Plan(day, record.Final); + // Exits asked for at this close go now (equity_meanrev's 15:55); the rest waits for the next open. + foreach (var exit in record.Final.Where(i => i.AtClose && i.TargetWeight == 0m)) + { + if (_positions.TryGetValue(exit.Symbol, out var p) && _lastClose.TryGetValue(exit.Symbol, out var close)) + { + Sell(day, exit.Symbol, p.Quantity, close, exit.Reason, exit: true); + _pending.Remove(exit.Symbol); + } + } + + Plan(day, [.. record.Final.Where(i => !(i.AtClose && i.TargetWeight == 0m))]); } public DecisionRecord Decide(DateOnly day, DateTimeOffset at) { - var available = _data.Instruments.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList(); - var universe = _strategy.Universe(new UniverseContext(day, available)); + var available = _data.Tradable.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList(); + BarSeries Bars(string s) => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty; + var universe = _strategy.Universe(new UniverseContext(day, available) { Bars = Bars, Spec = s => _data[s]?.Spec }); var equity = _cash + Invested(); var holdings = _positions.ToDictionary(p => p.Key, p => new Holding(p.Value.Quantity, p.Value.AveragePrice, p.Value.Stop, p.Value.EnteredOn), StringComparer.Ordinal); - var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), - s => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty, s => _data[s]?.Spec); + var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), Bars, s => _data[s]?.Spec) + { + NextSession = _data.NextSession(day), + ReferenceEquity = _options.ReferenceShare is > 0m and var share ? equity / share : equity, + PeriodsPerYear = _data.PeriodsPerYear, + History = _history, + }; var proposed = _strategy.Decide(context); var final = proposed; foreach (var stage in _options.Correctives) @@ -438,7 +465,7 @@ public static class BacktestEngine var difference = target - current; if (difference > 0m) { - _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason); + _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason) { StopOffset = intent.StopOffset }; } else if (difference < 0m) { @@ -480,6 +507,11 @@ public static class BacktestEngine p.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity)); p.Quantity += fill.Quantity; p.Stop = order.Stop ?? p.Stop; + if (p.Stop is null && order.StopOffset is > 0m and var offset && price - offset > 0m) + { + // A distance from the price obtained: the stop of a new position (SPEC 8.2, 8.3). + p.Stop = OrderRules.StopPrice(price - offset, OrderRules.TickOf(spec, price - offset)); + } p.Trade.Bought += fill.Gross; p.Trade.CashFlow += fill.CashDelta; p.Trade.Fees += fill.FeeValue; diff --git a/src/Anubis/Backtest/LookAhead.cs b/src/Anubis/Backtest/LookAhead.cs index 7651682..72d097e 100644 --- a/src/Anubis/Backtest/LookAhead.cs +++ b/src/Anubis/Backtest/LookAhead.cs @@ -62,7 +62,7 @@ public static class LookAheadCheck /// Intents as text, with stops to nine significant digits: adjusted prices may differ in the last bit. private static string Describe(IReadOnlyList intents) => string.Join(" | ", intents.Select(i => string.Create( CultureInfo.InvariantCulture, - $"{i.Symbol} {i.TargetWeight?.ToString(CultureInfo.InvariantCulture) ?? "keep"} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {i.Reason}"))); + $"{i.Symbol} {(i.TargetWeight is { } w ? ((double)w).ToString("G9", CultureInfo.InvariantCulture) : "keep")} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {(i.StopOffset is { } o ? ((double)o).ToString("G9", CultureInfo.InvariantCulture) : "-")}{(i.AtClose ? " close" : "")} {i.Reason}"))); } /// How the live intent and the backtest intent for one instrument compare (SPEC 12.3). diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 01e4274..6cb6f07 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -142,7 +142,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.Instruments.Count), data, options); + var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, options); var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Anubis/Strategies/CryptoTrend.cs b/src/Anubis/Strategies/CryptoTrend.cs new file mode 100644 index 0000000..c1b459a --- /dev/null +++ b/src/Anubis/Strategies/CryptoTrend.cs @@ -0,0 +1,478 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Strategies; + +/// The fixed rules of crypto_trend (SPEC 8.1). Only the two family parameters move in a test. +public sealed record CryptoTrendSettings +{ + public IReadOnlyList Periods { get; init; } = [5, 10, 20, 30, 60, 90, 150, 250, 360]; + + /// Volatility each coin is sized to: raw weight = e × this / its volatility. + public double CoinVolatility { get; init; } = 0.15; + + /// Above this estimated volatility of the whole strategy, every weight shrinks by one factor. + public double StrategyVolatility { get; init; } = 0.20; + + /// The server stop is never further than this below the last close. + public double MaxStop { get; init; } = 0.15; + + public decimal MajorCap { get; init; } = 0.35m; + + public decimal OtherCap { get; init; } = 0.20m; + + public IReadOnlySet Majors { get; init; } = new HashSet(StringComparer.OrdinalIgnoreCase) { "BTC", "ETH" }; + + public int VolatilityWindow { get; init; } = 90; + + /// A position is resized only when it is this far from its target, relative to the target… + public decimal RebalanceRelative { get; init; } = 0.20m; + + /// …and this far in share of the strategy's capital. + public decimal RebalanceMinimum { get; init; } = 0.005m; + + public int UniverseSize { get; init; } = CryptoUniverse.Size; + + public int MinAgeDays { get; init; } = CryptoUniverse.MinAgeDays; + + public double MinValue { get; init; } = CryptoUniverse.MinValueEur; + + public double MaxSpreadBp { get; init; } = CryptoUniverse.MaxSpreadBp; + + public int ValueWindow { get; init; } = CryptoUniverse.Window; +} + +/// +/// crypto_trend (SPEC 8.1): Donchian channels on nine periods. A period turns on when a close beats the highest +/// of its previous N closes, with a trailing stop at the middle of the last N closes that can only rise, and turns off +/// when a close ends below yesterday's stop. The average of the nine states, e, sizes each coin against its +/// volatility. The state depends on the whole history: it is rebuilt by walking the daily bars with the backtest's +/// rules, and kept between decisions so each bar is walked once. +/// +public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrategy +{ + private readonly CryptoTrendSettings _settings = settings ?? new CryptoTrendSettings(); + private readonly Dictionary _trackers = new(StringComparer.Ordinal); + private (string Key, IReadOnlyList Members)? _universe; + + public string Id => CryptoTrendFamily.FamilyId; + + public string Version => CryptoTrendFamily.FamilyVersion; + + public CryptoTrendSettings Settings => _settings; + + /// Once a day on the 00:00 UTC close (SPEC 8.1); orders go right after. + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + /// + /// The 10 coins with the highest median traded value over 30 days on the first day of the month, among those + /// listed for 400 days, above the minimum value and, live, below the maximum spread; no stablecoins, wrapped or + /// leveraged tokens. The same for the whole month. + /// + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + var month = new DateOnly(context.Day.Year, context.Day.Month, 1); + if (context.Members?.Invoke(Id, month) is { } saved) + { + return saved; + } + + var key = month.ToString("yyyy-MM", CultureInfo.InvariantCulture) + "|" + string.Join(',', context.Available); + if (_universe is { } cached && cached.Key == key) + { + return cached.Members; + } + + var ranked = new List<(string Symbol, double Value)>(); + foreach (var symbol in context.Available) + { + if (context.Spec(symbol) is not { } spec || spec.AssetClass != AssetClasses.Crypto || CryptoUniverse.Excluded(Symbols.BaseOf(spec))) + { + continue; + } + + var bars = context.Bars(symbol); + var index = bars.IndexThrough(month); + if (index < _settings.ValueWindow - 1 || bars.Day(index) < month.AddDays(-3)) + { + continue; // Too little history, or not trading any more on that day. + } + + var listed = spec.ListedAt is { } at ? DateOnly.FromDateTime(at.UtcDateTime) : bars.FirstDay!.Value; + if (listed > month.AddDays(-_settings.MinAgeDays)) + { + continue; + } + + var value = Indicators.MedianValue(bars, _settings.ValueWindow, index) ?? 0; + if (value <= _settings.MinValue) + { + continue; + } + + if (context.SpreadBp is { } spread && (spread(symbol) is not { } bp || bp >= _settings.MaxSpreadBp)) + { + continue; // Live only: an unknown spread counts as too wide. + } + + ranked.Add((symbol, value)); + } + + var members = ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal) + .Take(_settings.UniverseSize).Select(r => r.Symbol).ToList(); + _universe = (key, members); + return members; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + if (equity <= 0m) + { + return []; + } + + // Coins of the universe, and coins held that left it: those stay managed until their signal exits. + var inUniverse = new HashSet(context.Universe, StringComparer.Ordinal); + var symbols = context.Universe.Concat(context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key)) + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); + + var rows = new List(); + foreach (var symbol in symbols) + { + var bars = context.Bars(symbol); + if (bars.Count == 0) + { + continue; + } + + var tracker = Tracker(symbol).Advance(bars, _settings); + var close = bars.Close(bars.Count - 1); + var holding = context.Portfolio.Of(symbol); + var current = holding is { Quantity: > 0m } h && close > 0 ? h.Quantity * (decimal)close / equity : 0m; + var weight = 0d; + var volatility = Indicators.Volatility(bars, _settings.VolatilityWindow, 365); + if (tracker.Ensemble > 0 && volatility is > 0) + { + var cap = _settings.Majors.Contains(Symbols.BaseOf(context.Spec(symbol), symbol)) ? _settings.MajorCap : _settings.OtherCap; + weight = Math.Min(tracker.Ensemble * _settings.CoinVolatility / volatility.Value, (double)cap); + } + + rows.Add(new Row(symbol, bars, tracker, holding, current, weight, inUniverse.Contains(symbol))); + } + + // Caps first; then, if the weights add up to more than everything, all shrink in proportion; then one factor + // for the volatility of the whole strategy. What is cut stays cash. + var total = rows.Sum(r => r.Weight); + if (total > 1) + { + foreach (var r in rows) + { + r.Weight /= total; + } + } + + var portfolio = Indicators.PortfolioVolatility([.. rows.Where(r => r.Weight > 0).Select(r => (r.Bars, r.Weight))], _settings.VolatilityWindow, 365); + if (portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility) + { + var factor = _settings.StrategyVolatility / portfolio.Value; + foreach (var r in rows) + { + r.Weight *= factor; + } + } + + var intents = new List(); + foreach (var r in rows) + { + var target = Math.Round((decimal)r.Weight, 6, MidpointRounding.ToZero); + if (!r.InUniverse) + { + target = Math.Min(target, r.Current); // Out of the universe: managed, never bought. + } + + var stop = r.Tracker.ServerStop is { } s ? (decimal?)Math.Round((decimal)s, 8) : null; + var held = r.Holding is { Quantity: > 0m }; + if (held && target <= 0m) + { + intents.Add(new Intent(r.Symbol, 0m, Reasons.Exit)); + } + else if (!held && target > 0m) + { + if (target > _settings.RebalanceMinimum) + { + intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop }); + } + } + else if (held) + { + var gap = Math.Abs(target - r.Current); + if (gap > _settings.RebalanceRelative * target && gap > _settings.RebalanceMinimum) + { + intents.Add(new Intent(r.Symbol, target, target > r.Current ? Reasons.Increase : Reasons.Reduce) { Stop = stop }); + } + else if (stop is not null && stop != r.Holding!.Stop) + { + intents.Add(new Intent(r.Symbol, null, Reasons.StopMoved) { Stop = stop }); + } + } + } + + return intents; + } + + /// The state of a coin as of its last bar walked: the nine periods, e, the server stop. + public TrendTracker Tracker(string symbol) + { + if (!_trackers.TryGetValue(symbol, out var tracker)) + { + tracker = new TrendTracker(); + _trackers[symbol] = tracker; + } + + return tracker; + } + + public static class Reasons + { + public const string Entry = "trend_entry"; + public const string Increase = "trend_increase"; + public const string Reduce = "trend_reduce"; + public const string Exit = "trend_exit"; + public const string StopMoved = "trend_stop"; + } + + private sealed class Row(string symbol, BarSeries bars, TrendTracker tracker, Holding? holding, decimal current, double weight, bool inUniverse) + { + public string Symbol { get; } = symbol; + + public BarSeries Bars { get; } = bars; + + public TrendTracker Tracker { get; } = tracker; + + public Holding? Holding { get; } = holding; + + public decimal Current { get; } = current; + + public double Weight { get; set; } = weight; + + public bool InUniverse { get; } = inUniverse; + } +} + +/// +/// The Donchian states of one coin (SPEC 8.1), walked one daily bar at a time. Walking the same bars always gives the +/// same state: from scratch on the first start, or from the saved state and the bars missing since. +/// +public sealed class TrendTracker +{ + private bool[] _active = []; + private double[] _stops = []; + private int _walked; + private DateOnly? _first; + private DateOnly? _last; + + /// The average of the period states, between 0 and 1. + public double Ensemble { get; private set; } + + /// The level of the stop on the broker; null when no period is on. + public double? ServerStop { get; private set; } + + /// The day of the last bar walked. + public DateOnly? LastDay => _last; + + public IReadOnlyList Active => _active; + + /// Walks the bars not walked yet. A history that does not continue the one walked starts again. + public TrendTracker Advance(BarSeries bars, CryptoTrendSettings settings) + { + ArgumentNullException.ThrowIfNull(bars); + ArgumentNullException.ThrowIfNull(settings); + if (_active.Length != settings.Periods.Count || bars.Count < _walked || (_walked > 0 && (bars.FirstDay != _first || bars.Day(_walked - 1) != _last))) + { + Reset(settings); + } + + for (var i = _walked; i < bars.Count; i++) + { + Step(bars, i, settings); + } + + _walked = bars.Count; + _first = bars.FirstDay; + _last = bars.LastDay; + return this; + } + + private void Reset(CryptoTrendSettings settings) + { + _active = new bool[settings.Periods.Count]; + _stops = new double[settings.Periods.Count]; + _walked = 0; + _first = null; + _last = null; + Ensemble = 0; + ServerStop = null; + } + + private void Step(BarSeries bars, int i, CryptoTrendSettings settings) + { + var close = bars.Close(i); + // The stop on the broker, touched by the low of the day: every period of the coin goes back to 0 and a new + // high is needed to come back. The backtest applies the same rule (SPEC 8.1). + if (Ensemble > 0 && ServerStop is { } server && bars.Low(i) <= server) + { + Array.Clear(_active); + Ensemble = 0; + ServerStop = null; + } + + var activated = false; + for (var k = 0; k < settings.Periods.Count; k++) + { + var n = settings.Periods[k]; + if (i < n) + { + continue; // Not N previous closes yet. + } + + if (_active[k]) + { + if (close < _stops[k]) + { + _active[k] = false; // A close below yesterday's stop. + continue; + } + + _stops[k] = Math.Max(_stops[k], Middle(bars, i, n)); + } + else if (close > HighestBefore(bars, i, n)) + { + _active[k] = true; + _stops[k] = Middle(bars, i, n); + activated = true; + } + } + + var on = 0; + var lowest = double.MaxValue; + for (var k = 0; k < _active.Length; k++) + { + if (_active[k]) + { + on++; + lowest = Math.Min(lowest, _stops[k]); + } + } + + Ensemble = (double)on / _active.Length; + if (on == 0) + { + ServerStop = null; + return; + } + + // Where every active period would have left, but never more than the maximum below the close. It can only rise, + // except when a period turns on and brings a lower stop with it. + var candidate = Math.Max(lowest, close * (1 - settings.MaxStop)); + ServerStop = ServerStop is { } previous && !activated ? Math.Max(previous, candidate) : candidate; + } + + /// The highest of the N closes before bar i. + private static double HighestBefore(BarSeries bars, int i, int n) + { + var high = double.MinValue; + for (var j = i - n; j < i; j++) + { + high = Math.Max(high, bars.Close(j)); + } + + return high; + } + + /// The middle between the highest and the lowest of the last N closes, bar i included. + private static double Middle(BarSeries bars, int i, int n) + { + double high = double.MinValue, low = double.MaxValue; + for (var j = i - n + 1; j <= i; j++) + { + var c = bars.Close(j); + high = Math.Max(high, c); + low = Math.Min(low, c); + } + + return (high + low) / 2; + } +} + +public sealed class CryptoTrendFamily : IStrategyFamily +{ + public const string FamilyId = "crypto_trend"; + + public const string FamilyVersion = "1"; + + public static CryptoTrendFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Trend crypto"; + + public string Description => + "Segue la tendenza delle 10 crypto più scambiate in euro. Compra quando il prezzo supera i massimi recenti su nove orizzonti, da 5 a 360 giorni, " + + "e più orizzonti sono d'accordo più compra; pesa meno le monete più agitate. Esce quando il prezzo scende sotto lo stop, che sale con il prezzo."; + + public IReadOnlyList Parameters => + [ + new("coin_vol", "Volatilità obiettivo per moneta (%)", 15m, [10m, 15m, 20m], 1m, 100m, Whole: true), + new("max_stop", "Stop al massimo sotto la chiusura (%)", 15m, [10m, 15m, 20m], 2m, 50m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return new CryptoTrend(new CryptoTrendSettings + { + CoinVolatility = (double)parameters["coin_vol"] / 100, + MaxStop = (double)parameters["max_stop"] / 100, + }); + } +} + +/// Reading the coin or company behind a symbol. +public static class Symbols +{ + private static readonly string[] Quotes = ["USDT", "USDC", "EUR", "USD", "BTC"]; + + /// The base currency of a pair: BTC for BTC-EUR and for BTCUSDT. + public static string BaseOf(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + return spec.BaseCurrency ?? BaseOf(spec.Symbol); + } + + public static string BaseOf(InstrumentSpec? spec, string symbol) => spec is null ? BaseOf(symbol) : BaseOf(spec); + + public static string BaseOf(string symbol) + { + ArgumentNullException.ThrowIfNull(symbol); + var dash = symbol.IndexOf('-', StringComparison.Ordinal); + if (dash > 0) + { + return symbol[..dash]; + } + + foreach (var quote in Quotes) + { + if (symbol.Length > quote.Length && symbol.EndsWith(quote, StringComparison.OrdinalIgnoreCase)) + { + return symbol[..^quote.Length]; + } + } + + return symbol; + } +} diff --git a/src/Anubis/Strategies/EquityStrategies.cs b/src/Anubis/Strategies/EquityStrategies.cs new file mode 100644 index 0000000..9092f0b --- /dev/null +++ b/src/Anubis/Strategies/EquityStrategies.cs @@ -0,0 +1,546 @@ +using Anubis.Data; + +namespace Anubis.Strategies; + +/// +/// The stock universe of SPEC 8.2 computed from the bars known on the day: common shares on NYSE and Nasdaq, +/// fractionable, no funds, real close above 10 $, at least 300 sessions, ranked by the median traded value of the last +/// 60 sessions. Live, the universe saved "as of the date" is used instead (SPEC 6.7). +/// +public static class EquityUniverseRanking +{ + public static IReadOnlyList Rank(UniverseContext context, int size) + { + ArgumentNullException.ThrowIfNull(context); + var ranked = new List<(string Symbol, double Value)>(); + foreach (var symbol in context.Available) + { + if (context.Spec(symbol) is not { } spec || !EquityUniverse.Eligible(spec)) + { + continue; + } + + var bars = context.Bars(symbol); + var last = bars.Count - 1; + if (bars.Count < EquityUniverse.MinSessions || bars.Day(last) < context.Day.AddDays(-7) || bars.RealClose(last) <= EquityUniverse.MinPrice) + { + continue; + } + + ranked.Add((symbol, Indicators.MedianValue(bars, EquityUniverse.Window, last) ?? 0)); + } + + return [.. ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal).Take(size).Select(r => r.Symbol)]; + } + + /// Monday of the week of a day: two days are in the same week when their Mondays match. + public static DateOnly WeekOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7)); +} + +/// The fixed rules of equity_momentum (SPEC 8.2). +public sealed record EquityMomentumSettings +{ + public int UniverseSize { get; init; } = EquityUniverse.Size; + + public IReadOnlyList Lookbacks { get; init; } = [63, 126, 252]; + + /// The returns skip the last sessions (short-term reversal). + public int Skip { get; init; } = 5; + + /// New entries among the first of the ranking… + public int Top { get; init; } = 12; + + /// …and a stock held leaves when it falls out of these. + public int Keep { get; init; } = 30; + + public int MaxPositions { get; init; } = 12; + + /// Each stock must close above its own average of these sessions. + public int Trend { get; init; } = 100; + + /// The market filter: SPY above its average of these sessions. + public int MarketTrend { get; init; } = 200; + + public string MarketSymbol { get; init; } = "SPY"; + + public int AtrLength { get; init; } = 20; + + public double AtrMultiple { get; init; } = 3; + + public int VolatilityWindow { get; init; } = 60; + + public double StrategyVolatility { get; init; } = 0.20; + + public decimal Cap { get; init; } = 0.15m; + + /// A position already open is resized only when this far from its target, relative to the target. + public decimal Rebalance { get; init; } = 0.25m; +} + +/// +/// equity_momentum (SPEC 8.2): the strongest US stocks, only while the market rises. The weekly review runs on +/// the close of the last session before a new week, so its orders go at the open of the first session of the week +/// (live: 09:35 of that session, on the same data). Every close moves the trailing stops. +/// +public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IStrategy +{ + private readonly EquityMomentumSettings _settings = settings ?? new EquityMomentumSettings(); + + public string Id => EquityMomentumFamily.FamilyId; + + public string Version => EquityMomentumFamily.FamilyVersion; + + public EquityMomentumSettings Settings => _settings; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.Members?.Invoke(Id, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize); + } + + /// True when the next session opens a new week: the close of today is the time of the weekly review. + public static bool IsReview(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.NextSession is { } next && EquityUniverseRanking.WeekOf(next) != EquityUniverseRanking.WeekOf(context.Day); + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + var held = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key).Order(StringComparer.Ordinal).ToList(); + var stops = new Dictionary(StringComparer.Ordinal); + foreach (var symbol in held) + { + if (TrailingStop(context, symbol) is { } stop) + { + stops[symbol] = stop; + } + } + + var intents = new SortedDictionary(StringComparer.Ordinal); + foreach (var (symbol, stop) in stops) + { + intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop }; + } + + if (!IsReview(context) || equity <= 0m) + { + return [.. intents.Values]; + } + + // The ranking: average of the 63, 126 and 252 session returns, each skipping the last 5 sessions. + var scores = new List<(string Symbol, double Score)>(); + foreach (var symbol in context.Universe) + { + var bars = context.Bars(symbol); + var parts = _settings.Lookbacks.Select(n => Indicators.Momentum(bars, n, _settings.Skip)).ToList(); + if (parts.All(p => p is not null)) + { + scores.Add((symbol, parts.Average(p => p!.Value))); + } + } + + var ranking = scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal).Select(s => s.Symbol).ToList(); + var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal); + bool AboveTrend(string symbol) + { + var bars = context.Bars(symbol); + return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Count > 0 && bars.Close(bars.Count - 1) > average; + } + + var market = context.Bars(_settings.MarketSymbol); + var marketUp = Indicators.Sma(market, _settings.MarketTrend) is { } spyAverage && market.Close(market.Count - 1) > spyAverage; + + var keep = new List(); + foreach (var symbol in held) + { + if (!rank.TryGetValue(symbol, out var r) || r >= _settings.Keep) + { + intents[symbol] = new Intent(symbol, 0m, Reasons.ExitRank); + } + else if (!AboveTrend(symbol)) + { + intents[symbol] = new Intent(symbol, 0m, Reasons.ExitTrend); + } + else + { + keep.Add(symbol); + } + } + + // New entries only while SPY is above its average, and only among the first 12. + var entries = new List(); + if (marketUp) + { + foreach (var symbol in ranking.Take(_settings.Top)) + { + if (keep.Count + entries.Count >= _settings.MaxPositions) + { + break; + } + + if (!held.Contains(symbol) && AboveTrend(symbol)) + { + entries.Add(symbol); + } + } + } + + var weights = Weights(context, [.. keep, .. entries]); + foreach (var symbol in entries) + { + if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr) + { + intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8) }; + } + } + + foreach (var symbol in keep) + { + var bars = context.Bars(symbol); + var holding = context.Portfolio.Of(symbol)!; + var current = holding.Quantity * (decimal)bars.Close(bars.Count - 1) / equity; + var target = weights.GetValueOrDefault(symbol, current); + if (!marketUp) + { + target = Math.Min(target, current); // With SPY below its average the strategy can only sell. + } + + if (Math.Abs(target - current) > _settings.Rebalance * target) + { + intents[symbol] = new Intent(symbol, target, target > current ? Reasons.Increase : Reasons.Reduce) { Stop = stops.GetValueOrDefault(symbol, holding.Stop ?? 0m) is > 0m and var s ? s : null }; + } + } + + return [.. intents.Values]; + } + + /// + /// Weights in inverse proportion to the 60-session volatility, the 15% cap (what it cuts stays cash), then one + /// factor, never above 1, when the strategy's estimated volatility is above 20% a year. + /// + private Dictionary Weights(StrategyContext context, IReadOnlyList members) + { + var inverse = new Dictionary(StringComparer.Ordinal); + foreach (var symbol in members) + { + if (Indicators.Volatility(context.Bars(symbol), _settings.VolatilityWindow, 252) is > 0 and var vol) + { + inverse[symbol] = 1 / vol; + } + } + + var sum = inverse.Values.Sum(); + var raw = inverse.ToDictionary(p => p.Key, p => Math.Min(p.Value / sum, (double)_settings.Cap), StringComparer.Ordinal); + var portfolio = Indicators.PortfolioVolatility([.. raw.Select(p => (context.Bars(p.Key), p.Value))], _settings.VolatilityWindow, 252); + var factor = portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility ? _settings.StrategyVolatility / portfolio.Value : 1; + return raw.ToDictionary(p => p.Key, p => Math.Round((decimal)(p.Value * factor), 6, MidpointRounding.ToZero), StringComparer.Ordinal); + } + + /// 3 ATR(20) below the highest close since the entry; it can only rise. + private decimal? TrailingStop(StrategyContext context, string symbol) + { + var holding = context.Portfolio.Of(symbol)!; + var bars = context.Bars(symbol); + if (Indicators.Atr(bars, _settings.AtrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high) + { + return null; + } + + var candidate = Math.Round((decimal)(high - (_settings.AtrMultiple * atr)), 8); + if (candidate <= 0m || (holding.Stop is { } current && candidate <= current)) + { + return null; + } + + return candidate; + } + + public static class Reasons + { + public const string Entry = "momentum_entry"; + public const string Increase = "momentum_increase"; + public const string Reduce = "momentum_reduce"; + public const string ExitRank = "momentum_exit_rank"; + public const string ExitTrend = "momentum_exit_trend"; + public const string StopMoved = "momentum_stop"; + } +} + +public sealed class EquityMomentumFamily : IStrategyFamily +{ + public const string FamilyId = "equity_momentum"; + + public const string FamilyVersion = "1"; + + public static EquityMomentumFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Momentum azioni"; + + public string Description => + "Ogni settimana compra le azioni americane salite di più nell'ultimo anno, fino a 12, ma solo quando il mercato nel suo insieme sale. " + + "Vende quelle che perdono forza o scendono sotto la loro media; ognuna ha uno stop che sale con il prezzo."; + + public IReadOnlyList Parameters => + [ + new("positions", "Numero massimo di titoli", 12m, [8m, 12m, 16m], 3m, 30m, Whole: true), + new("stop_atr", "Stop in ATR sotto il massimo", 3m, [2m, 3m, 4m], 1m, 10m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + var positions = parameters.Whole("positions"); + return new EquityMomentum(new EquityMomentumSettings + { + Top = positions, + MaxPositions = positions, + AtrMultiple = (double)parameters["stop_atr"], + }); + } +} + +/// The fixed rules of equity_meanrev (SPEC 8.3). +public sealed record EquityMeanrevSettings +{ + public int UniverseSize { get; init; } = 100; + + public int Trend { get; init; } = 200; + + public int RsiLength { get; init; } = 2; + + public double EntryRsi { get; init; } = 10; + + public double ExitRsi { get; init; } = 70; + + public int Fast { get; init; } = 5; + + public int MaxPositions { get; init; } = 3; + + /// The entry session is the first: the time exit comes at the close of the fifth. + public int MaxSessions { get; init; } = 5; + + public int AtrLength { get; init; } = 14; + + public double AtrMultiple { get; init; } = 2.5; + + /// Risk of one operation, as a share of the reference equity of SPEC 9.2. + public decimal RiskPerTrade { get; init; } = 0.004m; + + public decimal Cap { get; init; } = 0.30m; + + /// The day-trade guard of SPEC 9.2, off by default: never exit on the entry day. + public bool PdtGuard { get; init; } + + /// Sessions after the entry in which an earnings report keeps the strategy out. + public int EarningsSessions { get; init; } = 3; +} + +/// +/// equity_meanrev (SPEC 8.3): buys the short dips of solid stocks. On the close, RSI(2) below 10 and the close +/// below its 5-session average; buys at the next open the lowest RSI, up to 3 positions. It exits at 15:55 (in the +/// backtest: the close) above the 5-session average, with RSI(2) above 70, before earnings, or at the fifth session. +/// +public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStrategy +{ + private readonly EquityMeanrevSettings _settings = settings ?? new EquityMeanrevSettings(); + + public string Id => EquityMeanrevFamily.FamilyId; + + public string Version => EquityMeanrevFamily.FamilyVersion; + + public EquityMeanrevSettings Settings => _settings; + + public IReadOnlyList Schedule() => [DecisionTime.AfterClose]; + + /// The first 100 stocks of the universe of 8.2, in its order, that close above their 200-session average. + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + var ranked = context.Members?.Invoke(EquityMomentumFamily.FamilyId, context.Day) ?? EquityUniverseRanking.Rank(context, EquityUniverse.Size); + return [.. ranked.Where(s => + { + var bars = context.Bars(s); + return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Close(bars.Count - 1) > average; + }).Take(_settings.UniverseSize)]; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + var intents = new List(); + var freeCash = context.Portfolio.Cash; + var open = 0; + foreach (var (symbol, holding) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).OrderBy(h => h.Key, StringComparer.Ordinal)) + { + var bars = context.Bars(symbol); + if (bars.Count == 0) + { + open++; + continue; + } + + var close = bars.Close(bars.Count - 1); + var sessions = Indicators.SessionsSince(bars, holding.EnteredOn); + var reason = ExitReason(context, symbol, bars, close, sessions); + if (reason is not null && !(_settings.PdtGuard && sessions <= 1)) + { + intents.Add(new Intent(symbol, 0m, reason) { AtClose = true }); + freeCash += holding.Quantity * (decimal)close; // Sold at this close, before tomorrow's entries. + } + else + { + open++; + } + } + + var slots = _settings.MaxPositions - open; + if (slots <= 0 || equity <= 0m) + { + return intents; + } + + var candidates = new List<(string Symbol, double Rsi, double Close, double Atr)>(); + foreach (var symbol in context.Universe) + { + if (context.Portfolio.Holds(symbol) || context.Restricted?.Invoke(symbol) == true || EarningsAhead(context, symbol)) + { + continue; + } + + var bars = context.Bars(symbol); + if (Indicators.Rsi(bars, _settings.RsiLength) is not { } rsi || Indicators.Sma(bars, _settings.Fast) is not { } fast + || Indicators.Atr(bars, _settings.AtrLength) is not { } atr) + { + continue; + } + + var close = bars.Close(bars.Count - 1); + if (rsi < _settings.EntryRsi && close < fast) + { + candidates.Add((symbol, rsi, close, atr)); + } + } + + foreach (var c in candidates.OrderBy(c => c.Rsi).ThenBy(c => c.Symbol, StringComparer.Ordinal)) + { + if (slots == 0) + { + break; + } + + // Risk of 0.4% of the reference equity at the stop distance, capped at 30% of the strategy's capital. + var distance = Math.Round((decimal)(c.Atr * _settings.AtrMultiple), 8); + if (distance <= 0m) + { + continue; + } + + var value = _settings.RiskPerTrade * context.ReferenceEquity / distance * (decimal)c.Close; + value = Math.Min(value, _settings.Cap * equity); + if (value > freeCash) + { + continue; // Not enough free capital for this candidate: it is dropped. + } + + intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = distance }); + freeCash -= value; + slots--; + } + + return intents; + } + + private string? ExitReason(StrategyContext context, string symbol, BarSeries bars, double close, int sessions) + { + if (Indicators.Sma(bars, _settings.Fast) is { } fast && close > fast) + { + return Reasons.ExitAverage; + } + + if (Indicators.Rsi(bars, _settings.RsiLength) is > 0 and var rsi && rsi > _settings.ExitRsi) + { + return Reasons.ExitRsi; + } + + if (context.NextEarnings?.Invoke(symbol) is { } earnings && context.NextSession is { } next && earnings <= next) + { + return Reasons.ExitEarnings; // The report comes out by the close of the next session. + } + + return sessions >= _settings.MaxSessions ? Reasons.ExitTime : null; + } + + /// + /// Earnings in the entry session or the three after it, or out after today's close (live only: the backtest has no + /// earnings calendar, SPEC 8.3). + /// + private bool EarningsAhead(StrategyContext context, string symbol) + { + if (context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry) + { + return false; + } + + var last = entry; + for (var i = 0; i < _settings.EarningsSessions; i++) + { + last = last.AddDays(last.DayOfWeek == DayOfWeek.Friday ? 3 : 1); + } + + return earnings >= context.Day && earnings <= last; + } + + public static class Reasons + { + public const string Entry = "meanrev_entry"; + public const string ExitAverage = "meanrev_exit_average"; + public const string ExitRsi = "meanrev_exit_rsi"; + public const string ExitEarnings = "meanrev_exit_earnings"; + public const string ExitTime = "meanrev_exit_time"; + } +} + +public sealed class EquityMeanrevFamily : IStrategyFamily +{ + public const string FamilyId = "equity_meanrev"; + + public const string FamilyVersion = "1"; + + public static EquityMeanrevFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Mean reversion azioni"; + + public string Description => + "Compra le azioni solide, sopra la loro media di 200 giorni, dopo un calo di pochi giorni, e le rivende al primo rimbalzo o dopo cinque sedute. " + + "Al massimo 3 posizioni, ognuna con un rischio piccolo e uno stop fisso."; + + public IReadOnlyList Parameters => + [ + new("entry_rsi", "RSI a 2 giorni per entrare (sotto)", 10m, [5m, 10m, 15m], 1m, 50m, Whole: true), + new("max_sessions", "Sedute al massimo in portafoglio", 5m, [3m, 5m, 7m], 1m, 20m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return new EquityMeanrev(new EquityMeanrevSettings + { + EntryRsi = (double)parameters["entry_rsi"], + MaxSessions = parameters.Whole("max_sessions"), + }); + } +} diff --git a/src/Anubis/Strategies/Indicators.cs b/src/Anubis/Strategies/Indicators.cs new file mode 100644 index 0000000..5a34ea1 --- /dev/null +++ b/src/Anubis/Strategies/Indicators.cs @@ -0,0 +1,264 @@ +namespace Anubis.Strategies; + +/// +/// The indicators of the strategies (SPEC 8), written in house (SPEC 2.7). Each reads a up to +/// its last bar, so it cannot look ahead. They return null when the history is too short: a strategy then does not +/// act on that instrument. +/// +public static class Indicators +{ + /// Simple average of the last closes. + public static double? Sma(BarSeries bars, int length) => Sma(bars, length, bars?.Count - 1 ?? -1); + + /// Simple average of the closes ending at , included. + public static double? Sma(BarSeries bars, int length, int end) + { + ArgumentNullException.ThrowIfNull(bars); + if (length <= 0 || end < length - 1 || end >= bars.Count) + { + return null; + } + + var sum = 0d; + for (var i = end - length + 1; i <= end; i++) + { + sum += bars.Close(i); + } + + return sum / length; + } + + /// + /// Average true range: the simple average of the last true ranges, each the largest of + /// high − low, |high − previous close| and |low − previous close|. A plain average, so the value depends only on + /// those bars and not on where the history starts. + /// + public static double? Atr(BarSeries bars, int length) + { + ArgumentNullException.ThrowIfNull(bars); + var end = bars.Count - 1; + if (length <= 0 || end < length) + { + return null; + } + + var sum = 0d; + for (var i = end - length + 1; i <= end; i++) + { + var previous = bars.Close(i - 1); + var high = bars.High(i); + var low = bars.Low(i); + sum += Math.Max(high - low, Math.Max(Math.Abs(high - previous), Math.Abs(low - previous))); + } + + return sum / length; + } + + /// + /// Wilder's relative strength index on the closes. The smoothing starts from a plain average of the first + /// changes of a window of × length bars: older bars weigh less + /// than one part in a million, and the value does not depend on where the history starts. + /// + public static double? Rsi(BarSeries bars, int length) + { + ArgumentNullException.ThrowIfNull(bars); + if (length <= 0 || bars.Count < length + 1) + { + return null; + } + + var start = Math.Max(0, bars.Count - (RsiWarmUp * length) - 1); + double gain = 0, loss = 0; + for (var i = start + 1; i <= start + length; i++) + { + var change = bars.Close(i) - bars.Close(i - 1); + gain += Math.Max(change, 0); + loss += Math.Max(-change, 0); + } + + gain /= length; + loss /= length; + for (var i = start + length + 1; i < bars.Count; i++) + { + var change = bars.Close(i) - bars.Close(i - 1); + gain = ((gain * (length - 1)) + Math.Max(change, 0)) / length; + loss = ((loss * (length - 1)) + Math.Max(-change, 0)) / length; + } + + if (loss == 0) + { + return gain == 0 ? 50 : 100; + } + + return 100 - (100 / (1 + (gain / loss))); + } + + /// Bars of history the RSI reads, in multiples of its length. + public const int RsiWarmUp = 50; + + /// The last simple daily returns, oldest first; null when the history is shorter. + public static double[]? Returns(BarSeries bars, int count) + { + ArgumentNullException.ThrowIfNull(bars); + if (count <= 0 || bars.Count < count + 1) + { + return null; + } + + var result = new double[count]; + var first = bars.Count - count; + for (var i = 0; i < count; i++) + { + var before = bars.Close(first + i - 1); + result[i] = before > 0 ? (bars.Close(first + i) / before) - 1 : 0; + } + + return result; + } + + /// + /// Annualised volatility of the last daily returns: sample standard deviation times the + /// square root of the sessions in a year. + /// + public static double? Volatility(BarSeries bars, int count, int periodsPerYear) + { + var returns = Returns(bars, count); + if (returns is null || returns.Length < 2) + { + return null; + } + + return StandardDeviation(returns) * Math.Sqrt(periodsPerYear); + } + + /// + /// The return over sessions that ends sessions before the last + /// bar: close[t − skip] / close[t − skip − length] − 1. + /// + public static double? Momentum(BarSeries bars, int length, int skip) + { + ArgumentNullException.ThrowIfNull(bars); + var end = bars.Count - 1 - skip; + var start = end - length; + if (start < 0 || end < 0) + { + return null; + } + + var before = bars.Close(start); + return before > 0 ? (bars.Close(end) / before) - 1 : null; + } + + /// + /// Annualised volatility of a portfolio with the given weights, from the covariance of the last + /// daily returns of each instrument, aligned by day. Days missing for an instrument count + /// as no change. Null when no instrument has enough history. + /// + public static double? PortfolioVolatility(IReadOnlyList<(BarSeries Bars, double Weight)> holdings, int count, int periodsPerYear) + { + ArgumentNullException.ThrowIfNull(holdings); + var series = new List<(Dictionary Returns, double Weight)>(); + var days = new SortedSet(); + foreach (var (bars, weight) in holdings) + { + if (weight == 0 || bars.Count < count + 1) + { + continue; + } + + var map = new Dictionary(count); + for (var i = bars.Count - count; i < bars.Count; i++) + { + var before = bars.Close(i - 1); + map[bars.Day(i)] = before > 0 ? (bars.Close(i) / before) - 1 : 0; + } + + series.Add((map, weight)); + } + + if (series.Count == 0) + { + return null; + } + + // The common calendar is the last `count` days any of them traded. + foreach (var (map, _) in series) + { + days.UnionWith(map.Keys); + } + + var calendar = days.TakeLast(count).ToList(); + if (calendar.Count < 2) + { + return null; + } + + var portfolio = calendar.Select(d => series.Sum(s => s.Weight * s.Returns.GetValueOrDefault(d))).ToArray(); + return StandardDeviation(portfolio) * Math.Sqrt(periodsPerYear); + } + + /// Sample standard deviation (n − 1). + public static double StandardDeviation(IReadOnlyList values) + { + ArgumentNullException.ThrowIfNull(values); + if (values.Count < 2) + { + return 0; + } + + var mean = values.Average(); + var sum = 0d; + foreach (var v in values) + { + sum += (v - mean) * (v - mean); + } + + return Math.Sqrt(sum / (values.Count - 1)); + } + + /// Highest close from to the last bar, both included. + public static double? HighestCloseSince(BarSeries bars, DateOnly from) + { + ArgumentNullException.ThrowIfNull(bars); + double? high = null; + for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--) + { + high = Math.Max(high ?? double.MinValue, bars.Close(i)); + } + + return high; + } + + /// Sessions from to the last bar, both included. + public static int SessionsSince(BarSeries bars, DateOnly from) + { + ArgumentNullException.ThrowIfNull(bars); + var n = 0; + for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--) + { + n++; + } + + return n; + } + + /// Median of the last traded values (close × volume, or the quote volume when known). + public static double? MedianValue(BarSeries bars, int count, int end) + { + ArgumentNullException.ThrowIfNull(bars); + if (end < count - 1 || end >= bars.Count) + { + return null; + } + + var values = new double[count]; + for (var i = 0; i < count; i++) + { + var k = end - count + 1 + i; + values[i] = bars.Value(k); + } + + Array.Sort(values); + return count % 2 == 1 ? values[count / 2] : (values[(count / 2) - 1] + values[count / 2]) / 2; + } +} diff --git a/src/Anubis/Strategies/Research.cs b/src/Anubis/Strategies/Research.cs index 04dabc0..43a3290 100644 --- a/src/Anubis/Strategies/Research.cs +++ b/src/Anubis/Strategies/Research.cs @@ -143,10 +143,11 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily } } -/// The strategies the laboratory can test. The bot's own strategies join with Phase 5. +/// The strategies the laboratory can test: the three of the bot first, then the examples. public static class StrategyCatalog { - public static IReadOnlyList All { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance]; + public static IReadOnlyList All { get; } = + [CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance]; public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id); } diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index 24bd73d..d34f3c4 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -28,6 +28,18 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason) { public decimal? Stop { get; init; } + /// + /// For a new position: the stop goes this far below the price obtained (a distance in today's prices, such as 3 + /// ATR). Ignored when is given or the position already has a stop. + /// + public decimal? StopOffset { get; init; } + + /// + /// An exit to carry out at this close rather than at the next open: equity_meanrev sells at 15:55 live, + /// which the daily backtest reads as the close (SPEC 8.3). + /// + public bool AtClose { get; init; } + 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})"); } @@ -94,6 +106,42 @@ public sealed class BarSeries public double Volume(int index) => Bar(index).Volume; + /// Value traded in the session, in the quote currency: the source's own figure, or close × volume. + public double Value(int index) + { + var bar = Bar(index); + return bar.QuoteVolume ?? (bar.Close * bar.Volume); + } + + /// The real close of the session, as traded that day, not adjusted to today. + public double RealClose(int index) => Bar(index).Close; + + /// Index of the last bar on or before ; −1 when there is none. + public int IndexThrough(DateOnly day) + { + int lo = 0, hi = Count; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (_bars[mid].Day <= day) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo - 1; + } + + /// The first day of the history; null when there is none. + public DateOnly? FirstDay => Count > 0 ? _bars[0].Day : null; + + /// The day of the last bar; null when there is none. + public DateOnly? LastDay => Count > 0 ? _bars[Count - 1].Day : null; + /// The last closes, oldest first (fewer when the history is shorter). public double[] Closes(int length) { @@ -115,8 +163,22 @@ public sealed class BarSeries } } -/// What a strategy may read to choose its instruments for a decision. -public sealed record UniverseContext(DateOnly Day, IReadOnlyList Available); +/// +/// What a strategy may read to choose its instruments for a decision: the instruments with data, their bars up to the +/// day and their rules. Live, gives the universes chosen and saved "as of a date" (SPEC 6.7). +/// +public sealed record UniverseContext(DateOnly Day, IReadOnlyList Available) +{ + public Func Bars { get; init; } = _ => BarSeries.Empty; + + public Func Spec { get; init; } = _ => null; + + /// Median spread of the last 30 days in basis points, live only; null in a backtest (no history). + public Func? SpreadBp { get; init; } + + /// The saved universe of a strategy on a date, live; null means "compute it from the bars". + public Func?>? Members { get; init; } +} /// Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly. public sealed class StrategyParameters @@ -169,8 +231,45 @@ public sealed class StrategyContext( public BarSeries Bars(string symbol) => bars(symbol); public InstrumentSpec? Spec(string symbol) => spec(symbol); + + /// + /// The next session of the market calendar after . Calendars are published in advance, so this + /// is not looking ahead: equity_momentum uses it to find the last session before a new week. + /// + public DateOnly? NextSession { get; init; } + + /// + /// The reference equity of SPEC 9.2: capital entrusted on every broker plus the strategies' results, which does + /// not move when a strategy changes stage. In the backtest of one strategy: its equity divided by its share of + /// the total. Defaults to the strategy's equity. + /// + public decimal ReferenceEquity + { + get => _reference ?? Portfolio.Equity; + init => _reference = value; + } + + private readonly decimal? _reference; + + /// Sessions in a year for this market: 365 for crypto, 252 for stocks. + public int PeriodsPerYear { get; init; } = 365; + + /// Next earnings date of a stock, live and when the calendar has it; null in a backtest (SPEC 8.3). + public Func? NextEarnings { get; init; } + + /// A restriction from the news on the instrument (SPEC 10.5, Phase 7); null in a backtest. + public Func? Restricted { get; init; } + + /// + /// The strategy's equity at each earlier close, up to and including this one: what the risk limits of SPEC 9.2 + /// measure losses and the fall from the high on. + /// + public IReadOnlyList History { get; init; } = []; } +/// The equity at a close and the part of it in positions. +public sealed record EquityMark(DateOnly Day, decimal Equity, decimal Invested); + /// A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else. public interface IStrategy { diff --git a/tests/Anubis.Tests/StrategyTests.cs b/tests/Anubis.Tests/StrategyTests.cs new file mode 100644 index 0000000..ee459df --- /dev/null +++ b/tests/Anubis.Tests/StrategyTests.cs @@ -0,0 +1,562 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +internal static class StrategyData +{ + public static readonly DateOnly Start = new(2024, 1, 1); + + public static InstrumentSpec Coin(string coin) => new(Venues.Okx, coin + "-EUR", coin, AssetClasses.Crypto, "EUR") + { + BaseCurrency = coin, + TickSize = 0.0001m, + LotSize = 0.00000001m, + MinSize = 0.00000001m, + MinNotional = 1m, + Status = "live", + }; + + public static InstrumentSpec Share(string symbol) => new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD") + { + Fractionable = true, + Status = "active", + Exchange = "NASDAQ", + TickSize = 0.01m, + LotSize = 0.000000001m, + MinNotional = 1m, + }; + + /// Bars with the given closes on consecutive days; high and low a fixed distance around the close. + public static List FromCloses(IReadOnlyList closes, DateOnly? from = null, double range = 0, double volume = 10_000) + { + var day = from ?? Start; + return [.. closes.Select((c, i) => new DailyBar(day.AddDays(i), c, c + range, c - range, c, volume))]; + } + + /// Bars on business days (no weekends) from a Monday. + public static List OnBusinessDays(IReadOnlyList bars, DateOnly from) + { + var days = BusinessDays(from, bars.Count); + return [.. bars.Select((b, i) => b with { Day = days[i] })]; + } + + public static List BusinessDays(DateOnly from, int count) + { + var result = new List(count); + for (var d = from; result.Count < count; d = d.AddDays(1)) + { + if (d.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + result.Add(d); + } + } + + return result; + } + + /// A steady rise with a tiny alternating wobble: every period of crypto_trend is on, volatility near 1%. + public static List SteadyRise(int days, double start = 100, double volume = 10_000) => + FromCloses([.. Enumerable.Range(0, days).Select(i => start * Math.Pow(1.001, i) * (1 + (0.0005 * (i % 2))))], volume: volume); + + public static BarSeries Series(IReadOnlyList bars, InstrumentSpec? spec = null) => + new BacktestInstrument(spec ?? Coin("BTC"), bars).SeriesThrough(bars[^1].Day); + + public static BacktestDataset Crypto(params (string Coin, IReadOnlyList Bars)[] coins) => + new(coins.Select(c => new BacktestInstrument(Coin(c.Coin), c.Bars)), "EUR"); +} + +/// Indicators and the three base strategies (issues #38, #39, #40; SPEC 8.1–8.3). +[TestClass] +public sealed class StrategyTests +{ + // ---- Indicators, against values computed by hand ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void IndicatorsGiveTheValuesComputedByHand() + { + var closes = StrategyData.Series(StrategyData.FromCloses([1, 2, 3, 4, 5])); + Assert.AreEqual(4d, Indicators.Sma(closes, 3)); + Assert.IsNull(Indicators.Sma(closes, 6)); + + // True ranges: max(11−9, |11−9|, |9−9|) = 2; max(3, |12−10|, |9−10|) = 3; max(4, |11−11|, |7−11|) = 4. + var bars = StrategyData.Series( + [ + new DailyBar(StrategyData.Start, 9, 10, 8, 9, 1), + new DailyBar(StrategyData.Start.AddDays(1), 10, 11, 9, 10, 1), + new DailyBar(StrategyData.Start.AddDays(2), 11, 12, 9, 11, 1), + new DailyBar(StrategyData.Start.AddDays(3), 9, 11, 7, 8, 1), + ]); + Assert.AreEqual(3d, Indicators.Atr(bars, 3)); + Assert.AreEqual(3.5d, Indicators.Atr(bars, 2)); + + // RSI(2) on 10, 11, 10,5, 12: average gain 0,5 and loss 0,25 on the first two changes; then +1,5 gives + // gain (0,5 + 1,5) / 2 = 1 and loss 0,25 / 2 = 0,125: RS 8, RSI 100 − 100 / 9. + Assert.AreEqual(100 - (100 / 9d), Indicators.Rsi(StrategyData.Series(StrategyData.FromCloses([10, 11, 10.5, 12])), 2)!.Value, 1e-12); + + // 121 / 100 − 1, skipping the last close. + Assert.AreEqual(0.21, Indicators.Momentum(StrategyData.Series(StrategyData.FromCloses([100, 110, 121, 133.1])), 2, 1)!.Value, 1e-12); + + // Returns +10% and −10%: sample standard deviation √0,02, times √365. + Assert.AreEqual(Math.Sqrt(0.02) * Math.Sqrt(365), Indicators.Volatility(StrategyData.Series(StrategyData.FromCloses([100, 110, 99])), 2, 365)!.Value, 1e-12); + } + + // ---- crypto_trend ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void ThePeriodsTurnOnAtANewHighAndOffBelowYesterdaysStop() + { + // Periods 2 and 3, flat bars (high = low = close) so only the closes count. + var settings = new CryptoTrendSettings { Periods = [2, 3], MaxStop = 0.15 }; + var bars = StrategyData.FromCloses([10, 10, 10, 12, 13, 12.4, 12.6]); + bars[6] = bars[6] with { Low = 12.0 }; + var tracker = new TrendTracker(); + + // Day 3, close 12: both periods beat their previous highs (10); stops at the middle of the last N closes, 11. + tracker.Advance(StrategyData.Series(bars[..4]), settings); + CollectionAssert.AreEqual(new[] { true, true }, tracker.Active.ToArray()); + Assert.AreEqual(1d, tracker.Ensemble); + Assert.AreEqual(11d, tracker.ServerStop); + + // Day 4, close 13: stops rise to 12,5 and 11,5; the server stop is the lowest, 11,5. + tracker.Advance(StrategyData.Series(bars[..5]), settings); + Assert.AreEqual(11.5d, tracker.ServerStop); + + // Day 5, close 12,4: below the 2-day stop of yesterday (12,5), so that period turns off; the 3-day one stays, + // its stop rising to the middle of 12, 13, 12,4 = 12,5. e = 0,5. + tracker.Advance(StrategyData.Series(bars[..6]), settings); + CollectionAssert.AreEqual(new[] { false, true }, tracker.Active.ToArray()); + Assert.AreEqual(0.5d, tracker.Ensemble); + Assert.AreEqual(12.5d, tracker.ServerStop); + + // Day 6: the low (12) touches the server stop during the day. Every period goes back to 0, and the close of + // 12,6 is not a new high for either: no stop, no position. + tracker.Advance(StrategyData.Series(bars), settings); + CollectionAssert.AreEqual(new[] { false, false }, tracker.Active.ToArray()); + Assert.AreEqual(0d, tracker.Ensemble); + Assert.IsNull(tracker.ServerStop); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheServerStopRisesStaysWithin15PercentAndFallsOnlyWhenAPeriodTurnsOn() + { + var tracker = new TrendTracker(); + + // Never more than 15% below the close: the middle of 10 and 20 is 15, the cap 17. + tracker.Advance(StrategyData.Series(StrategyData.FromCloses([10, 10, 20])), new CryptoTrendSettings { Periods = [2] }); + Assert.AreEqual(17d, tracker.ServerStop); + + // With a loose cap: the 2-day period alone lifts the stop to 11, 13, 15; on day 5 the 5-day period turns on + // with its stop at the middle of 10…17 = 13,5, and the server stop comes down to it. + var loose = new CryptoTrendSettings { Periods = [2, 5], MaxStop = 0.5 }; + var bars = StrategyData.FromCloses([10, 10, 12, 14, 16, 17]); + var stops = new List(); + for (var n = 3; n <= bars.Count; n++) + { + stops.Add(new TrendTracker().Advance(StrategyData.Series(bars[..n]), loose).ServerStop); + } + + CollectionAssert.AreEqual(new double?[] { 11, 13, 15, 13.5 }, stops); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void WalkingTheBarsOnceOrDayByDayGivesTheSameState() + { + var bars = BacktestData.Walk(700, 11, start: 30_000, volatility: 0.04); + var settings = new CryptoTrendSettings(); + var once = new TrendTracker().Advance(StrategyData.Series(bars), settings); + var stepwise = new TrendTracker(); + for (var n = 1; n <= bars.Count; n++) + { + stepwise.Advance(StrategyData.Series([.. bars.Take(n)]), settings); + } + + Assert.AreEqual(once.Ensemble, stepwise.Ensemble); + Assert.AreEqual(once.ServerStop, stepwise.ServerStop); + CollectionAssert.AreEqual(once.Active.ToArray(), stepwise.Active.ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void WeightsFollowTheCapsThenShrinkTogether() + { + // Six coins in a steady rise: e = 1 and a volatility near 1%, so every raw weight hits its cap. 35% for BTC + // and ETH, 20% for the others: 150% in all, so everything shrinks by 1,5. + var coins = new[] { "BTC", "ETH", "SOL", "ADA", "XRP", "DOT" }; + var data = StrategyData.Crypto([.. coins.Select(c => (c, (IReadOnlyList)StrategyData.SteadyRise(450)))]); + var last = data.Sessions[^1]; + var decision = BacktestEngine.DecideOnce(new CryptoTrend(), data, PortfolioState.OnlyCash(10_000m), last); + var weights = decision.Proposed.ToDictionary(i => i.Symbol, i => i.TargetWeight); + Assert.AreEqual(0.233333m, weights["BTC-EUR"]); + Assert.AreEqual(0.233333m, weights["ETH-EUR"]); + foreach (var other in new[] { "SOL-EUR", "ADA-EUR", "XRP-EUR", "DOT-EUR" }) + { + Assert.AreEqual(0.133333m, weights[other]); + } + + Assert.IsTrue(decision.Proposed.All(i => i.Reason == CryptoTrend.Reasons.Entry && i.Stop > 0m)); + + // Alone, bitcoin stops at its cap. + var alone = BacktestEngine.DecideOnce(new CryptoTrend(), StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450))), PortfolioState.OnlyCash(10_000m), last); + Assert.AreEqual(0.35m, alone.Proposed.Single().TargetWeight); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void APositionIsResizedOnlyBeyondTheThresholds() + { + var bars = StrategyData.SteadyRise(450); + var data = StrategyData.Crypto(("BTC", bars)); + var last = data.Sessions[^1]; + var close = Math.Round((decimal)bars[^1].Close, 8); + + IReadOnlyList At(decimal weight) + { + var quantity = weight * 10_000m / close; + var state = new PortfolioState(10_000m - (quantity * close), new Dictionary { ["BTC-EUR"] = new(quantity, close, null, StrategyData.Start) }); + return BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed; + } + + // Target 35%. At 30% the gap (5 points) is within 20% of the target (7 points): only the stop moves. + var near = At(0.30m).Single(); + Assert.IsNull(near.TargetWeight); + Assert.AreEqual(CryptoTrend.Reasons.StopMoved, near.Reason); + + // At 25% the gap (10 points) is beyond both thresholds: back to 35%. + var far = At(0.25m).Single(); + Assert.AreEqual(0.35m, far.TargetWeight); + Assert.AreEqual(CryptoTrend.Reasons.Increase, far.Reason); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheUniverseIsTheTopTenOnTheFirstOfTheMonthWithoutStablecoinsOrYoungCoins() + { + // Twelve coins with growing traded value, a stablecoin with the largest of all, a coin listed 200 days ago. + var instruments = new List(); + for (var k = 1; k <= 12; k++) + { + instruments.Add(new BacktestInstrument(StrategyData.Coin("C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)), StrategyData.SteadyRise(450, volume: 10_000 * k))); + } + + instruments.Add(new BacktestInstrument(StrategyData.Coin("USDC"), StrategyData.FromCloses([.. Enumerable.Repeat(1d, 450)], volume: 1e12))); + instruments.Add(new BacktestInstrument(StrategyData.Coin("NEW"), StrategyData.FromCloses([.. Enumerable.Repeat(100d, 200)], from: StrategyData.Start.AddDays(250), volume: 1e9))); + var data = new BacktestDataset(instruments, "EUR"); + var strategy = new CryptoTrend(); + var day = new DateOnly(2025, 3, 20); + UniverseContext Context(DateOnly d) => new(d, [.. data.Instruments.Select(i => i.Symbol)]) + { + Bars = s => data[s]!.SeriesThrough(d), + Spec = s => data[s]?.Spec, + }; + + var universe = strategy.Universe(Context(day)); + CollectionAssert.AreEqual(Enumerable.Range(3, 10).Reverse().Select(k => "C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + "-EUR").ToList(), universe.ToList()); + + // Live, the spread is known: one too wide is out, and the 11th by value comes in. + var live = new CryptoTrend().Universe(Context(day) with { SpreadBp = s => s == "C12-EUR" ? 25 : 5 }); + CollectionAssert.DoesNotContain(live.ToList(), "C12-EUR"); + CollectionAssert.Contains(live.ToList(), "C02-EUR"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void ACoinThatLeftTheUniverseIsManagedButNeverBought() + { + // A young coin (not in the universe) held at 10% in a steady rise: its target would be its cap, 20%. + var data = StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450)), ("NEW", StrategyData.SteadyRise(450).GetRange(150, 300))); + var last = data.Sessions[^1]; + var close = Math.Round((decimal)data["NEW-EUR"]!.Bars[^1].Close, 8); + var quantity = 1_000m / close; + var state = new PortfolioState(9_000m, new Dictionary { ["NEW-EUR"] = new(quantity, close, null, last.AddDays(-10)) }); + var intents = BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed; + var coin = intents.Single(i => i.Symbol == "NEW-EUR"); + Assert.IsNull(coin.TargetWeight, "No purchase for a coin out of the universe."); + Assert.IsNotNull(coin.Stop); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CryptoTrendDecidesOnTheMidnightUtcClose() + { + // The day's bar opens and closes at 00:00 UTC (trap 23): the decision comes at the close, at midnight. + var times = new List(); + var data = StrategyData.Crypto(("BTC", BacktestData.Walk(30, 3, from: StrategyData.Start))); + BacktestEngine.Run(new Recording(new CryptoTrend(), times), data); + Assert.HasCount(30, times); + for (var i = 0; i < times.Count; i++) + { + Assert.AreEqual(new DateTimeOffset(StrategyData.Start.AddDays(i + 1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), times[i]); + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CryptoTrendDoesNotLookAhead() + { + var data = StrategyData.Crypto( + ("BTC", BacktestData.Walk(900, 21, start: 30_000, drift: 0.001, volatility: 0.035, from: StrategyData.Start)), + ("ETH", BacktestData.Walk(900, 22, start: 2_000, drift: 0.0008, volatility: 0.045, from: StrategyData.Start)), + ("SOL", BacktestData.Walk(900, 23, start: 50, drift: 0.0005, volatility: 0.06, from: StrategyData.Start))); + var result = LookAheadCheck.Run(_ => new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data); + Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3))); + var run = BacktestEngine.Run(new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data); + Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades."); + } + + // ---- equity_momentum ---- + + private static readonly DateOnly Monday = new(2022, 1, 3); + + /// Thirty stocks with different drifts, SPY as data only, on business days. + private static BacktestDataset Stocks(int sessions, double spyDrift, int count = 30, ulong seed = 100) + { + var instruments = new List(); + for (var k = 0; k < count; k++) + { + var bars = BacktestData.Walk(sessions, seed + (ulong)k, start: 50 + k, drift: 0.0002 * (k - 10), volatility: 0.015 + (0.0005 * k)); + instruments.Add(new BacktestInstrument(StrategyData.Share("S" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)), + StrategyData.OnBusinessDays([.. bars.Select(b => b with { Volume = 100_000 })], Monday))); + } + + var spy = BacktestData.Walk(sessions, seed + 999, start: 400, drift: spyDrift, volatility: 0.008); + instruments.Add(new BacktestInstrument(StrategyData.Share("SPY") with { IsFund = true }, StrategyData.OnBusinessDays([.. spy], Monday))); + return new BacktestDataset(instruments, "USD", dataOnly: ["SPY"]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheWeeklyReviewIsTheLastCloseBeforeANewWeek() + { + StrategyContext At(DateOnly day, DateOnly? next) => new(day, default, [], new PortfolioView(0m, 0m, new Dictionary()), _ => BarSeries.Empty, _ => null) + { + NextSession = next, + }; + + var friday = new DateOnly(2026, 4, 3); + Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(3)))); + Assert.IsFalse(EquityMomentum.IsReview(At(friday.AddDays(-1), friday))); + // Good Friday closed: Thursday is the last session of the week. + Assert.IsTrue(EquityMomentum.IsReview(At(friday.AddDays(-1), friday.AddDays(3)))); + // A Monday holiday: the review on Friday, orders on Tuesday. + Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(4)))); + Assert.IsFalse(EquityMomentum.IsReview(At(friday, null))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MomentumBuysOnTheFirstSessionOfTheWeekOnlyWhileTheMarketRises() + { + var rising = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001)); + var buys = rising.Fills.Where(f => f.Side == OrderSide.Buy && f.Reason == EquityMomentum.Reasons.Entry).ToList(); + Assert.IsNotEmpty(buys); + // Every purchase at the open of the first session of its week (here always a Monday). + Assert.IsTrue(buys.All(f => f.Day.DayOfWeek == DayOfWeek.Monday), string.Join(", ", buys.Select(f => f.Day))); + Assert.IsFalse(rising.Fills.Any(f => f.Symbol == "SPY"), "SPY is data, never an instrument."); + + // At most 12 positions, no target above the 15% cap. + var entries = rising.Decisions.SelectMany(d => d.Proposed).Where(i => i.TargetWeight > 0m).ToList(); + Assert.IsTrue(entries.All(i => i.TargetWeight <= 0.15m)); + Assert.IsTrue(rising.Decisions.All(d => d.Proposed.Count(i => i.Reason == EquityMomentum.Reasons.Entry) <= 12)); + + // SPY below its 200-day average: no purchase at all. + var falling = BacktestEngine.Run(new EquityMomentum(), Stocks(520, -0.002)); + Assert.IsFalse(falling.Fills.Any(f => f.Side == OrderSide.Buy)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MomentumStopsOnlyRise() + { + var run = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001)); + var stops = run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == EquityMomentum.Reasons.StopMoved).Select(i => (d.Day, i.Symbol, Stop: i.Stop!.Value))).ToList(); + Assert.IsNotEmpty(stops); + foreach (var group in stops.GroupBy(s => s.Symbol)) + { + var list = group.OrderBy(s => s.Day).ToList(); + for (var i = 1; i < list.Count; i++) + { + // A new holding period may start lower; within one, every move is up. + var exited = run.Fills.Any(f => f.Symbol == group.Key && f.Side == OrderSide.Sell && f.Day > list[i - 1].Day && f.Day <= list[i].Day); + Assert.IsTrue(exited || list[i].Stop > list[i - 1].Stop, $"{group.Key} {list[i - 1]} → {list[i]}"); + } + } + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MomentumSellsAStockBelowItsAverageAtTheReview() + { + var data = Stocks(520, 0.001); + var friday = data.Sessions.Last(d => d.DayOfWeek == DayOfWeek.Friday && d < data.Sessions[^1]); + // S00 drifts down: it is below its 100-session average. + var bars = data["S00"]!.SeriesThrough(friday); + Assert.IsLessThan(Indicators.Sma(bars, 100)!.Value, bars.Close(bars.Count - 1)); + var close = Math.Round((decimal)bars.Close(bars.Count - 1), 2); + var state = new PortfolioState(9_000m, new Dictionary { ["S00"] = new(1_000m / close, close, null, friday.AddDays(-30)) }); + var intent = BacktestEngine.DecideOnce(new EquityMomentum(), data, state, friday).Proposed.Single(i => i.Symbol == "S00"); + Assert.AreEqual(0m, intent.TargetWeight); + Assert.IsTrue(intent.Reason is EquityMomentum.Reasons.ExitTrend or EquityMomentum.Reasons.ExitRank); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EquityMomentumDoesNotLookAhead() + { + var data = Stocks(520, 0.001); + var result = LookAheadCheck.Run(_ => new EquityMomentum(), data); + Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3))); + } + + // ---- equity_meanrev ---- + + /// + /// 320 sessions rising by 0,1 a day from 72,3, then three falls of 1: every true range is 2 (high and low one away + /// from the close), so ATR(14) = 2 and the stop distance 2,5 × 2 = 5. RSI(2) ends near 1, the close (101) is below + /// its 5-session average and above its 200-session one. + /// + private static List Dip(double shift = 0) + { + var closes = Enumerable.Range(0, 317).Select(i => Math.Round(72.3 + (0.1 * i), 1) + shift).Concat([103 + shift, 102 + shift, 101 + shift]).ToList(); + return StrategyData.OnBusinessDays(StrategyData.FromCloses(closes, range: 1, volume: 100_000), Monday); + } + + private static BacktestDataset Shares(params (string Symbol, List Bars)[] stocks) => + new(stocks.Select(s => new BacktestInstrument(StrategyData.Share(s.Symbol), s.Bars)), "USD"); + + [TestMethod] + [TestCategory(Category.Unit)] + public void MeanrevSizesForARiskOfFourThousandthsCappedAtThirtyPercent() + { + var data = Shares(("AAA", Dip())); + var last = data.Sessions[^1]; + + // Reference equity = the strategy's 10.000 $: risk 40 $ over a 5 $ distance = 8 shares at 101 = 808 $, 8,08%. + var entry = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last).Proposed.Single(); + Assert.AreEqual(EquityMeanrev.Reasons.Entry, entry.Reason); + Assert.AreEqual(0.0808m, entry.TargetWeight); + Assert.AreEqual(5m, entry.StopOffset); + + // With the default share (15% of the bot) the reference is 66.666 $: 53,3 shares, more than the 30% cap. + var capped = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last, new BacktestOptions { ReferenceShare = 0.15m }).Proposed.Single(); + Assert.AreEqual(0.3m, capped.TargetWeight); + + // A position bought today holds 9.500 $, 500 $ stay free: not enough for the candidate (808 $), dropped. + var both = Shares(("AAA", Dip()), ("BBB", Dip())); + var poor = new PortfolioState(500m, new Dictionary { ["BBB"] = new(9_500m / 101m, 101m, 96m, last) }); + Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), both, poor, last).Proposed.Any(i => i.Symbol == "AAA")); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MeanrevTakesAtMostThreeWithTheLowestRsi() + { + // Five dips; a deeper last fall gives a lower RSI. The three deepest are chosen. + var stocks = Enumerable.Range(0, 5).Select(k => + { + var bars = Dip(k); + bars[^1] = bars[^1] with { Close = bars[^1].Close - (0.1 * k), Low = bars[^1].Low - (0.1 * k) }; + return ("D" + k.ToString(System.Globalization.CultureInfo.InvariantCulture), bars); + }).ToArray(); + var data = Shares(stocks); + var intents = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(100_000m), data.Sessions[^1]).Proposed; + CollectionAssert.AreEqual(new[] { "D4", "D3", "D2" }, intents.Select(i => i.Symbol).ToArray()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void MeanrevExitsAtTheCloseOnTheRules() + { + var bars = Dip(); + var data = Shares(("AAA", bars)); + var last = data.Sessions[^1]; + Intent Exit(DateOnly entered, DateOnly day) + { + var state = new PortfolioState(9_000m, new Dictionary { ["AAA"] = new(10m, 100m, 95m, entered) }); + return BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, day).Proposed.Single(i => i.Symbol == "AAA"); + } + + // In the rise the close is above its 5-session average: out at the close. + var rising = Exit(data.Sessions[^10], data.Sessions[^5]); + Assert.AreEqual(EquityMeanrev.Reasons.ExitAverage, rising.Reason); + Assert.IsTrue(rising.AtClose); + + // In the dip none of the price rules says exit; held since the fifth session from the end: time is up. + var timed = Exit(data.Sessions[^5], last); + Assert.AreEqual(EquityMeanrev.Reasons.ExitTime, timed.Reason); + var state = new PortfolioState(9_000m, new Dictionary { ["AAA"] = new(10m, 100m, 95m, data.Sessions[^4]) }); + Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, last).Proposed.Any(i => i.Symbol == "AAA"), "Four sessions: still held."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void EquityMeanrevDoesNotLookAhead() + { + var instruments = Enumerable.Range(0, 12).Select(k => new BacktestInstrument(StrategyData.Share("M" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)), + StrategyData.OnBusinessDays([.. BacktestData.Walk(520, 300 + (ulong)k, start: 60 + k, drift: 0.0006, volatility: 0.02).Select(b => b with { Volume = 100_000 })], Monday))); + var data = new BacktestDataset(instruments, "USD"); + var result = LookAheadCheck.Run(_ => new EquityMeanrev(), data); + Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3))); + var run = BacktestEngine.Run(new EquityMeanrev(), data); + Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades."); + } + + // ---- Engine features the strategies need ---- + + [TestMethod] + [TestCategory(Category.Unit)] + public void AnExitAtTheCloseIsFilledAtThatCloseAndAStopOffsetFollowsThePriceObtained() + { + var d1 = BacktestData.D1; + var bars = new List + { + new(d1, 100, 101, 99, 100, 1000), + new(d1.AddDays(1), 100, 102, 99, 101, 1000), + new(d1.AddDays(2), 101, 103, 100, 102, 1000), + new(d1.AddDays(3), 102, 103, 90, 95, 1000), + }; + var script = new ScriptedStrategy(new Dictionary> + { + [d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }], + [d1.AddDays(2)] = [new Intent("BTC-EUR", 0m, "exit") { AtClose = true }], + }); + var run = BacktestEngine.Run(script, BacktestData.One(BacktestData.Btc(), bars)); + // Bought at the open of day 2 (100 + 5 bp → 100,1); sold at the close of day 3 itself, 102 − 5 bp → 101,9. + Assert.AreEqual(d1.AddDays(1), run.Fills[0].Day); + Assert.AreEqual(d1.AddDays(2), run.Fills[1].Day); + Assert.AreEqual(101.9m, run.Fills[1].Price); + Assert.AreEqual("exit", run.Fills[1].Reason); + + // Without the exit, the stop sits 5 below the price obtained (95,1) and the low of day 4 (90) takes it. + var held = BacktestEngine.Run(new ScriptedStrategy(new Dictionary> { [d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }] }), + BacktestData.One(BacktestData.Btc(), bars)); + var stop = held.Fills.Single(f => f.Side == OrderSide.Sell); + Assert.AreEqual(BacktestReasons.Stop, stop.Reason); + Assert.AreEqual(d1.AddDays(3), stop.Day); + Assert.AreEqual(95.0m, stop.Price); + } + + /// Records the moment each decision is taken. + private sealed class Recording(IStrategy inner, List times) : IStrategy + { + public string Id => inner.Id; + + public string Version => inner.Version; + + public IReadOnlyList Schedule() => inner.Schedule(); + + public IReadOnlyList Universe(UniverseContext context) => inner.Universe(context); + + public IReadOnlyList Decide(StrategyContext context) + { + times.Add(context.Now); + return inner.Decide(context); + } + } +} -- 2.54.1 From 8def84e12278c9fe0a9dc3bdeef05b7ad7d2fbfe Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 15:22:35 +0100 Subject: [PATCH 2/8] 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); + } +} -- 2.54.1 From 7041533ce2b5534e97b5e5cca32d77c035e7ed28 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 16:13:23 +0100 Subject: [PATCH 3/8] Add the honest backtests of the base strategies (refs #44) crypto_trend now has a backtest report and an outcome file, computed by "anubis backtest base" on the Binance daily archives from 2019 to October 2026. Prices are converted from USDT to euro with the ECB rate of the day, and delisted coins stay in the universe, so survivors do not flatter the result. The protocol runs the broad universe and BTC, ETH and SOL, with costs doubled and tripled and buy and hold beside. Both universes must pass. The outcome is "not passed": the broad universe falls 29.1% (limit 25%) and the narrow one has a probability of overfitting of 0.84 (limit 0.40). The strategy therefore stays in observation. The stock strategies wait for the Alpaca keys and stay in observation too. The bot reads the outcome files at every start. Trials now read 450 days of history before their start, only so the indicators and the 400-day listing age are ready on the first day. Before this, 2019 was spent warming up and BTC and ETH could not be chosen until 2020. A daily series also stops at a hole longer than a week, so the LUNA relaunched in 2022 is not mistaken for the coin that collapsed. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 1 + deploy/docker/Dockerfile | 2 + docs/backtests/crypto_trend.md | 256 +++++++++++++ docs/backtests/crypto_trend.outcome.json | 376 ++++++++++++++++++++ docs/backtests/equity_meanrev.md | 10 + docs/backtests/equity_meanrev.outcome.json | 9 + docs/backtests/equity_momentum.md | 10 + docs/backtests/equity_momentum.outcome.json | 9 + src/Anubis.Server/BacktestCommand.cs | 142 ++++++++ src/Anubis.Server/Program.cs | 6 + src/Anubis/Anubis.csproj | 2 + src/Anubis/Backtest/Laboratory.cs | 50 ++- src/Anubis/Backtest/Protocol.cs | 376 ++++++++++++++++++++ src/Anubis/Backtest/ProtocolReport.cs | 206 +++++++++++ src/Anubis/Backtest/Report.cs | 16 +- src/Anubis/Backtest/Trials.cs | 15 +- src/Anubis/Trading/TradingService.cs | 16 + tests/Anubis.Tests/LaboratoryTests.cs | 3 +- tests/Anubis.Tests/ProtocolTests.cs | 216 +++++++++++ 19 files changed, 1696 insertions(+), 25 deletions(-) create mode 100644 docs/backtests/crypto_trend.md create mode 100644 docs/backtests/crypto_trend.outcome.json create mode 100644 docs/backtests/equity_meanrev.md create mode 100644 docs/backtests/equity_meanrev.outcome.json create mode 100644 docs/backtests/equity_momentum.md create mode 100644 docs/backtests/equity_momentum.outcome.json create mode 100644 src/Anubis.Server/BacktestCommand.cs create mode 100644 src/Anubis/Backtest/Protocol.cs create mode 100644 src/Anubis/Backtest/ProtocolReport.cs create mode 100644 tests/Anubis.Tests/ProtocolTests.cs diff --git a/.dockerignore b/.dockerignore index cf448c2..baa4069 100644 --- a/.dockerignore +++ b/.dockerignore @@ -7,6 +7,7 @@ artifacts/ TestResults/ docs/ !docs/design/logo/ +!docs/backtests/*.outcome.json **/*.md .env .env.* diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index d0a17b6..f1bc33a 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -11,6 +11,8 @@ COPY src/Anubis/ src/Anubis/ COPY src/Anubis.Server/ src/Anubis.Server/ # The logo is embedded from docs/design/logo, its only source (ADR 0005). COPY docs/design/logo/ docs/design/logo/ +# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through. +COPY docs/backtests/ docs/backtests/ RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app FROM mcr.microsoft.com/dotnet/aspnet:10.0 diff --git a/docs/backtests/crypto_trend.md b/docs/backtests/crypto_trend.md new file mode 100644 index 0000000..94d925e --- /dev/null +++ b/docs/backtests/crypto_trend.md @@ -0,0 +1,256 @@ +# Backtest di `crypto_trend` (Trend crypto) + +**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 29,1%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,839, serve ≤ 0,40. Resta in osservazione. + +Calcolato il 2026-11-11 con la versione 1 della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo. + +Per rifarlo: `anubis backtest base --to 2026-10-31`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/crypto_trend.outcome.json`. + +## Dati + +- Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso. +- Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno (7133 giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1). +- 47 coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni. +- Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo. +- Senza archivi nel periodo, quindi non usate: BCCEUR, VENEUR. + +## Riepilogo + +| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito | +|---|---|---:|---:|---:|---:|---:|---| +| Universo ampio | `coin_vol=10;max_stop=20` | 11,2% | −29,1% | 8.053,52 € | 0,960 | 0,143 | non superata | +| BTC, ETH e SOL | `coin_vol=20;max_stop=15` | 13,8% | −17,3% | 12.845,05 € | 0,971 | 0,839 | non superata | + +## Cosa conserva il bot + +- Calo massimo del backtest: −29,1%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3). +- Scostamento di prezzo previsto: 11,91 punti base; costo stimato di andata e ritorno 0,64%. +- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −4,9% dopo 30 giorni, −7,6% dopo 90, −13,2% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro. + +## Universo ampio + +Le 10 monete con più scambi, scelte ogni mese tra 47 coppie (anche quelle poi chiuse). + +Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `737ca3a07b9c`, dei dati `8486b858321b`. + +| | Strategia | Comprare e tenere | +|---|---:|---:| +| Risultato netto | 12.984,56 € | 82.750,41 € | +| Rendimento totale | 129,8% | 827,5% | +| Rendimento annuo | 11,2% | 32,9% | +| Volatilità annua | 14,0% | 74,2% | +| Calo massimo | −29,1% (11/2021 → 10/2023) | −85,8% | +| Sharpe annuo | 0,83 | 0,76 | +| Operazioni chiuse | 1826 | 0 | +| Operazioni in guadagno | 14,1% | — | +| Rapporto guadagni/perdite | 1,51 | — | +| Commissioni pagate | 2.975,10 € | 20,00 € | +| Tempo investito | 16,9% | 92,0% | + +**Per anno** + +| Anno | Strategia | Comprare e tenere | +|---|---:|---:| +| 2019 | 17,8% | 4,4% | +| 2020 | 34,9% | 103,9% | +| 2021 | 24,9% | 1.603,5% | +| 2022 | −10,5% | −79,9% | +| 2023 | 14,6% | 56,4% | +| 2024 | 26,8% | 34,5% | +| 2025 | −8,8% | −33,1% | +| 2026 | −2,4% | −9,4% | + +**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme) + +| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni | +|---|---:|---:|---:|---:|---:| +| ×1 | 12.984,56 € | 129,8% | 0,83 | −29,1% | 2.975,10 € | +| ×2 | 8.053,52 € | 80,5% | 0,61 | −33,9% | 5.005,99 € | +| ×3 | 4.349,38 € | 43,5% | 0,40 | −36,0% | 6.495,29 € | + +**Convalide** + +- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 67,6%, Sharpe annuo 0,65. +- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,83, peggiore 0,83, percorsi positivi 100,0%. +- Deflated Sharpe Ratio 0,96, contando 9 varianti provate in tutto. +- Probabilità di sovra-adattamento (PBO) 0,14, su 12870 combinazioni di 9 varianti. +- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate. + +**Soglie** + +| Controllo | Valore | Soglia | Esito | +|---|---:|---:|---| +| Risultato netto con costi doppi | 8.053,52 € | > 0,00 € | superato | +| Deflated Sharpe Ratio | 0,960 | ≥ 0,9 | superato | +| Probabilità di sovra-adattamento (PBO) | 0,143 | ≤ 0,4 | superato | +| Calo massimo | 29,1% | ≤ 25% | **non superato** | +| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato | + +**Varianti della griglia** + +| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni | +|---|---:|---:|---:|---:|---:| +| `coin_vol=10;max_stop=10` | 0,58 | 0,58 | 6.383,12 € | −22,9% | 2243 | +| `coin_vol=10;max_stop=15` | 0,83 | 0,71 | 12.327,24 € | −24,6% | 1994 | +| `coin_vol=10;max_stop=20` (scelta) | 0,83 | 0,78 | 12.984,56 € | −29,1% | 1826 | +| `coin_vol=15;max_stop=10` | 0,53 | 0,53 | 6.035,84 € | −25,0% | 2257 | +| `coin_vol=15;max_stop=15` | 0,74 | 0,67 | 10.656,85 € | −29,4% | 2002 | +| `coin_vol=15;max_stop=20` | 0,74 | 0,74 | 11.167,92 € | −30,8% | 1837 | +| `coin_vol=20;max_stop=10` | 0,44 | 0,44 | 4.826,58 € | −25,0% | 2258 | +| `coin_vol=20;max_stop=15` | 0,65 | 0,63 | 8.943,30 € | −30,5% | 2008 | +| `coin_vol=20;max_stop=20` | 0,66 | 0,66 | 9.921,78 € | −31,1% | 1838 | + +**Interventi di correttivi e rischio sulla variante scelta** + +| Motivo | Volte | +|---|---:| +| `residue_written_off` | 1823 | +| `below_min_notional` | 387 | + +**Strumenti** + +| Coppia | Prima barra | Ultima barra | Barre | +|---|---|---|---:| +| ADAEUR | 2018-04-17 | 2026-10-31 | 3120 | +| APEEUR | 2022-03-17 | 2026-10-31 | 1690 | +| ARBEUR | 2023-03-23 | 2026-10-31 | 1319 | +| ATOMEUR | 2019-04-29 | 2026-10-31 | 2743 | +| AVAXEUR | 2020-09-22 | 2026-10-31 | 2231 | +| BCHABCEUR | 2018-11-16 | 2019-11-28 | 378 | +| BCHEUR | 2019-11-28 | 2026-10-31 | 2530 | +| BCHSVEUR | 2018-11-16 | 2019-04-22 | 158 | +| BNBEUR | 2017-11-06 | 2026-10-31 | 3282 | +| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 | +| DASHEUR | 2019-03-28 | 2026-10-31 | 2775 | +| DOGEEUR | 2019-07-05 | 2026-10-31 | 2676 | +| DOTEUR | 2020-08-18 | 2026-10-31 | 2266 | +| EOSEUR | 2018-05-28 | 2025-05-26 | 2556 | +| ETCEUR | 2018-06-12 | 2026-10-31 | 3064 | +| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 | +| FILEUR | 2020-10-15 | 2026-10-31 | 2208 | +| FTTEUR | 2019-12-20 | 2022-11-15 | 1062 | +| GMTEUR | 2022-03-09 | 2026-10-31 | 1698 | +| ICXEUR | 2018-06-13 | 2026-09-03 | 3005 | +| IOTAEUR | 2018-05-31 | 2026-10-31 | 3076 | +| LINKEUR | 2019-01-16 | 2026-10-31 | 2846 | +| LTCEUR | 2017-12-13 | 2026-10-31 | 3245 | +| LUNAEUR | 2020-08-21 | 2022-05-13 | 631 | +| MATICEUR | 2019-04-26 | 2024-09-10 | 1965 | +| NEAREUR | 2020-10-14 | 2026-10-31 | 2209 | +| NEOEUR | 2017-11-20 | 2026-10-31 | 3268 | +| ONTEUR | 2018-06-08 | 2026-10-31 | 3068 | +| OPEUR | 2022-06-01 | 2026-10-31 | 1614 | +| ORDIEUR | 2023-11-07 | 2026-10-31 | 1090 | +| PEPEEUR | 2023-05-05 | 2026-10-31 | 1276 | +| POLEUR | 2024-09-13 | 2026-10-31 | 779 | +| QTUMEUR | 2018-03-19 | 2026-10-31 | 3149 | +| SANDEUR | 2020-08-14 | 2026-10-31 | 2270 | +| SHIBEUR | 2021-05-10 | 2026-10-31 | 2001 | +| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 | +| SUIEUR | 2023-05-03 | 2026-10-31 | 1278 | +| TONEUR | 2024-08-08 | 2026-06-30 | 692 | +| TRUMPEUR | 2025-01-19 | 2026-10-31 | 651 | +| TRXEUR | 2018-06-11 | 2026-10-31 | 3065 | +| UNIEUR | 2020-09-17 | 2026-10-31 | 2236 | +| VETEUR | 2018-07-25 | 2026-10-31 | 3021 | +| WIFEUR | 2024-03-05 | 2026-10-31 | 971 | +| XLMEUR | 2018-05-31 | 2026-10-31 | 3076 | +| XMREUR | 2019-03-15 | 2024-02-20 | 1804 | +| XRPEUR | 2018-05-04 | 2026-10-31 | 3103 | +| ZECEUR | 2019-03-21 | 2026-10-31 | 2782 | + +## BTC, ETH e SOL + +Solo le tre coppie in euro con la liquidità migliore. + +Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=15` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `3ba7de18ca85`, dei dati `f8e752dabf31`. + +| | Strategia | Comprare e tenere | +|---|---:|---:| +| Risultato netto | 17.515,31 € | 215.787,99 € | +| Rendimento totale | 175,2% | 2.157,9% | +| Rendimento annuo | 13,8% | 48,9% | +| Volatilità annua | 12,8% | 71,7% | +| Calo massimo | −17,3% (11/2021 → 10/2023) | −86,7% | +| Sharpe annuo | 1,07 | 0,92 | +| Operazioni chiuse | 452 | 0 | +| Operazioni in guadagno | 15,7% | — | +| Rapporto guadagni/perdite | 2,29 | — | +| Commissioni pagate | 2.282,94 € | 20,00 € | +| Tempo investito | 14,9% | 95,2% | + +**Per anno** + +| Anno | Strategia | Comprare e tenere | +|---|---:|---:| +| 2019 | 15,0% | 28,6% | +| 2020 | 30,5% | 221,5% | +| 2021 | 20,9% | 643,3% | +| 2022 | −7,4% | −81,4% | +| 2023 | 29,4% | 256,5% | +| 2024 | 22,8% | 93,3% | +| 2025 | −0,3% | −31,6% | +| 2026 | 3,5% | −16,1% | + +**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme) + +| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni | +|---|---:|---:|---:|---:|---:| +| ×1 | 17.515,31 € | 175,2% | 1,07 | −17,3% | 2.282,94 € | +| ×2 | 12.845,05 € | 128,5% | 0,89 | −20,9% | 4.070,32 € | +| ×3 | 9.959,70 € | 99,6% | 0,75 | −22,7% | 5.605,48 € | + +**Convalide** + +- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 90,3%, Sharpe annuo 0,91. +- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 1,00, peggiore 0,94, percorsi positivi 100,0%. +- Deflated Sharpe Ratio 0,97, contando 18 varianti provate in tutto. +- Probabilità di sovra-adattamento (PBO) 0,84, su 12870 combinazioni di 9 varianti. +- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate. + +**Soglie** + +| Controllo | Valore | Soglia | Esito | +|---|---:|---:|---| +| Risultato netto con costi doppi | 12.845,05 € | > 0,00 € | superato | +| Deflated Sharpe Ratio | 0,971 | ≥ 0,9 | superato | +| Probabilità di sovra-adattamento (PBO) | 0,839 | ≤ 0,4 | **non superato** | +| Calo massimo | 17,3% | ≤ 25% | superato | +| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato | + +**Varianti della griglia** + +| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni | +|---|---:|---:|---:|---:|---:| +| `coin_vol=10;max_stop=10` | 1,01 | 1,00 | 9.436,53 € | −10,9% | 532 | +| `coin_vol=10;max_stop=15` | 0,94 | 0,94 | 9.790,38 € | −13,0% | 452 | +| `coin_vol=10;max_stop=20` | 1,05 | 1,01 | 12.078,19 € | −13,0% | 388 | +| `coin_vol=15;max_stop=10` | 1,04 | 1,03 | 13.029,82 € | −13,3% | 532 | +| `coin_vol=15;max_stop=15` | 1,01 | 1,01 | 14.386,02 € | −15,8% | 452 | +| `coin_vol=15;max_stop=20` | 1,05 | 1,03 | 15.995,77 € | −15,0% | 388 | +| `coin_vol=20;max_stop=10` | 1,09 | 1,05 | 15.920,52 € | −13,9% | 532 | +| `coin_vol=20;max_stop=15` (scelta) | 1,07 | 1,06 | 17.515,31 € | −17,3% | 452 | +| `coin_vol=20;max_stop=20` | 1,08 | 1,05 | 18.543,32 € | −15,5% | 388 | + +**Interventi di correttivi e rischio sulla variante scelta** + +| Motivo | Volte | +|---|---:| +| `residue_written_off` | 450 | +| `below_min_notional` | 89 | + +**Strumenti** + +| Coppia | Prima barra | Ultima barra | Barre | +|---|---|---|---:| +| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 | +| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 | +| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 | + +## Cosa il backtest non rappresenta + +- I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono. +- 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. +- Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il 40% 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. +- Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX. diff --git a/docs/backtests/crypto_trend.outcome.json b/docs/backtests/crypto_trend.outcome.json new file mode 100644 index 0000000..9325ceb --- /dev/null +++ b/docs/backtests/crypto_trend.outcome.json @@ -0,0 +1,376 @@ +{ + "passed": false, + "verdict": "Protocollo non superato. Universo ampio: calo massimo 29,1%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,839, serve \u2264 0,40. Resta in osservazione.", + "report": "docs/backtests/crypto_trend.md", + "plan_hash": "737ca3a07b9c67574013581d6ebc395e60b8edfa0681707804e67601112f1c12", + "max_drawdown": 0.2910, + "expected_slippage_bp": 11.91, + "round_trip_cost": 0.006382, + "expected_path_p5": [ + -0.0099, + -0.0133, + -0.0175, + -0.0205, + -0.0231, + -0.0234, + -0.0242, + -0.026, + -0.0281, + -0.0291, + -0.031, + -0.031, + -0.0334, + -0.034, + -0.0352, + -0.037, + -0.0382, + -0.0396, + -0.0412, + -0.0405, + -0.0401, + -0.0415, + -0.0421, + -0.0437, + -0.044, + -0.0446, + -0.0458, + -0.0467, + -0.0479, + -0.0489, + -0.0503, + -0.0517, + -0.0528, + -0.0525, + -0.0529, + -0.0539, + -0.0552, + -0.0557, + -0.0563, + -0.0568, + -0.0583, + -0.0585, + -0.0595, + -0.0591, + -0.0583, + -0.0587, + -0.0593, + -0.0595, + -0.0596, + -0.0613, + -0.0609, + -0.0618, + -0.0629, + -0.0638, + -0.0641, + -0.0634, + -0.0646, + -0.0649, + -0.066, + -0.0659, + -0.067, + -0.0676, + -0.0693, + -0.0692, + -0.0697, + -0.0686, + -0.0687, + -0.0693, + -0.0693, + -0.0697, + -0.0696, + -0.069, + -0.069, + -0.0716, + -0.0725, + -0.0727, + -0.073, + -0.073, + -0.0734, + -0.0735, + -0.0738, + -0.074, + -0.0747, + -0.074, + -0.0757, + -0.0741, + -0.0742, + -0.0746, + -0.0757, + -0.0756, + -0.0761, + -0.0757, + -0.0761, + -0.0771, + -0.0785, + -0.0807, + -0.0819, + -0.0827, + -0.0823, + -0.083, + -0.0823, + -0.0831, + -0.0829, + -0.0853, + -0.0849, + -0.0836, + -0.0841, + -0.0835, + -0.084, + -0.0857, + -0.0856, + -0.0852, + -0.0861, + -0.0861, + -0.0861, + -0.0848, + -0.0861, + -0.0866, + -0.0876, + -0.0887, + -0.0897, + -0.0906, + -0.0902, + -0.0916, + -0.0917, + -0.0922, + -0.0937, + -0.0922, + -0.0931, + -0.0926, + -0.0922, + -0.0914, + -0.0914, + -0.0901, + -0.0916, + -0.0917, + -0.0937, + -0.0937, + -0.0955, + -0.0971, + -0.0958, + -0.0969, + -0.0972, + -0.0992, + -0.1007, + -0.101, + -0.1004, + -0.1008, + -0.1003, + -0.1005, + -0.1025, + -0.1024, + -0.1034, + -0.1027, + -0.1034, + -0.1042, + -0.1034, + -0.105, + -0.1037, + -0.1054, + -0.1066, + -0.1053, + -0.1055, + -0.1062, + -0.1057, + -0.1057, + -0.1072, + -0.1071, + -0.108, + -0.108, + -0.1087, + -0.1102, + -0.1118, + -0.1117, + -0.111, + -0.1112, + -0.111, + -0.1132, + -0.1108, + -0.1112, + -0.1119, + -0.1113, + -0.1127, + -0.1129, + -0.1129, + -0.1127, + -0.1143, + -0.1139, + -0.1162, + -0.1156, + -0.1159, + -0.1154, + -0.1173, + -0.116, + -0.1147, + -0.1162, + -0.1139, + -0.1135, + -0.1135, + -0.1138, + -0.1133, + -0.1144, + -0.1136, + -0.1136, + -0.1139, + -0.114, + -0.1151, + -0.1147, + -0.1148, + -0.1163, + -0.1161, + -0.1169, + -0.1164, + -0.1179, + -0.1179, + -0.1201, + -0.1206, + -0.1211, + -0.122, + -0.1227, + -0.1218, + -0.1221, + -0.1222, + -0.1222, + -0.1233, + -0.123, + -0.123, + -0.1229, + -0.1231, + -0.1225, + -0.1212, + -0.1195, + -0.1201, + -0.1202, + -0.1203, + -0.121, + -0.1228, + -0.1225, + -0.1221, + -0.1222, + -0.1222, + -0.1223, + -0.1223, + -0.1223, + -0.1241, + -0.1238, + -0.126, + -0.1252, + -0.1269, + -0.1266, + -0.1265, + -0.1258, + -0.1245, + -0.1261, + -0.1256, + -0.1258, + -0.1261, + -0.1263, + -0.1254, + -0.1272, + -0.1266, + -0.1266, + -0.1268, + -0.1273, + -0.1287, + -0.1275, + -0.1288, + -0.1269, + -0.1268, + -0.1273, + -0.1272, + -0.1269, + -0.1262, + -0.1259, + -0.1273, + -0.1267, + -0.1268, + -0.1259, + -0.1266, + -0.1257, + -0.1267, + -0.1272, + -0.1267, + -0.1268, + -0.126, + -0.1269, + -0.1267, + -0.1256, + -0.1256, + -0.1254, + -0.1258, + -0.1267, + -0.127, + -0.1275, + -0.1291, + -0.1262, + -0.1273, + -0.1287, + -0.129, + -0.1292, + -0.1278, + -0.125, + -0.1259, + -0.1273, + -0.1278, + -0.1278, + -0.1274, + -0.1253, + -0.1257, + -0.1237, + -0.1237, + -0.1244, + -0.1236, + -0.1242, + -0.1242, + -0.1248, + -0.1258, + -0.1266, + -0.127, + -0.126, + -0.126, + -0.1264, + -0.1263, + -0.1263, + -0.1268, + -0.1263, + -0.1249, + -0.1281, + -0.1282, + -0.1265, + -0.126, + -0.1262, + -0.1259, + -0.1281, + -0.1275, + -0.1296, + -0.1299, + -0.1286, + -0.1299, + -0.1292, + -0.128, + -0.1304, + -0.1309, + -0.1283, + -0.1313, + -0.1319, + -0.1308, + -0.1308, + -0.1307, + -0.1297, + -0.1303, + -0.1298, + -0.1322, + -0.1323, + -0.1323, + -0.1316, + -0.1311, + -0.1325, + -0.1332, + -0.1339, + -0.1339, + -0.1336, + -0.1332, + -0.1318, + -0.132 + ] +} diff --git a/docs/backtests/equity_meanrev.md b/docs/backtests/equity_meanrev.md new file mode 100644 index 0000000..db3757f --- /dev/null +++ b/docs/backtests/equity_meanrev.md @@ -0,0 +1,10 @@ +# Backtest di `equity_meanrev` (Ritorno alla media azioni) + +**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione. + +Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite. + +Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. + +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie. + diff --git a/docs/backtests/equity_meanrev.outcome.json b/docs/backtests/equity_meanrev.outcome.json new file mode 100644 index 0000000..dce192e --- /dev/null +++ b/docs/backtests/equity_meanrev.outcome.json @@ -0,0 +1,9 @@ +{ + "passed": false, + "verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.", + "report": "docs/backtests/equity_meanrev.md", + "max_drawdown": 0, + "expected_slippage_bp": 0, + "round_trip_cost": 0, + "expected_path_p5": [] +} diff --git a/docs/backtests/equity_momentum.md b/docs/backtests/equity_momentum.md new file mode 100644 index 0000000..9f182a7 --- /dev/null +++ b/docs/backtests/equity_momentum.md @@ -0,0 +1,10 @@ +# Backtest di `equity_momentum` (Momentum azioni) + +**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione. + +Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite. + +Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. + +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie. + diff --git a/docs/backtests/equity_momentum.outcome.json b/docs/backtests/equity_momentum.outcome.json new file mode 100644 index 0000000..87af21a --- /dev/null +++ b/docs/backtests/equity_momentum.outcome.json @@ -0,0 +1,9 @@ +{ + "passed": false, + "verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.", + "report": "docs/backtests/equity_momentum.md", + "max_drawdown": 0, + "expected_slippage_bp": 0, + "round_trip_cost": 0, + "expected_path_p5": [] +} diff --git a/src/Anubis.Server/BacktestCommand.cs b/src/Anubis.Server/BacktestCommand.cs new file mode 100644 index 0000000..49096cc --- /dev/null +++ b/src/Anubis.Server/BacktestCommand.cs @@ -0,0 +1,142 @@ +using System.Collections; +using System.Globalization; +using Anubis.Backtest; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// +/// "anubis backtest base": the honest backtests of the base strategies (SPEC 12.2, issue #44). It downloads the +/// Binance daily archives (each checked against its SHA-256) and the ECB rates into the research history, converts +/// them to euro, runs the protocol of crypto_trend on both universes and writes reports and outcome files. +/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation. +/// +internal static class BacktestCommand +{ + private const string Usage = + "Uso: anubis backtest base [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" + + " --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--platform docker|desktop] [--data-dir ]"; + + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, + HttpMessageHandler? handler = null) + { + output ??= Console.Out; + if (args.Length < 1 || args[0] != "base") + { + await output.WriteLineAsync(Usage).ConfigureAwait(false); + return 2; + } + + var rest = args[1..].ToList(); + environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); + var options = ServerOptions.Parse([.. rest.Where(a => a != "--offline")], environment); + var config = options.LoadConfig(environment); + var clock = new SystemClock(); + var now = clock.UtcNow; + var to = Option(rest, "--to") is { } t + ? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture) + : new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last month whose archive is published. + var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "backtests")); + try + { + config.Data.Ensure(); + Directory.CreateDirectory(outDir); + var store = new ResearchStore(config.Data.Research); + IReadOnlyList rates; + using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false)) + { + http.Timeout = TimeSpan.FromMinutes(5); + http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + rates = await RatesAsync(new ApiHttp(http, clock, "ecb"), config.Data.Research, rest.Contains("--offline"), output).ConfigureAwait(false); + if (!rest.Contains("--offline")) + { + var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), store, clock); + foreach (var symbol in CryptoTrendProtocol.Archives) + { + var result = await importer.ImportAsync(symbol, "1d", 2017, 8, CancellationToken.None).ConfigureAwait(false); + await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{symbol}: {result.Bars} barre giornaliere")).ConfigureAwait(false); + } + } + } + + var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false); + await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").ConfigureAwait(false); + + var outcome = await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false); + var notes = DataNotes(outcome, rates); + await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.md"), + ProtocolReport.Markdown(outcome, "crypto_trend", notes, "anubis backtest base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false); + await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false); + foreach (var run in outcome.Runs) + { + // The full reports (curve, trades) stay with the data: the repository keeps the summary and the outcome. + await File.WriteAllTextAsync(Path.Combine(config.Data.Research, "crypto_trend-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson()) + .ConfigureAwait(false); + } + + foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") }) + { + var waiting = EquityProtocol.Waiting(strategy); + await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false); + await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false); + } + + await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false); + await output.WriteLineAsync("Rapporti scritti in " + outDir).ConfigureAwait(false); + return 0; + } + catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException + or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException) + { + await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); + return 1; + } + } + + /// The ECB history of EUR/USD, kept next to the research data so an offline run uses the same rates. + private static async Task> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output) + { + var path = Path.Combine(researchRoot, "ecb-eurofxref-hist.zip"); + if (!offline || !File.Exists(path)) + { + var zip = await http.GetBytesAsync(Ecb.History, null, null, CancellationToken.None).ConfigureAwait(false) + ?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true); + await File.WriteAllBytesAsync(path, zip).ConfigureAwait(false); + } + + var rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(await File.ReadAllBytesAsync(path).ConfigureAwait(false)), ["USD"]); + await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Cambi BCE EUR/USD: {rates.Count} giorni, dal {rates[0].Date:yyyy-MM-dd} al {rates[^1].Date:yyyy-MM-dd}.")) + .ConfigureAwait(false); + return rates; + } + + private static List DataNotes(ProtocolOutcome outcome, IReadOnlyList rates) + { + var broad = outcome.Runs[0].Report.Instruments; + var it = CultureInfo.GetCultureInfo("it-IT"); + var missing = CryptoTrendProtocol.Archives.Select(EuroHistory.SymbolOf).Where(s => broad.All(i => i.Symbol != s)).ToList(); + var notes = new List + { + "Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.", + string.Create(it, $"Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno ({rates.Count} giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1)."), + string.Create(it, $"{broad.Count} coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni."), + "Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.", + }; + if (missing.Count > 0) + { + notes.Add("Senza archivi nel periodo, quindi non usate: " + string.Join(", ", missing) + "."); + } + + return notes; + } + + private static string? Option(List args, string name) + { + var index = args.IndexOf(name); + return index >= 0 && index < args.Count - 1 ? args[index + 1] : null; + } +} diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index f8c172c..c145661 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -12,6 +12,12 @@ if (args.Length >= 1 && args[0] == "data") return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false); } +// "anubis backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5). +if (args.Length >= 1 && args[0] == "backtest") +{ + return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false); +} + var app = ServerApp.Build(args); await app.RunAsync().ConfigureAwait(false); return 0; diff --git a/src/Anubis/Anubis.csproj b/src/Anubis/Anubis.csproj index 7cc3c05..7ee364e 100644 --- a/src/Anubis/Anubis.csproj +++ b/src/Anubis/Anubis.csproj @@ -10,6 +10,8 @@ + + diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index e9a2c63..0309736 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -46,7 +46,7 @@ public static class TrialRequestErrors /// public sealed partial class Laboratory : IDisposable { - public const int MaxSymbols = 20; + public const int MaxSymbols = 60; public const int MaxVariants = 200; @@ -264,29 +264,45 @@ public sealed partial class Laboratory : IDisposable { var instrument = await catalog.FindAsync(data.Venue, symbol, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"Strumento sconosciuto: {symbol} su {data.Venue}."); - var daily = await bars.DailyAsync(instrument.Id, data.From, data.To, cancellationToken).ConfigureAwait(false); + var daily = await bars.DailyAsync(instrument.Id, data.HistoryStart(), data.To, cancellationToken).ConfigureAwait(false); var events = instrument.IsCrypto ? [] : await actions.ForSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); - instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.From && a.ExDate <= data.To)], "barre raccolte")); + instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.HistoryStart() && a.ExDate <= data.To)], "barre raccolte")); } } else { - var store = new ResearchStore(researchRoot); - var from = new DateTimeOffset(data.From.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); - var to = new DateTimeOffset(data.To.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); - foreach (var symbol in data.Symbols) - { - var daily = new List(); - await foreach (var b in store.ReadAsync(data.Venue, symbol, Timeframes.Day, from, to, cancellationToken).ConfigureAwait(false)) - { - daily.Add(new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, (double)b.Close, (double)b.Volume)); - } - - instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, "storico di ricerca")); - } + return await LoadResearchAsync(researchRoot, data, cancellationToken).ConfigureAwait(false); } - var empty = instruments.FirstOrDefault(i => i.Bars.Count == 0); + return Checked(instruments, data); + } + + /// The bars of a trial on the research history: no database needed (the protocol runs from the command line). + public static async Task LoadResearchAsync(string researchRoot, TrialData data, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(data); + var instruments = new List(); + var store = new ResearchStore(researchRoot); + var from = new DateTimeOffset(data.HistoryStart().ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var to = new DateTimeOffset(data.To.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var source = data.Venue == EuroHistory.Venue ? "storico Binance convertito in euro" : "storico di ricerca"; + foreach (var symbol in data.Symbols) + { + var daily = new List(); + await foreach (var b in store.ReadAsync(data.Venue, symbol, Timeframes.Day, from, to, cancellationToken).ConfigureAwait(false)) + { + daily.Add(new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, (double)b.Close, (double)b.Volume)); + } + + instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, source)); + } + + return Checked(instruments, data); + } + + private static BacktestDataset Checked(List instruments, TrialData data) + { + var empty = instruments.FirstOrDefault(i => !i.Bars.Any(b => b.Day >= data.From && b.Day <= data.To)); if (empty is not null) { throw new InvalidOperationException($"Nessuna barra giornaliera per {empty.Symbol} tra il {data.From:dd/MM/yyyy} e il {data.To:dd/MM/yyyy}."); diff --git a/src/Anubis/Backtest/Protocol.cs b/src/Anubis/Backtest/Protocol.cs new file mode 100644 index 0000000..0fa9cfc --- /dev/null +++ b/src/Anubis/Backtest/Protocol.cs @@ -0,0 +1,376 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The Binance USDT archives turned into euro (SPEC 8.1): the EUR pairs of OKX start in November 2023, so the years +/// before use the USDT history divided by the ECB EUR/USD rate of the day, one USDT counted as one dollar. The +/// converted series live in the research history under their own venue, so a trial on them can be planned again. +/// +public static class EuroHistory +{ + public const string Venue = "binance_eur"; + + /// A rate older than this is not used: the ECB never skips more than a long holiday weekend. + public static readonly int MaxRateAgeDays = 7; + + /// + /// A hole longer than this in a coin's daily series ends it: what comes after is a relaunch under the same ticker + /// (LUNA after May 2022), not the coin the earlier bars describe. + /// + public static readonly int MaxGapDays = 7; + + /// BTCUSDT becomes BTCEUR. + public static string SymbolOf(string usdtSymbol) + { + ArgumentNullException.ThrowIfNull(usdtSymbol); + return usdtSymbol.EndsWith("USDT", StringComparison.Ordinal) && usdtSymbol.Length > 4 + ? usdtSymbol[..^4] + "EUR" + : throw new ArgumentException("Not a USDT pair: " + usdtSymbol, nameof(usdtSymbol)); + } + + /// + /// Divides prices and traded value by the EUR/USD rate of the bar's day, or of the last day before with a rate. A + /// bar is dropped when no rate of the last days exists. The rate of day d is fixed at + /// 16:00 CET, before the daily bar closes at 00:00 UTC, so the close in euro uses nothing from the future. The + /// series stops at the first hole longer than days. + /// + public static IReadOnlyList Convert(IEnumerable bars, IReadOnlyList eurUsd) + { + ArgumentNullException.ThrowIfNull(bars); + ArgumentNullException.ThrowIfNull(eurUsd); + var rates = eurUsd.Where(r => r.Base == "EUR" && r.Quote == "USD" && r.Rate > 0m).OrderBy(r => r.Date).ToList(); + var result = new List(); + var k = -1; + DateTimeOffset? previous = null; + foreach (var bar in bars.OrderBy(b => b.OpensAt)) + { + if (previous is { } p && bar.OpensAt - p > TimeSpan.FromDays(MaxGapDays)) + { + break; + } + + previous = bar.OpensAt; + var day = DateOnly.FromDateTime(bar.OpensAt.UtcDateTime); + while (k + 1 < rates.Count && rates[k + 1].Date <= day) + { + k++; + } + + if (k < 0 || rates[k].Date < day.AddDays(-MaxRateAgeDays)) + { + continue; + } + + var rate = rates[k].Rate; + result.Add(new ResearchBar(bar.OpensAt, Round(bar.Open / rate), Round(bar.High / rate), Round(bar.Low / rate), Round(bar.Close / rate), bar.Volume) + { + QuoteVolume = bar.QuoteVolume is { } q ? Round(q / rate) : null, + Trades = bar.Trades, + }); + } + + return result; + } + + /// Converts every daily USDT series of the Binance archives in the store. Returns the symbols written. + public static async Task> ConvertAllAsync(ResearchStore store, IReadOnlyList eurUsd, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(store); + var written = new List(); + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == Venues.Binance && s.Timeframe == Timeframes.Day && s.Symbol.EndsWith("USDT", StringComparison.Ordinal))) + { + var bars = new List(); + await foreach (var bar in store.ReadAsync(Venues.Binance, symbol, Timeframes.Day, Ever.From, Ever.To, cancellationToken).ConfigureAwait(false)) + { + bars.Add(bar); + } + + var converted = Convert(bars, eurUsd); + if (converted.Count > 0) + { + await store.WriteAsync(Venue, SymbolOf(symbol), Timeframes.Day, converted, cancellationToken).ConfigureAwait(false); + written.Add(SymbolOf(symbol)); + } + } + + return written; + } + + // Twelve decimals keep seven significant digits even for coins priced at a hundred-thousandth of a euro. + private static decimal Round(decimal value) => Math.Round(value, 12, MidpointRounding.ToEven); + + private static class Ever + { + public static readonly DateTimeOffset From = new(2009, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static readonly DateTimeOffset To = new(2100, 1, 1, 0, 0, 0, TimeSpan.Zero); + } +} + +/// A trial of the protocol: which universe, its report and the daily returns of the chosen variant. +public sealed record ProtocolRun(string Name, string Description, TrialPlan Plan, BacktestReport Report, IReadOnlyList DailyReturns, decimal ExpectedSlippageBp); + +/// What the protocol of a strategy concluded: the outcome file and the trials behind it. +public sealed record ProtocolOutcome(Qualification Qualification, IReadOnlyList Runs); + +/// +/// The anti-illusion protocol of SPEC 12.2 for crypto_trend, run from the command line on the research +/// history: it must pass twice (SPEC 8.1), on the broad universe and on BTC, ETH and SOL alone. Everything is fixed +/// before the run: dates, capital, grid, costs, thresholds. The result is written whatever it is. +/// +public static class CryptoTrendProtocol +{ + public const string Strategy = StrategyNames.CryptoTrend; + + public const string ReportPath = "docs/backtests/crypto_trend.md"; + + public const decimal Capital = 10_000m; + + /// Two years of Binance history before this day are enough for the longest period (360) and the 400 days of age. + public static readonly DateOnly From = new(2019, 1, 1); + + public static readonly IReadOnlyList Narrow = ["BTCEUR", "ETHEUR", "SOLEUR"]; + + /// + /// The USDT pairs downloaded from the Binance archives: every coin that was among the ten most traded at some time + /// since 2018, including those later delisted (LUNA, FTT, BCC, VEN, XMR...), so the past universe is not chosen + /// with hindsight. Stablecoins are left out: the strategy excludes them anyway. A pair without archives is skipped. + /// + public static readonly IReadOnlyList Archives = + [ + "BTCUSDT", "ETHUSDT", "BNBUSDT", "XRPUSDT", "ADAUSDT", "SOLUSDT", "DOGEUSDT", "LTCUSDT", "BCCUSDT", "BCHABCUSDT", "BCHUSDT", "BCHSVUSDT", + "EOSUSDT", "TRXUSDT", "ETCUSDT", "LINKUSDT", "DOTUSDT", "MATICUSDT", "POLUSDT", "AVAXUSDT", "LUNAUSDT", "FTTUSDT", "SHIBUSDT", "FILUSDT", + "ATOMUSDT", "UNIUSDT", "NEOUSDT", "XLMUSDT", "VENUSDT", "VETUSDT", "SANDUSDT", "APEUSDT", "GMTUSDT", "NEARUSDT", "PEPEUSDT", "WIFUSDT", + "SUIUSDT", "ARBUSDT", "OPUSDT", "ORDIUSDT", "ONTUSDT", "IOTAUSDT", "QTUMUSDT", "ICXUSDT", "XMRUSDT", "DASHUSDT", "ZECUSDT", "TONUSDT", "TRUMPUSDT", + ]; + + /// Length of the expected path of the outcome: one year of daily closes. + public const int PathDays = 365; + + public static async Task RunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action? progress, CancellationToken cancellationToken) + { + var store = new ResearchStore(researchRoot); + var broad = new List(); + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day)) + { + // Every converted pair goes in: the strategy picks its top 10 month by month, among coins that died too. + if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false)) + { + broad.Add(symbol); + } + } + + if (Narrow.Any(s => !broad.Contains(s))) + { + throw new InvalidOperationException("Mancano gli storici di BTC, ETH o SOL in euro: scarica prima gli archivi Binance e il cambio BCE."); + } + + var family = StrategyCatalog.Find(Strategy) ?? throw new InvalidOperationException("crypto_trend non è nel catalogo."); + var first = await RunOneAsync(family, "Universo ampio", $"Le 10 monete con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).", + broad, to, now, researchRoot, PriorTrials.None, progress, cancellationToken).ConfigureAwait(false); + var prior = new PriorTrials(1, first.Report.Variants.Count, [.. first.Report.Variants.Select(v => v.Sharpe)]); + var second = await RunOneAsync(family, "BTC, ETH e SOL", "Solo le tre coppie in euro con la liquidità migliore.", + Narrow, to, now, researchRoot, prior, progress, cancellationToken).ConfigureAwait(false); + List runs = [first, second]; + return new ProtocolOutcome(QualificationOf(runs), runs); + } + + /// The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live. + public static Qualification QualificationOf(IReadOnlyList runs) + { + ArgumentNullException.ThrowIfNull(runs); + var main = runs[0]; + var passed = runs.All(r => r.Report.Passed); + var it = CultureInfo.GetCultureInfo("it-IT"); + string verdict; + if (passed) + { + verdict = "Protocollo superato su entrambi gli universi: parte in simulazione."; + } + else + { + var failures = runs.Where(r => !r.Report.Passed) + .Select(r => r.Name + ": " + string.Join("; ", r.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, it)))); + verdict = "Protocollo non superato. " + string.Join(". ", failures) + ". Resta in osservazione."; + } + + var taker = PaperOptions.Okx().TakerFee; + return new Qualification + { + Passed = passed, + Verdict = verdict, + Report = ReportPath, + PlanHash = TrialPlan.Hash(main.Plan.ToJson()), + MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4), + ExpectedSlippageBp = main.ExpectedSlippageBp, + RoundTripCost = Math.Round(2m * (taker + (main.ExpectedSlippageBp / 10_000m)), 6), + ExpectedPathP5 = [.. PathBootstrap.Percentile(main.DailyReturns, PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) + .Select(x => Math.Round(x, 4))], + }; + } + + /// A failed check in plain Italian, e.g. "calo massimo 38,2%, oltre il 25%". + public static string Describe(ReportCheck check, IFormatProvider culture) + { + ArgumentNullException.ThrowIfNull(check); + var value = check.Value is not { } v ? "non calcolabile" + : check.Unit switch + { + "percent" => string.Create(culture, $"{v * 100:0.0}%"), + "money" => string.Create(culture, $"{v:#,0.00} €"), + "count" => string.Create(culture, $"{v:0}"), + _ => string.Create(culture, $"{v:0.000}"), + }; + var threshold = check.Unit == "percent" ? string.Create(culture, $"{check.Threshold * 100:0}%") : string.Create(culture, $"{check.Threshold:0.00}"); + return $"{check.Name.ToLower(CultureInfo.GetCultureInfo("it-IT"))} {value}, serve {check.Comparison} {threshold}"; + } + + private static async Task RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList symbols, DateOnly to, + DateTimeOffset now, string researchRoot, PriorTrials prior, Action? progress, CancellationToken cancellationToken) + { + var request = new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, symbols, From, to, Capital, null); + var (plan, _) = Laboratory.BuildPlan(request, now); + var json = plan.ToJson(); + var hash = TrialPlan.Hash(json); + var data = await Laboratory.LoadResearchAsync(researchRoot, plan.Data, cancellationToken).ConfigureAwait(false); + + // The id comes from the plan, so the same plan on the same data writes the same report. + var id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(hash)).AsSpan(0, 16)); + var (report, _) = TrialRunner.Run(id, plan, hash, family, data, prior, now, text => progress?.Invoke(name + ": " + text), cancellationToken); + + // The chosen variant again, for its daily returns and the slippage of what it traded. + var variant = ParameterGrid.Of(family, plan.Grid).First(v => v.ToString() == report.Chosen); + var options = StrategyPipeline.For(family.Id, data, new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }, plan.ReferenceShare); + var run = BacktestEngine.Run(family.Create(variant.Parameters), data, options); + var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var traded = run.Trades.Sum(t => t.Invested); + var slippage = traded > 0m + ? Math.Round(run.Trades.Sum(t => t.Invested * PaperBroker.SlippageBp(specs.GetValueOrDefault(t.Symbol))) / traded, 2) + : PaperBroker.SlippageBp(null); + return new ProtocolRun(name, description, plan, report, run.DailyReturns(), slippage); + } + + private static async Task HasBarsAsync(ResearchStore store, string symbol, DateOnly to, CancellationToken cancellationToken) + { + var from = new DateTimeOffset(From.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var end = new DateTimeOffset(to.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + await foreach (var _ in store.ReadAsync(EuroHistory.Venue, symbol, Timeframes.Day, from, end, cancellationToken).ConfigureAwait(false)) + { + return true; + } + + return false; + } +} + +/// +/// The expected path of SPEC 12.3: a stationary block bootstrap of the backtest's daily returns (blocks keep the +/// clustering of volatility), and for each day from the start the given percentile of the cumulative result. The seed +/// is fixed, so the same returns always give the same path. +/// +public static class PathBootstrap +{ + public const int Paths = 2000; + + public const int Block = 20; + + public const int Seed = 20_260_101; + + public static IReadOnlyList Percentile(IReadOnlyList returns, int days, double percentile, int paths, int block, int seed) + { + ArgumentNullException.ThrowIfNull(returns); + ArgumentOutOfRangeException.ThrowIfLessThan(days, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(paths, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(block, 1); + if (returns.Count == 0) + { + return [.. Enumerable.Repeat(0d, days)]; + } + + var random = new Random(seed); + var cumulative = new double[days][]; + for (var d = 0; d < days; d++) + { + cumulative[d] = new double[paths]; + } + + for (var p = 0; p < paths; p++) + { + var value = 1d; + var index = random.Next(returns.Count); + for (var d = 0; d < days; d++) + { + // A new block starts with probability 1/block: blocks of geometric length, mean "block" days. + if (d > 0 && random.NextDouble() < 1d / block) + { + index = random.Next(returns.Count); + } + else if (d > 0) + { + index = (index + 1) % returns.Count; + } + + value *= 1d + returns[index]; + cumulative[d][p] = value - 1d; + } + } + + var result = new double[days]; + for (var d = 0; d < days; d++) + { + Array.Sort(cumulative[d]); + var rank = Math.Clamp((int)Math.Floor(percentile * (paths - 1)), 0, paths - 1); + result[d] = cumulative[d][rank]; + } + + return result; + } +} + +/// +/// The outcome files of docs/backtests/, built into the program: loaded at the first start, they decide +/// whether a base strategy starts in simulation or stays in observation (SPEC 12.3). +/// +public static class BacktestOutcomes +{ + public const string ResourcePrefix = "Anubis.Backtests."; + + public static Qualification? Find(string strategy) + { + using var stream = typeof(BacktestOutcomes).Assembly.GetManifestResourceStream(ResourcePrefix + strategy + ".outcome.json"); + return stream is null ? null : JsonSerializer.Deserialize(stream, Qualification.Json); + } + + private static readonly JsonSerializerOptions Indented = new(Qualification.Json) { WriteIndented = true }; + + public static string ToJson(Qualification qualification) => JsonSerializer.Serialize(qualification, Indented) + "\n"; +} + +/// +/// The stock strategies wait for the Alpaca history (SPEC 8.2, 8.3): without the keys there are no adjusted daily +/// bars of the S&P 500 members, so the protocol cannot run and they stay in observation. The outcome file says so. +/// +public static class EquityProtocol +{ + public static readonly IReadOnlyList Explanation = + [ + "Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.", + "Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.", + "Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine \"barre raccolte\": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie.", + ]; + + public static Qualification Waiting(string strategy) => new() + { + Passed = false, + Verdict = "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.", + Report = "docs/backtests/" + strategy + ".md", + }; +} diff --git a/src/Anubis/Backtest/ProtocolReport.cs b/src/Anubis/Backtest/ProtocolReport.cs new file mode 100644 index 0000000..798d1e4 --- /dev/null +++ b/src/Anubis/Backtest/ProtocolReport.cs @@ -0,0 +1,206 @@ +using System.Globalization; +using System.Text; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The report of docs/backtests/ in plain Italian (SPEC 12.2 point 6): for each trial the figures of the chosen +/// variant against buy and hold, by year, at single, double and triple costs, the validations, the checks and what +/// the backtest does not model. It is written whatever the outcome. +/// +public static class ProtocolReport +{ + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + public static string Markdown(ProtocolOutcome outcome, string title, IReadOnlyList dataNotes, string command) + { + ArgumentNullException.ThrowIfNull(outcome); + ArgumentNullException.ThrowIfNull(dataNotes); + var q = outcome.Qualification; + var first = outcome.Runs[0].Report; + var b = new StringBuilder(); + b.Append("# Backtest di `").Append(first.Strategy).Append("` (").Append(first.StrategyName).AppendLine(")").AppendLine(); + b.Append("**Esito: ").Append(q.Passed ? "superato" : "non superato").Append(".** ").AppendLine(q.Verdict).AppendLine(); + b.AppendLine(Text($"Calcolato il {first.ComputedAt:yyyy-MM-dd} con la versione {first.StrategyVersion} della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.")) + .AppendLine(); + b.Append("Per rifarlo: `").Append(command).AppendLine("`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/" + first.Strategy + ".outcome.json`.").AppendLine(); + + b.AppendLine("## Dati").AppendLine(); + foreach (var note in dataNotes) + { + b.Append("- ").AppendLine(note); + } + + b.AppendLine(); + b.AppendLine("## Riepilogo").AppendLine(); + b.AppendLine("| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |"); + b.AppendLine("|---|---|---:|---:|---:|---:|---:|---|"); + foreach (var run in outcome.Runs) + { + var r = run.Report; + var doubled = r.Costs.FirstOrDefault(c => c.Multiplier == 2m); + b.Append("| ").Append(run.Name).Append(" | `").Append(r.Chosen).Append("` | ").Append(Pct(r.Metrics.AnnualReturn)).Append(" | ").Append(Pct(-r.Metrics.MaxDrawdown)) + .Append(" | ").Append(doubled is null ? "—" : Money(doubled.NetResult, r.Currency)).Append(" | ").Append(r.DeflatedSharpe.Value.ToString("0.000", It)) + .Append(" | ").Append(r.Overfitting is { } o ? o.Probability.ToString("0.000", It) : "—").Append(" | ").Append(r.Passed ? "superata" : "non superata").AppendLine(" |"); + } + + b.AppendLine(); + b.AppendLine("## Cosa conserva il bot").AppendLine(); + b.AppendLine(Text($"- Calo massimo del backtest: {Pct(-(double)q.MaxDrawdown)}. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).")); + b.AppendLine(Text($"- Scostamento di prezzo previsto: {q.ExpectedSlippageBp.ToString("0.##", It)} punti base; costo stimato di andata e ritorno {Pct((double)q.RoundTripCost, 2)}.")); + if (q.ExpectedPathP5.Count > 0) + { + b.AppendLine(Text($"- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): {Pct(q.ExpectedPathP5[Math.Min(29, q.ExpectedPathP5.Count - 1)])} dopo 30 giorni, {Pct(q.ExpectedPathP5[Math.Min(89, q.ExpectedPathP5.Count - 1)])} dopo 90, {Pct(q.ExpectedPathP5[^1])} dopo {q.ExpectedPathP5.Count}. Venti sedute di fila sotto questo percorso riportano la strategia indietro.")); + } + + b.AppendLine(); + foreach (var run in outcome.Runs) + { + Trial(b, run); + } + + b.AppendLine("## Cosa il backtest non rappresenta").AppendLine(); + foreach (var line in first.Limitations) + { + b.Append("- ").AppendLine(line); + } + + return b.ToString(); + } + + /// The report of a strategy whose backtest cannot run yet, with what it waits for. + public static string Waiting(string strategy, string name, Qualification qualification, IReadOnlyList lines) + { + ArgumentNullException.ThrowIfNull(qualification); + ArgumentNullException.ThrowIfNull(lines); + var b = new StringBuilder(); + b.Append("# Backtest di `").Append(strategy).Append("` (").Append(name).AppendLine(")").AppendLine(); + b.Append("**Esito: in attesa.** ").AppendLine(qualification.Verdict).AppendLine(); + foreach (var line in lines) + { + b.AppendLine(line).AppendLine(); + } + + return b.ToString(); + } + + private static void Trial(StringBuilder b, ProtocolRun run) + { + var r = run.Report; + var m = r.Metrics; + var h = r.Benchmark; + // Validations and variants keep the Sharpe of one session: shown per year, like the metrics above. + var annual = Math.Sqrt(r.PeriodsPerYear); + b.Append("## ").AppendLine(run.Name).AppendLine(); + b.AppendLine(run.Description).AppendLine(); + b.AppendLine(Text($"Dal {m.From:dd/MM/yyyy} al {m.To:dd/MM/yyyy}, {r.Sessions} chiusure giornaliere, capitale iniziale {Money(m.InitialCapital, r.Currency)}. Variante scelta: `{r.Chosen}` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `{r.PlanHash[..12]}`, dei dati `{r.DataFingerprint[..12]}`.")) + .AppendLine(); + + b.AppendLine("| | Strategia | Comprare e tenere |").AppendLine("|---|---:|---:|"); + Row(b, "Risultato netto", Money(m.NetResult, r.Currency), Money(h.NetResult, r.Currency)); + Row(b, "Rendimento totale", Pct(m.TotalReturn), Pct(h.TotalReturn)); + Row(b, "Rendimento annuo", Pct(m.AnnualReturn), Pct(h.AnnualReturn)); + Row(b, "Volatilità annua", Pct(m.Volatility), Pct(h.Volatility)); + Row(b, "Calo massimo", Pct(-m.MaxDrawdown) + Text($" ({m.DrawdownPeak:MM/yyyy} → {m.DrawdownLow:MM/yyyy})"), Pct(-h.MaxDrawdown)); + Row(b, "Sharpe annuo", Num(m.Sharpe), Num(h.Sharpe)); + Row(b, "Operazioni chiuse", m.Trades.ToString(It), h.Trades.ToString(It)); + Row(b, "Operazioni in guadagno", Pct(m.WinRate), "—"); + Row(b, "Rapporto guadagni/perdite", m.ProfitFactor is { } pf ? Num(pf) : "—", "—"); + Row(b, "Commissioni pagate", Money(m.Fees, r.Currency), Money(h.Fees, r.Currency)); + Row(b, "Tempo investito", Pct(m.Exposure), Pct(h.Exposure)); + b.AppendLine(); + + b.AppendLine("**Per anno**").AppendLine(); + b.AppendLine("| Anno | Strategia | Comprare e tenere |").AppendLine("|---|---:|---:|"); + var held = h.Years.ToDictionary(y => y.Year); + foreach (var y in m.Years) + { + Row(b, y.Year.ToString(CultureInfo.InvariantCulture), Pct(y.Return), held.TryGetValue(y.Year, out var hy) ? Pct(hy.Return) : "—"); + } + + b.AppendLine(); + b.AppendLine("**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)").AppendLine(); + b.AppendLine("| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |").AppendLine("|---|---:|---:|---:|---:|---:|"); + foreach (var c in r.Costs) + { + b.AppendLine(Text($"| ×{c.Multiplier:0} | {Money(c.NetResult, r.Currency)} | {Pct(c.TotalReturn)} | {Num(c.Sharpe)} | {Pct(-c.MaxDrawdown)} | {Money(c.Fees, r.Currency)} |")); + } + + b.AppendLine(); + b.AppendLine("**Convalide**").AppendLine(); + if (r.WalkForward is { } wf) + { + b.AppendLine(Text($"- Finestre che avanzano ({wf.Windows.Count}, con {wf.Purge} giorni di stacco): rendimento fuori campione {Pct(wf.Return)}, Sharpe annuo {Num(wf.Sharpe * annual)}.")); + } + + if (r.Combinatorial is { } cv) + { + b.AppendLine(Text($"- K-fold purgato combinatorio ({cv.Groups} gruppi, {cv.TestGroups} di prova, {cv.Splits} divisioni): Sharpe annuo medio dei percorsi {Num(cv.MeanSharpe * annual)}, peggiore {Num(cv.WorstSharpe * annual)}, percorsi positivi {Pct(cv.PositiveShare)}.")); + } + + b.AppendLine(Text($"- Deflated Sharpe Ratio {Num(r.DeflatedSharpe.Value)}, contando {r.TrialsCounted} varianti provate in tutto.")); + b.AppendLine(r.Overfitting is { } pbo + ? Text($"- Probabilità di sovra-adattamento (PBO) {Num(pbo.Probability)}, su {pbo.Combinations} combinazioni di {pbo.Variants} varianti.") + : "- Probabilità di sovra-adattamento: non calcolabile con una sola variante."); + b.AppendLine(Text($"- Sguardo in avanti: {r.LookAhead.Decisions} decisioni rifatte tagliando i dati in {r.LookAhead.Cutoffs.Count} punti, {r.LookAhead.Changed} cambiate.")); + b.AppendLine(); + + b.AppendLine("**Soglie**").AppendLine(); + b.AppendLine("| Controllo | Valore | Soglia | Esito |").AppendLine("|---|---:|---:|---|"); + foreach (var c in r.Checks) + { + var value = c.Value is not { } v ? "—" : c.Unit switch + { + "percent" => Pct(v), + "money" => Money((decimal)v, r.Currency), + "count" => v.ToString("0", It), + _ => v.ToString("0.000", It), + }; + var threshold = c.Unit == "percent" ? Pct(c.Threshold, 0) : c.Unit == "money" ? Money((decimal)c.Threshold, r.Currency) : c.Threshold.ToString("0.##", It); + b.AppendLine(Text($"| {c.Name} | {value} | {c.Comparison} {threshold} | {(c.Passed is null ? "non si applica" : c.Passed.Value ? "superato" : "**non superato**")} |")); + } + + b.AppendLine(); + b.AppendLine("**Varianti della griglia**").AppendLine(); + b.AppendLine("| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |").AppendLine("|---|---:|---:|---:|---:|---:|"); + foreach (var v in r.Variants) + { + b.AppendLine(Text($"| `{v.Parameters}`{(v.Chosen ? " (scelta)" : "")} | {Num(v.Sharpe * annual)} | {Num(v.PlateauScore * annual)} | {Money(v.NetResult, r.Currency)} | {Pct(-v.MaxDrawdown)} | {v.Trades} |")); + } + + if (r.Notes.Count > 0) + { + b.AppendLine(); + b.AppendLine("**Interventi di correttivi e rischio sulla variante scelta**").AppendLine(); + b.AppendLine("| Motivo | Volte |").AppendLine("|---|---:|"); + foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value).ThenBy(n => n.Key, StringComparer.Ordinal)) + { + b.AppendLine(Text($"| `{reason}` | {count} |")); + } + } + + b.AppendLine(); + b.AppendLine("**Strumenti**").AppendLine(); + b.AppendLine("| Coppia | Prima barra | Ultima barra | Barre |").AppendLine("|---|---|---|---:|"); + foreach (var i in r.Instruments) + { + b.AppendLine(Text($"| {i.Symbol} | {i.First:yyyy-MM-dd} | {i.Last:yyyy-MM-dd} | {i.Bars} |")); + } + + b.AppendLine(); + } + + private static void Row(StringBuilder b, string label, string strategy, string benchmark) => + b.Append("| ").Append(label).Append(" | ").Append(strategy).Append(" | ").Append(benchmark).AppendLine(" |"); + + private static string Pct(double fraction, int decimals = 1) => + (fraction < 0 ? "−" : "") + Math.Abs(fraction * 100).ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), It) + "%"; + + private static string Num(double value) => (value < 0 ? "−" : "") + Math.Abs(value).ToString("0.00", It); + + private static string Money(decimal value, string currency) => + (value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.00", It) + " " + (currency == "EUR" ? "€" : currency); + + private static string Text(FormattableString text) => text.ToString(It); +} diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index f4e627c..94201cc 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -106,9 +106,10 @@ public static class TrialRunner ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(prior); var watch = Stopwatch.StartNew(); - if (data.Sessions.Count < 30) + var sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + if (sessions < 30) { - throw new InvalidOperationException($"Dati insufficienti: {data.Sessions.Count} sedute, ne servono almeno 30."); + throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30."); } var variants = ParameterGrid.Of(family, plan.Grid); @@ -118,7 +119,7 @@ public static class TrialRunner } // 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 plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }; var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) @@ -204,7 +205,7 @@ public static class TrialRunner data.Fingerprint(), data.Currency, data.PeriodsPerYear, - data.Sessions.Count, + sessions, [.. data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))], chosen.ToString(), @@ -258,7 +259,12 @@ public static class TrialRunner result.Add("Strategia d'esempio: correttivi e limiti di rischio non si applicano, ogni intenzione passa così com'è."); } - if (plan.Data.Source == TrialSources.Research) + if (plan.Data.Source == TrialSources.Research && plan.Data.Venue == EuroHistory.Venue) + { + result.Add("Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. " + + "Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX."); + } + else 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/Trials.cs b/src/Anubis/Backtest/Trials.cs index 62bdc38..96cd14a 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -17,8 +17,19 @@ public static class TrialSources public const string Research = "research"; } -/// The data a trial reads: one venue, a few instruments, a period (both days included). -public sealed record TrialData(string Source, string Venue, IReadOnlyList Symbols, DateOnly From, DateOnly To); +/// +/// The data a trial reads: one venue, a few instruments, a period (both days included). The bars of the +/// before are read too, only so the indicators and the listing age are ready on +/// the first day: the simulation, the measures and buy and hold start at . +/// +public sealed record TrialData(string Source, string Venue, IReadOnlyList Symbols, DateOnly From, DateOnly To) +{ + /// Calendar days of history before the start: a year of 252 sessions, a 360-day lookback, 400 days of listing. + public const int WarmupDays = 450; + + /// The first day read from the history. + public DateOnly HistoryStart() => From.AddDays(-WarmupDays); +} /// /// The thresholds of SPEC 12.2, fixed in the plan before the trial runs: changing them after seeing the results needs diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 48ee059..b3929de 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -216,6 +216,7 @@ public sealed partial class TradingService : IDisposable var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false); var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false); var accounts = await AccountSetup.EnsureAsync(_db, _clock, alpaca is not null, okx is not null, cancellationToken).ConfigureAwait(false); + await LoadOutcomesAsync(cancellationToken).ConfigureAwait(false); await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); foreach (var account in accounts) @@ -260,6 +261,21 @@ public sealed partial class TradingService : IDisposable await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); } + /// + /// The backtest outcomes built into the program (docs/backtests): at the first start a base strategy that passed + /// moves to simulation, one that did not stays in observation with the reason (SPEC 12.3). + /// + public async Task LoadOutcomesAsync(CancellationToken cancellationToken) + { + foreach (var (strategy, _, _) in StrategyNames.Base) + { + if (Backtest.BacktestOutcomes.Find(strategy) is { } outcome) + { + await Stages.ApplyQualificationAsync(strategy, outcome, cancellationToken).ConfigureAwait(false); + } + } + } + public IReadOnlyList Jobs() => [ new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync), diff --git a/tests/Anubis.Tests/LaboratoryTests.cs b/tests/Anubis.Tests/LaboratoryTests.cs index 2ddfcc7..6b962e9 100644 --- a/tests/Anubis.Tests/LaboratoryTests.cs +++ b/tests/Anubis.Tests/LaboratoryTests.cs @@ -209,7 +209,8 @@ public sealed class LaboratoryTests var data = await Laboratory.LoadAsync(null!, SystemClock.Instance, root, new TrialData(TrialSources.Research, Venues.Binance, ["ETHUSDT"], From.AddDays(10), From.AddDays(29)), CancellationToken.None).ConfigureAwait(false); Assert.AreEqual("USDT", data.Currency); - Assert.HasCount(20, data.Sessions); + Assert.HasCount(30, data.Sessions, "the days before the start are read too, for the indicators"); + Assert.AreEqual(20, data.Sessions.Count(d => d >= From.AddDays(10)), "the trial itself covers its 20 days"); Assert.AreEqual("ETH", data["ETHUSDT"]!.Spec.BaseCurrency); Assert.IsTrue(data.IsCrypto); } diff --git a/tests/Anubis.Tests/ProtocolTests.cs b/tests/Anubis.Tests/ProtocolTests.cs new file mode 100644 index 0000000..5ed19da --- /dev/null +++ b/tests/Anubis.Tests/ProtocolTests.cs @@ -0,0 +1,216 @@ +using Anubis.Backtest; +using Anubis.Data; +using Anubis.Platform; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The honest backtests of the base strategies (issue #44; SPEC 8.1, 12.2, 12.3): the Binance history in euro, the +/// protocol on both universes of crypto_trend, the expected path, the report and the outcome files read at the first +/// start. +/// +[TestClass] +public sealed class ProtocolTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + private static ResearchBar Bar(DateOnly day, decimal close) => + new(new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), close, close * 1.01m, close * 0.99m, close, 100m) { QuoteVolume = close * 100m }; + + private static FxRate Usd(DateOnly day, decimal rate) => new("EUR", "USD", day, rate, "ecb"); + + [TestMethod] + public void UsdtPricesBecomeEurosWithTheRateOfTheDayOrTheLastBefore() + { + var friday = new DateOnly(2024, 3, 1); + var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m) }; + var rates = new[] { Usd(friday, 1.10m), Usd(friday.AddDays(3), 1.25m) }; + + var euro = EuroHistory.Convert(bars, rates); + + Assert.HasCount(3, euro); + Assert.AreEqual(100m, euro[0].Close); + Assert.AreEqual(109.090909090909m, euro[1].Close); // Saturday: Friday's rate. + Assert.AreEqual(80m, euro[2].Close); + Assert.AreEqual(100m, euro[0].Volume, "the volume is in coins: it does not change"); + Assert.AreEqual(10_000m, euro[0].QuoteVolume); + Assert.AreEqual("BTCEUR", EuroHistory.SymbolOf("BTCUSDT")); + } + + [TestMethod] + public void ABarWithoutARecentRateIsDropped() + { + var day = new DateOnly(2024, 3, 1); + var bars = Enumerable.Range(-1, EuroHistory.MaxRateAgeDays + 3).Select(i => Bar(day.AddDays(i), 1m)).ToList(); + + var euro = EuroHistory.Convert(bars, [Usd(day, 1m)]); + + Assert.HasCount(EuroHistory.MaxRateAgeDays + 1, euro, "before the first rate and after a week without rates there is no price in euro"); + Assert.AreEqual(day, DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime)); + Assert.AreEqual(day.AddDays(EuroHistory.MaxRateAgeDays), DateOnly.FromDateTime(euro[^1].OpensAt.UtcDateTime)); + } + + [TestMethod] + public void AHoleOfMoreThanAWeekEndsTheSeriesBecauseWhatFollowsIsAnotherCoin() + { + var day = new DateOnly(2022, 5, 10); + var bars = new[] { Bar(day, 1m), Bar(day.AddDays(1), 0.0001m), Bar(day.AddDays(1 + EuroHistory.MaxGapDays + 1), 5m), Bar(day.AddDays(2 + EuroHistory.MaxGapDays + 1), 6m) }; + var rates = Enumerable.Range(0, 20).Select(i => Usd(day.AddDays(i), 1m)).ToList(); + + var euro = EuroHistory.Convert(bars, rates); + + Assert.HasCount(2, euro, "the relaunch under the same ticker is not the coin that collapsed"); + Assert.AreEqual(0.0001m, euro[^1].Close); + } + + [TestMethod] + public void TheExpectedPathIsTheCompoundedPercentileAndRepeatsWithTheSameSeed() + { + var steady = PathBootstrap.Percentile([0.01, 0.01, 0.01], 3, 0.05, 50, 5, 1); + Assert.AreEqual(0.01, steady[0], 1e-12); + Assert.AreEqual(0.030301, steady[2], 1e-12); + + var random = new Random(7); + var returns = Enumerable.Range(0, 500).Select(_ => (random.NextDouble() - 0.48) * 0.06).ToArray(); + var p5 = PathBootstrap.Percentile(returns, 100, 0.05, 500, 20, 3); + var median = PathBootstrap.Percentile(returns, 100, 0.50, 500, 20, 3); + CollectionAssert.AreEqual(p5.ToList(), PathBootstrap.Percentile(returns, 100, 0.05, 500, 20, 3).ToList()); + Assert.IsTrue(p5.Zip(median).All(x => x.First <= x.Second), "the 5th percentile is never above the median"); + Assert.IsLessThan(p5[9], p5[99], "the bad tail widens with time"); + } + + [TestMethod] + public async Task TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome() + { + var folder = TempFolder.Create("protocol"); + try + { + var store = new ResearchStore(folder); + var random = new Random(11); + var start = new DateOnly(2017, 8, 1); + var end = new DateOnly(2020, 12, 31); + foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP", "LTC" }) + { + var price = 100m; + var bars = new List(); + for (var day = start; day <= end; day = day.AddDays(1)) + { + price *= 1m + (decimal)((random.NextDouble() - 0.49) * 0.08); + bars.Add(Bar(day, Math.Round(price, 6)) with { Volume = 1_000_000m }); + } + + await store.WriteAsync(Venues.Binance, coin + "USDT", Timeframes.Day, bars, _none); + } + + var rates = new List(); + for (var day = start; day <= end; day = day.AddDays(1)) + { + if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + rates.Add(Usd(day, 1.15m)); + } + } + + var converted = await EuroHistory.ConvertAllAsync(store, rates, _none); + Assert.HasCount(5, converted); + + var outcome = await CryptoTrendProtocol.RunAsync(folder, end, new DateTimeOffset(2021, 1, 2, 0, 0, 0, TimeSpan.Zero), null, _none); + + Assert.HasCount(2, outcome.Runs); + Assert.HasCount(5, outcome.Runs[0].Report.Instruments); + CollectionAssert.AreEqual(CryptoTrendProtocol.Narrow.ToList(), outcome.Runs[1].Report.Instruments.Select(i => i.Symbol).ToList()); + Assert.AreEqual("EUR", outcome.Runs[0].Report.Currency); + Assert.AreEqual(outcome.Runs[0].Report.Variants.Count + outcome.Runs[1].Report.Variants.Count, outcome.Runs[1].Report.TrialsCounted, + "the second universe counts the variants of the first as tries"); + Assert.IsTrue(outcome.Runs.All(r => r.Report.LookAhead.Passed), "no decision changes when later data is added"); + + var q = outcome.Qualification; + Assert.AreEqual(outcome.Runs.All(r => r.Report.Passed), q.Passed); + Assert.AreEqual(CryptoTrendProtocol.ReportPath, q.Report); + Assert.HasCount(CryptoTrendProtocol.PathDays, q.ExpectedPathP5); + Assert.AreEqual(Math.Round((decimal)outcome.Runs[0].Report.Metrics.MaxDrawdown, 4), q.MaxDrawdown); + Assert.IsTrue(q.ExpectedSlippageBp is >= 5m and <= 15m); + Assert.AreEqual(2m * (0.002m + (q.ExpectedSlippageBp / 10_000m)), q.RoundTripCost); + if (!q.Passed) + { + StringAssert.Contains(q.Verdict, "Resta in osservazione"); + } + + var markdown = ProtocolReport.Markdown(outcome, "crypto_trend", ["dati di prova"], "anubis backtest base"); + foreach (var part in new[] { "# Backtest di `crypto_trend`", "## Universo ampio", "## BTC, ETH e SOL", "Comprare e tenere", "×2", "×3", "**Per anno**", + "Deflated Sharpe Ratio", "convertiti in euro con il cambio BCE", "dati di prova" }) + { + StringAssert.Contains(markdown, part); + } + + var json = BacktestOutcomes.ToJson(q); + Assert.AreEqual(q.Verdict, System.Text.Json.JsonSerializer.Deserialize(json, Qualification.Json)!.Verdict); + StringAssert.Contains(json, "\"expected_path_p5\""); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + public void AFailedCheckIsDescribedInPlainItalian() + { + var check = new ReportCheck(ReportCheckKeys.Drawdown, "Calo massimo", 0.382, "≤", 0.25, "percent", false); + + Assert.AreEqual("calo massimo 38,2%, serve ≤ 25%", CryptoTrendProtocol.Describe(check, System.Globalization.CultureInfo.GetCultureInfo("it-IT"))); + } + + [TestMethod] + public void EveryBaseStrategyHasItsOutcomeFileBuiltIn() + { + foreach (var (strategy, _, _) in StrategyNames.Base) + { + var outcome = BacktestOutcomes.Find(strategy); + Assert.IsNotNull(outcome, strategy); + Assert.AreEqual("docs/backtests/" + strategy + ".md", outcome.Report); + Assert.IsTrue(File.Exists(Path.Combine(RepositoryRoot(), outcome.Report)), "the report of " + strategy + " is in the repository"); + } + + foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) + { + var outcome = BacktestOutcomes.Find(strategy)!; + Assert.IsFalse(outcome.Passed, "without the Alpaca history the stock strategies cannot pass"); + StringAssert.Contains(outcome.Verdict, "chiavi Alpaca"); + } + } + + [TestMethod] + public async Task AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome() + { + await using var rig = await TradingRig.CreateAsync(); + await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none); + var stages = new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + foreach (var (strategy, _, _) in StrategyNames.Base) + { + await stages.ApplyQualificationAsync(strategy, BacktestOutcomes.Find(strategy)!, _none); + } + + foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) + { + var stage = await stages.GetAsync(strategy, _none); + Assert.AreEqual(StrategyStages.Observation, stage!.Stage); + StringAssert.Contains(stage.Qualification!.Verdict, "chiavi Alpaca"); + } + + var crypto = (await stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual(BacktestOutcomes.Find(StrategyNames.CryptoTrend)!.Passed ? StrategyStages.Simulation : StrategyStages.Observation, crypto.Stage); + } + + private static string RepositoryRoot() + { + var folder = new DirectoryInfo(AppContext.BaseDirectory); + while (folder is not null && !File.Exists(Path.Combine(folder.FullName, "Anubis.slnx"))) + { + folder = folder.Parent; + } + + return folder?.FullName ?? throw new InvalidOperationException("Repository root not found"); + } +} -- 2.54.1 From 13f9c42f61a0d8941e0b605c82e3aac1974cc7a4 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 16:14:44 +0100 Subject: [PATCH 4/8] Add the Operazioni, Strategie and Rischio screens (refs #45) The three screens follow mockups 03, 04 and 07. Operazioni shows the balance of the closed trades, filters, a CSV export, and for each trade why it was bought and sold. The reasons come from the decision codes through fixed Italian templates. Strategie shows the four stages towards real money, a card per strategy with its requirements, the procedure of SPEC 12.4, and why each strategy in observation waits. A strategy that failed its backtest cannot be moved into the simulation. Rischio shows the emergency switch, the automatic blocks, the use of each limit, the fall from the peak, the scenarios and the risk events. Stop, close and restart now go through the risk engine. A restart is refused while the STOP file exists. Impostazioni gains the limits, the day-trade guard and the scenarios. Lowering a limit is always allowed. Raising a limit or the entrusted capital while a strategy uses real money needs the phrase and the password. The demo now holds the decisions behind its trades, the 58 days of simulation and the indices of its curves, so it matches the mockups. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/Assets/app.css | 151 +++++++++ src/Anubis.Server/Components/Icon.razor | 9 + .../Components/Pages/Impostazioni.razor | 76 ++++- .../Components/Pages/Operazioni.razor | 230 ++++++++++++- .../Components/Pages/Rischio.razor | 306 ++++++++++++++++-- .../Components/Pages/Strategie.razor | 231 ++++++++++++- src/Anubis.Server/Endpoints.cs | 40 ++- src/Anubis.Server/Forms.cs | 163 +++++++++- src/Anubis.Server/ReasonTexts.cs | 124 +++++++ src/Anubis.Server/RiskView.cs | 134 ++++++++ src/Anubis.Server/StrategiesView.cs | 166 ++++++++++ src/Anubis.Server/TradesView.cs | 198 ++++++++++++ src/Anubis/Demo/DemoMode.cs | 79 ++++- src/Anubis/Trading/RiskEngine.cs | 4 + src/Anubis/Trading/Stages.cs | 29 ++ tests/Anubis.Tests/StrategyScreensTests.cs | 179 ++++++++++ 16 files changed, 2085 insertions(+), 34 deletions(-) create mode 100644 src/Anubis.Server/ReasonTexts.cs create mode 100644 src/Anubis.Server/RiskView.cs create mode 100644 src/Anubis.Server/StrategiesView.cs create mode 100644 src/Anubis.Server/TradesView.cs create mode 100644 tests/Anubis.Tests/StrategyScreensTests.cs diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 2e81dd9..c445c49 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -224,6 +224,7 @@ textarea { .panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; } .panel > h3, .panel h3 { margin: 20px 0 8px; } .note { color: var(--text-3); font-size: 13px; line-height: 18px; } +h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; } .hint { color: var(--text-3); font-size: 13px; line-height: 18px; } .empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; } .empty-title { color: var(--text); font-weight: 600; font-size: 15px; } @@ -389,6 +390,137 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .currency-lines dd { margin: 0; text-align: right; } .fx-warning { margin-top: 16px; } +/* ---- Operazioni ---- */ +.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } +.trades-head .lead { margin-top: 0; } +.trades-head .big-number { margin-top: 8px; } +.trades-head .note { margin-top: 10px; } +.trades-head h2 { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; } +.cells { margin-bottom: 0; } +.cells > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.cells dt { color: var(--text-3); font-size: 13px; } +.cells dd { margin: 0; display: flex; flex-direction: column; gap: 2px; } +.cells dd strong { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; font-variant-numeric: tabular-nums; } +.cells dd span { color: var(--text-3); font-size: 13px; } +.result-bars { display: block; width: 100%; height: 170px; margin-top: 16px; } +.result-bars .axis { stroke: var(--rule); stroke-width: 1; vector-effect: non-scaling-stroke; } +.result-bars rect.gain { fill: var(--gain); } +.result-bars rect.loss { fill: var(--loss); } +.bars-scale { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; } +.filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; } +.filters .btn:last-child { margin-left: auto; } +.search { position: relative; flex: 1 1 240px; display: flex; align-items: center; } +.search .icon { position: absolute; left: 14px; color: var(--text-3); pointer-events: none; } +.search input { width: 100%; padding-left: 40px !important; } +.trades { display: flex; flex-direction: column; margin: 0 -22px; } +.trade-row { + display: grid; grid-template-columns: 116px minmax(0, 1fr) 128px 70px 176px 146px minmax(0, 1.7fr) 20px; + gap: 12px; align-items: center; padding: 14px 22px; border-bottom: 1px solid var(--rule-inner); font-variant-numeric: tabular-nums; +} +.trade-header { color: var(--text-3); font-size: 13px; padding-top: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--rule); } +.trade-header::after { content: ""; } +.trade-row .num { text-align: right; } +.trade summary { list-style: none; cursor: pointer; } +.trade summary::-webkit-details-marker { display: none; } +.trade summary::after { + content: ""; justify-self: end; width: 8px; height: 8px; margin-right: 4px; + border-right: 2px solid var(--text-2); border-bottom: 2px solid var(--text-2); transform: rotate(45deg) translateY(-3px); +} +.trade[open] summary::after { transform: rotate(-135deg) translateY(-3px); } +.trade summary:hover { background: var(--surface-2); } +.trade[open] { background: var(--surface-2); } +.trade[open] summary { border-bottom: 0; } +.why { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 4px 22px 22px; border-bottom: 1px solid var(--rule-inner); } +.why-card { background: var(--surface); border: 1px solid var(--rule); border-radius: 12px; padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; } +.why-card h3 { margin: 0 !important; } +.why-card .account-lines { margin-top: 4px; } +.checks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.checks li { display: flex; align-items: flex-start; gap: 10px; } +.checks .icon { margin-top: 2px; } +.checks .ok .icon { color: var(--gain); } +.checks .warn { color: var(--attention); } +.checks .wait .icon { color: var(--text-2); } +.pager { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 18px; } +.pager .note { margin-right: auto; } + +/* ---- Strategie ---- */ +.stages { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; } +.stages li { border: 1px solid var(--rule); border-radius: 12px; padding: 16px 18px; display: flex; flex-direction: column; gap: 6px; } +.stages li > strong { font-size: 15px; } +.stages li > p { color: var(--text-2); font-size: 13.5px; } +.stages li.here { border: 2px solid var(--text); background: var(--surface-2); padding: 15px 17px; } +.stages .step { border: 1.5px solid var(--text); background: transparent; width: 24px; height: 24px; font-size: 13px; font-weight: 650; } +.stages .here .step { background: var(--text); color: var(--surface); } +.stage-count { display: flex; align-items: center; gap: 4px; margin-top: auto; padding-top: 6px; color: var(--text) !important; } +.stage-count .swatch { margin-right: 0; } +.stage-count strong { margin-left: 4px; } +.strategy { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1.15fr); padding: 0; } +.strategy > div { padding: 24px 26px; min-width: 0; display: flex; flex-direction: column; gap: 12px; } +.strategy > div + div { border-left: 1px solid var(--rule); } +.strategy-about h2 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 20px; line-height: 28px; } +.strategy-about h2 .tag { margin-left: 10px; background: var(--info-bg); color: var(--link); } +.strategy-about > p:first-of-type { font-size: 15px; line-height: 22px; } +.strategy-about ul { margin: 0; padding-left: 20px; color: var(--text-2); display: flex; flex-direction: column; gap: 4px; } +.strategy-about .note { margin-top: auto; } +.strategy-number { display: flex; align-items: center; gap: 14px; font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } +.spark { display: block; width: 100%; height: 80px; } +.strategy-result .account-lines { grid-template-columns: max-content minmax(0, 1fr); column-gap: 16px; } +.strategy-result .account-lines dd { overflow-wrap: anywhere; } +.spark polyline { fill: none; stroke-width: 2; stroke-linejoin: round; } +.strategy-steps h3 { margin: 0 !important; } +.strategy-steps form { margin: 0; } +.confirm-live summary { list-style: none; align-self: flex-start; display: inline-flex; } +.confirm-live summary::-webkit-details-marker { display: none; } +.confirm-live[open] summary { margin-bottom: 12px; } +.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px 16px; align-items: end; } +.form-grid > p { grid-column: 1 / -1; } +.form-grid label { display: flex; flex-direction: column; gap: 6px; font-weight: 550; } +.form-grid .btn { justify-self: start; } +.confirm-live .form-grid { grid-template-columns: 1fr; } +.plain { border-top: 2px solid var(--text); padding-top: 18px; } +.plain > h2 { margin-bottom: 8px; } +.observing { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); margin: 0; } +.observing dt, .observing dd { margin: 0; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); } +.observing dt { font-weight: 650; padding-right: 32px; } +.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); } +.observing form { margin: 0; flex: none; } +.attention { display: inline-flex; align-items: center; gap: 6px; } + +/* ---- Rischio ---- */ +.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; } +.risk-top .panel { display: flex; flex-direction: column; gap: 12px; } +.risk-top .panel-head { margin-bottom: 0; } +.risk-top p { color: var(--text-2); } +.btn-danger-solid { background: var(--loss); border-color: var(--loss); color: var(--surface); } +.btn-danger-solid:hover { background: var(--loss); opacity: .9; } +.status-line.gain { display: flex; align-items: center; gap: 8px; color: var(--gain); font-weight: 600; font-size: 14px; white-space: normal; } +.blocks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.blocks li { display: flex; align-items: flex-start; gap: 10px; } +.blocks .icon { margin-top: 2px; } +.block-list { margin: 0; display: flex; flex-direction: column; } +.block-list dt { color: var(--text-3); font-size: 13px; padding-top: 12px; border-top: 1px solid var(--rule-inner); } +.block-list dd { margin: 0 0 12px; display: flex; flex-direction: column; gap: 2px; } +.block-list dd span { color: var(--text-2); font-size: 13.5px; } +.limits td.wide { width: 24%; vertical-align: middle; } +.usage { display: block; position: relative; height: 6px; border-radius: 3px; background: var(--track); overflow: hidden; } +.usage span { display: block; height: 100%; border-radius: 3px; background: var(--text-2); min-width: 2px; } +.usage.high span { background: var(--attention); } +.drawdown { display: block; width: 100%; height: auto; margin-top: 12px; overflow: visible; } +.drawdown .axis { stroke: var(--rule); stroke-width: 1; } +.drawdown .tick { fill: var(--text-3); font-size: 12px; } +.drawdown .area { fill: var(--loss); opacity: .1; } +.drawdown .line { fill: none; stroke: var(--loss); stroke-width: 2; stroke-linejoin: round; } +.drawdown .dot { fill: var(--loss); } +.drawdown .label { fill: var(--text); font-size: 12.5px; font-weight: 650; } +.columns .panel .notice { margin-top: 12px; } +.never { list-style: none; margin: 0; padding: 0; } +.never li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); } +.never .icon { color: var(--text-2); } +.events { display: grid; grid-template-columns: 140px minmax(0, 1fr); margin: 0 0 12px; } +.events dt, .events dd { margin: 0; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); } +.events dt { color: var(--text-3); } +.limits-form { max-width: none; margin-bottom: 8px; } + /* ---- Service pages ---- */ .service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; } .service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; } @@ -438,6 +570,25 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .panel-tools { width: 100%; justify-content: space-between; } .facts { grid-template-columns: 1fr; gap: 2px; } .facts dd { margin-bottom: 8px; } + .panel > h2 { flex-direction: column; align-items: flex-start; gap: 4px; } + .trades-head .cells { grid-template-columns: 1fr 1fr; } + .trades { margin: 0 -18px; } + .trade-row { grid-template-columns: minmax(0, 1fr) auto 16px; gap: 4px 12px; padding: 12px 18px; } + .trade-row > span:first-child { grid-column: 1 / -1; color: var(--text-3); font-size: 13px; } + .trade-row .wide, .trade-header, .limits .wide, .filters .btn:last-child { display: none; } + .why { grid-template-columns: 1fr; padding: 4px 18px 18px; } + .filters > label:not(.search) { flex: 1 1 140px; } + .filters select { width: 100%; } + .stages { grid-template-columns: 1fr 1fr; gap: 10px; } + .strategy { grid-template-columns: 1fr; } + .strategy > div { padding: 18px; } + .strategy > div + div { border-left: 0; border-top: 1px solid var(--rule); } + .risk-top { grid-template-columns: 1fr; gap: 14px; } + .observing { grid-template-columns: 1fr; } + .observing dt { border-bottom: 0; padding-bottom: 0; } + .observing dd { flex-direction: column; align-items: flex-start; } + .events { grid-template-columns: 1fr; } + .events dt { border-bottom: 0; padding-bottom: 0; } .bottombar { display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0; padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10; diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor index 1de3da8..5267197 100644 --- a/src/Anubis.Server/Components/Icon.razor +++ b/src/Anubis.Server/Components/Icon.razor @@ -80,6 +80,15 @@ case "lock": break; + case "search": + + break; + case "ban": + + break; + case "tick": + + break; case "logout": break; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 52a35e8..cf5d79b 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -21,6 +21,9 @@ "chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.", "chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.", "capitale" => "Capitale affidato aggiornato e diviso tra le strategie.", + "limiti" => "Limiti di rischio salvati.", + "rischio" => "Impostazione del rischio salvata.", + _ => "Fatto.", })

} @@ -30,7 +33,7 @@ }
@@ -135,7 +138,56 @@ }
+
+

Rischio

+

I limiti valgono per tutte le strategie insieme. Abbassarli è sempre possibile. @(_anyLive ? "Una strategia usa soldi veri: per alzarne uno servono la frase e la password." : "Finché nessuna strategia usa soldi veri, puoi anche alzarli.")

+ @if (!Shell.IsDemo) + { +
+ + @foreach (var l in _limits) + { + + } + @if (_anyLive) + { + + + + } + + +

Protezione day trade

+
+ + + + + +

Scenari «Se succedesse domani»

+
+ + + + + + } + else + { +
+ @foreach (var l in _limits) + { +
@l.Label
@l.Value
+ } +
+ } +
+
+

Dati

@if (Host.Services!.MarketData is not { } market) { @@ -302,7 +354,13 @@ private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList Keys, AccountState? State, EntrustedCapital? Entrusted, IReadOnlyList Strategies); + private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly); + private readonly List _limits = []; + private bool _anyLive; + private string _pdt = "off"; + private string _scenarios = ""; private IReadOnlyList _sources = []; + private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private List _history = []; private IReadOnlyList _backups = []; @@ -328,6 +386,16 @@ _history = await services.Settings.HistoryAsync(null, 50, ct); _meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct); _sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct); + foreach (var definition in Anubis.Risk.RiskSettings.Limits) + { + var value = await services.Settings.GetAsync(definition.Key, ct); + _limits.Add(new LimitField(definition.Key, definition.Label, value.Value, value.ReadOnly)); + } + + _pdt = (await services.Settings.GetAsync(Anubis.Risk.RiskSettings.PdtGuard.Key, ct)).Value; + _scenarios = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, ct)).Value; + _anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct); + _backups = services.Backups.List(); var ledger = new Ledger(services.Db, Clock); var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock)); @@ -372,6 +440,12 @@ "importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.", "cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.", "capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.", + "limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.", + "ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.", + "frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.", + "password-rischio" => "Password o codice non corretti. Non ho cambiato nulla.", + "scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.", + _ => PasswordMessages.For(Errore), }; diff --git a/src/Anubis.Server/Components/Pages/Operazioni.razor b/src/Anubis.Server/Components/Pages/Operazioni.razor index 12359a1..080259c 100644 --- a/src/Anubis.Server/Components/Pages/Operazioni.razor +++ b/src/Anubis.Server/Components/Pages/Operazioni.razor @@ -1,5 +1,233 @@ +@inherits LoadedComponent @page "/operazioni" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading Operazioni · Anubis -Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita. +@{ + var v = _view; + var c = _currency; + var f = _filter; +} +@if (v.Total == 0) +{ + Qui compare ogni operazione quando si chiude: quanto ha reso, quanto è durata e perché il bot ha comprato e venduto. Le strategie in osservazione non operano: le vedi in Strategie. +} +else +{ +
+
+

Per ogni euro perso ne ha guadagnati

+

@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")

+

Guadagni incassati finora: @Shell.Money(v.Net, c, withSign: true)@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")

+
+
In guadagno
@v.Winners su @v.Matching@Format.Percent(v.Matching == 0 ? 0 : (decimal)v.Winners / v.Matching * 100m)
+
Guadagno medio
@(v.Winners == 0 ? "—" : Shell.Money(v.Gains / v.Winners, c, withSign: true))su @v.Winners @(v.Winners == 1 ? "operazione" : "operazioni")
+
Perdita media
@(v.Losers == 0 ? "—" : Shell.Money(v.Losses / v.Losers, c, withSign: true))su @v.Losers @(v.Losers == 1 ? "operazione" : "operazioni")
+
Commissioni
@Shell.Money(v.Fees, c)già tolte
+
+
+
+

Risultato di ogni operazione dalla prima all'ultima; in alto i guadagni, in basso le perdite

+ @if (v.Bars.Count > 0) + { + var max = Math.Max(1m, v.Bars.Max(b => Math.Abs(b.Eur))); + var width = 600m / v.Bars.Count; + var best = v.Bars.MaxBy(b => b.Eur); + var worst = v.Bars.MinBy(b => b.Eur); + + + @for (var i = 0; i < v.Bars.Count; i++) + { + var b = v.Bars[i]; + var h = Math.Abs(b.Eur) / max * 70m; + + } + +

@Day(v.Bars[0].At)@Day(v.Bars[^1].At)

+

La migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol.

+ } + else + { +

Nessuna operazione con questi filtri.

+ } +
+
+ +
+

Operazioni chiuse

+
+ + + + + + + Esporta CSV +
+ + @if (v.Rows.Count == 0) + { +

Nessuna operazione con questi filtri.

+ } + else + { +
+ + @foreach (var t in v.Rows) + { + var gain = t.RealizedEur >= 0; +
+ + @When(t.ClosedAt) + @t.Symbol @t.Name + @StrategyNames.Label(t.Strategy) + @Duration(t) + @Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4) → @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4) + @Shell.Money(t.RealizedEur, c, withSign: true) (@Format.Percent(t.Percent, 2, withSign: true)) + @t.ExitReason + +
+
+

Perché l'ho comprata

+ @if (t.Bought.Count == 0) + { +

Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.

+ } + else + { +
    + @foreach (var line in t.Bought) + { +
  • @line.Text
  • + } +
+ } +
+
+

Perché l'ho venduta

+ @if (t.Sold.Count == 0) + { +

@t.ExitReason.

+ } + else + { +
    + @foreach (var line in t.Sold) + { +
  • @line.Text
  • + } +
+ } + +
+
+
+ } +
+ var pages = (v.Matching + TradeFilter.PageSize - 1) / TradeFilter.PageSize; +
+ Mostrate @v.Rows.Count di @v.Matching + @if (f.Page > 1) + { + Più recenti + } + @if (f.Page < pages) + { + Più vecchie + } +
+ } +
+} + +@code { + private TradesView _view = null!; + private TradeFilter _filter = null!; + private string _currency = "EUR"; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "cerca")] public string? Cerca { get; set; } + [SupplyParameterFromQuery(Name = "conto")] public string? Conto { get; set; } + [SupplyParameterFromQuery(Name = "strategia")] public string? Strategia { get; set; } + [SupplyParameterFromQuery(Name = "esito")] public string? Esito { get; set; } + [SupplyParameterFromQuery(Name = "periodo")] public string? Periodo { get; set; } + [SupplyParameterFromQuery(Name = "pagina")] public string? Pagina { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + _currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); + _filter = TradeFilter.Parse(Cerca, Conto, Strategia, Esito, Periodo, Pagina); + _view = await TradesView.LoadAsync(services, Clock, _filter, null, ct); + } + + private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture); + + private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT")); + + private string When(DateTimeOffset at) => Capital(Local(at, "ddd d MMM, HH:mm")); + + private string Day(DateTimeOffset at) => Local(at, "d MMM"); + + private string Long(DateTimeOffset at) => Local(at, "dddd d MMMM, HH:mm"); + + private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..]; + + private static string Duration(TradeRow t) + { + var days = (int)Math.Round((t.ClosedAt - t.OpenedAt).TotalDays); + return days switch + { + < 1 => "in giornata", + 1 => "1 giorno", + _ => $"{days} giorni", + }; + } + + private static string Slip(decimal? bp) => bp is { } b ? Format.Percent(b / 100m, 2) : "—"; +} diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index 26eefce..07cb977 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -1,30 +1,298 @@ @inherits LoadedComponent @page "/rischio" @inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading +@using Anubis.Risk Rischio · Anubis -
-

Interruttore

- @if (_bot == "stopped") - { -

"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.

-
- - - - - } - else - { -

"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.

- } +@{ + var v = _view; + var c = _currency; +} +@if (_message is { } message) +{ +

@message

+} +
+
+
+

Interruttore d'emergenza

+ @BotText(v.BotState) +
+ @if (v.BotState == "stopped") + { +

+ @if (v.Risk.State.Tripped) + { + L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). + } + Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi. + @if (v.CloseAllPending) + { + Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura. + } +

+ @if (v.StopFile) + { +

C'è il file STOP nella cartella dei dati: toglilo, poi conferma qui la ripartenza.

+ } + @if (!Shell.IsDemo) + { +
+ + + + + } + } + else + { +

Con Ferma tutto annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.

+ @if (!Shell.IsDemo) + { +
+
+
+
+ } +

Anche un file chiamato STOP nella cartella dei dati ferma tutto entro un minuto.

+ } +
+
+

Blocchi automatici

+ @if (!v.AnyBlock) + { +

Nessun blocco attivo

+ } + else + { +
    + @if (v.Risk.State.Tripped) + { +
  • Interruttore scattato @(v.Risk.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.
  • + } + @if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow) + { +
  • Perdita del giorno oltre il limite: niente nuovi ingressi fino a @Moment(until).
  • + } + @if (v.Risk.State.WeeklyHalvingUntil is { } half && half > Clock.UtcNow) + { +
  • Perdita della settimana oltre il limite: rischio dimezzato fino a @Moment(half).
  • + } + @if (v.Risk.Measures.Drawdown <= -v.Limits.DrawdownHalf && !v.Risk.State.Tripped) + { +
  • Calo dal massimo oltre il @Format.Percent(v.Limits.DrawdownHalf * 100m, 0): rischio dimezzato.
  • + } + @if (v.BotState == "paused") + { +
  • Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.
  • + } + @if (v.BotState == "stopped" && !v.Risk.State.Tripped) + { +
  • Ferma tutto acceso.
  • + } +
+ } +
+
Prossimo blocco in programma
+ @if (v.NextCalendarBlock is { } next) + { +
@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")@next.Title: in quell'ora non apro posizioni.
+ } + else + { +
Nessun dato economico importante nei prossimi 14 giorni.
+ } +
Ultimo blocco scattato
+ @if (v.LastCalendarBlock is { } last) + { +
@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")@last.Title.
+ } + else + { +
Nessuno negli ultimi 14 giorni.
+ } +
Protezione day trade (azioni)
+
@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se il conto Alpaca vale meno di 25.000 $.")
+
+
+
+ +
+
+

I limiti Valgono per tutte le strategie insieme@(v.World == Worlds.Real ? ", sui conti veri" : ", nel mondo simulato"). Si cambiano dalle impostazioni, mai da soli.

+
+
+ + + + + + @foreach (var row in v.Rows) + { + + + + + + + + } + +
LimiteAdessoQuanto ne sto usandoSogliaSe lo supero
@row.Label@row.Now@if (row.Detail is { } d) { (@d)} + @if (row.Usage is { } u) + { + + } + @row.Threshold@row.Beyond
+
-Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio. + +
+
+

Quanto è sceso dal massimo

+

Ogni fotografia del patrimonio@(v.Risk.State.PeakFrom is { } from ? " dal " + Local(from, "d MMMM") : " dall'avvio"). A zero vuol dire che il portafoglio era al suo punto più alto.

+ @if (v.Drawdown.Count < 2) + { +

Ancora troppo poche fotografie per disegnare la curva.

+ } + else + { + var worst = v.Drawdown.MinBy(p => p.Drawdown)!; + var floor = Math.Min(-0.01m, worst.Drawdown * 1.2m); + var first = v.Drawdown[0].At; + var span = Math.Max(1d, (v.Drawdown[^1].At - first).TotalSeconds); + string X(DateTimeOffset at) => Css((decimal)((at - first).TotalSeconds / span) * 560m + 30m); + string Y(decimal d) => Css(10m + d / floor * 150m); + var points = string.Join(' ', v.Drawdown.Select(p => X(p.At) + "," + Y(p.Drawdown))); + + + 0% + @Format.Percent(floor * 100m, 1) + + + + @Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMM") + +

+ @if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m) + { + Le soglie del @Format.Percent(v.Limits.DrawdownHalf * 100m, 0) e del @Format.Percent(v.Limits.DrawdownStop * 100m, 0) sono fuori scala: il calo peggiore è rimasto sotto un quinto del limite. + } + else + { + A @Format.Percent(-v.Limits.DrawdownHalf * 100m, 0) il rischio si dimezza, a @Format.Percent(-v.Limits.DrawdownStop * 100m, 0) il bot si ferma e aspetta te. + } +

+ } +
+
+

Se succedesse domani

+

Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in Impostazioni.

+ @if (!v.HasPositions) + { +

Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.

+ } + else + { +
+ + + + @foreach (var s in v.Scenarios) + { + + + + + + } + +
ScenarioSenza stopCon gli stop
@s.Scenario.Label@Shell.Money(s.WithoutStops, c, decimals: 0) (@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true))@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0))
+
+

Gli stop non sono una garanzia: in un crollo improvviso il prezzo può saltarli. E nessuno stop protegge dal cambio.

+ } +
+
+ +
+
+

Cosa il bot non può fare, mai

+
    +
  • Usare soldi presi in prestito o vendere allo scoperto
  • +
  • Prelevare o spostare denaro: le chiavi dei conti non lo permettono
  • +
  • Toccare posizioni che non ha aperto lui
  • +
  • Passare ai soldi veri senza la tua conferma
  • +
  • Rischiare di più per recuperare una perdita
  • +
  • Comprare di più perché lo suggerisce una notizia o il modello
  • +
+
+
+
+

Eventi di rischio

+ @if (v.Events.Count == 0) + { + Nessun limite superato dall'avvio + } +
+ @if (v.Events.Count > 0) + { +
+ @foreach (var e in v.Events) + { +
@Local(e.At, "d MMMM")
+
@e.Message
+ } +
+ Vedi tutto nel diario + } +
+
@code { - private string _bot = "active"; + private RiskView _view = null!; + private string _currency = "EUR"; + private string? _message; - protected override async Task LoadAsync() => - _bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value; + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + _currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); + _view = await RiskView.LoadAsync(services, Clock, Shell.Zone, ct); + _message = Errore switch + { + "file-stop" => "Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire.", + "bot" => "Comando non ammesso nello stato attuale del bot.", + _ => null, + }; + } + + private static string BotText(string state) => state switch + { + "active" => "Il bot sta operando", + "paused" => "In pausa", + _ => "Fermo", + }; + + private static string RestartText(RiskView v) => v.Risk.State.Tripped + ? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?" + : "Riparti: il bot torna a operare. Confermi?"; + + private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture); + + private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT")); + + private string Moment(DateTimeOffset at) => Local(at, "d MMMM 'alle' HH:mm"); + + private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..]; } diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index 08c50f0..9b81385 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -1,5 +1,234 @@ +@inherits LoadedComponent @page "/strategie" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading Strategie · Anubis -Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati. +@{ + var v = _view; + var c = _currency; + var working = v.Cards.Where(x => x.Stage.Stage != StrategyStages.Observation).ToList(); + var watching = v.Cards.Where(x => x.Stage.Stage == StrategyStages.Observation).ToList(); +} +@if (_message is { } message) +{ +

@message

+} +
+

Il percorso verso i soldi veri Una strategia avanza solo se supera tutti i requisiti e se lo confermi tu. Se peggiora, torna indietro da sola.

+
    + @foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i))) + { + var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList(); +
  1. + @(i + 1) + @Capital(StrategyStages.Label(stage)) +

    @StageText(stage)

    +

    + @if (here.Count == 0) + { + Nessuna strategia + } + else + { + @foreach (var x in here) + { + + } + @(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie") + } +

    +
  2. + } +
+
+ +@foreach (var s in working) +{ + var up = s.ResultEur >= 0; +
+
+

@s.Name @(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

+

@s.Description

+
    + @foreach (var rule in s.Rules) + { +
  • @rule
  • + } +
+

Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).

+
+
+

@Shell.Money(s.ResultEur, c, withSign: true) @Format.Percent(s.ResultPercent, 2, withSign: true)

+ @if (s.Curve.Count > 1) + { + var min = s.Curve.Min(p => p.Index); + var max = s.Curve.Max(p => p.Index); + var range = Math.Max(0.0001m, max - min); + var points = string.Join(' ', s.Curve.Select((p, i) => Css(i * 300m / (s.Curve.Count - 1)) + "," + Css(70m - (p.Index - min) / range * 60m))); + + } + +
+
+

Requisiti per @(s.Stage.Stage == StrategyStages.Reduced ? "il reale pieno" : StrategyStages.IsLive(s.Stage.Stage) ? "restare con soldi veri" : "usare soldi veri")

+
    + @foreach (var r in s.Requirements) + { +
  • + + @r.Label: @r.Value (@r.Target) +
  • + } +
+ @if (s.Stage.ExitOnly) + { +

Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.

+ } + @if (StrategyStages.IsLive(s.Stage.Stage) && !Shell.IsDemo) + { +
+ + + + } + @if (s.Stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced) + { + var target = s.Stage.Stage == StrategyStages.Reduced ? "Passa al reale" : "Passa al reale ridotto"; + var broker = StrategyNames.BrokerOf(s.Stage.Strategy); + var accounts = v.LiveAccounts.Where(a => a.Broker == broker).ToList(); + if (!s.AllMet) + { +

@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")

+ @if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r))) + { +

Per ora non merita soldi veri. Resta in simulazione finché non migliora.

+ } + } + else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo) + { +

@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")

+ } + else + { +
+ @target +
+ +

Stai per affidare soldi veri a @s.Name@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Per confermare scrivi la frase qui sotto e la tua password.

+ + + + + + +
+ } + } + @if (s.Stage.Stage == StrategyStages.Simulation && !Shell.IsDemo) + { +
+ + + + } +
+
+} + +
+ + @if (watching.Count == 0) + { +

Nessuna strategia di base in osservazione.

+ } + else + { +
+ @foreach (var s in watching) + { + var report = StrategiesView.ReportOf(s.Stage); + var passed = s.Stage.Qualification?.Passed == true; +
@s.Name
+
+ @StrategiesView.ObservationReason(s.Stage)@if (report is not null) { Rapporto: @report} + @if (passed && !Shell.IsDemo) + { +
+ } + else if (!passed) + { + @(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test") + } +
+ } +
+ } +
+ +@code { + private StrategiesView _view = null!; + private string _currency = "EUR"; + private string? _message; + private bool _ok; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "ok")] + public string? Ok { get; set; } + + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + _currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); + _view = await StrategiesView.LoadAsync(services, Clock, TradingConsent.From(Host.Config).AllowLive, ct); + (_message, _ok) = (Ok, Errore) switch + { + ("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true), + ("osservazione", _) => ("Fatto: la strategia è in osservazione.", true), + ("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true), + (_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false), + (_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false), + (_, "password") => ("Password o codice non corretti.", false), + (_, "requisiti") => ("Non tutti i requisiti sono soddisfatti.", false), + (_, "conto") => ("Il conto scelto non è il conto reale del broker di questa strategia.", false), + (_, "consenso") => ("La configurazione d'avvio non consente i soldi veri.", false), + (_, { }) => ("Non è stato possibile completare la scelta: riprova.", false), + _ => (null, false), + }; + } + + private static string StageText(string stage) => stage switch + { + StrategyStages.Observation => "Produce solo segnali, nessun ordine.", + StrategyStages.Simulation => $"Ordini finti su prezzi veri, per almeno {StageBook.SimulationDays} giorni.", + StrategyStages.Reduced => "Soldi veri, con un quarto del capitale.", + _ => "Soldi veri, rischio pieno.", + }; + + private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..]; + + private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture); +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 7ac0522..406bd08 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -156,6 +156,17 @@ internal static partial class Endpoints "text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv"); }); + // The closed trades of the Operazioni screen as CSV (SPEC 13.6), with the same filters as the page. + api.MapGet("/operazioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? cerca, string? conto, string? strategia, string? esito, string? periodo, + CancellationToken ct) => + { + var filter = TradeFilter.Parse(cerca, conto, strategia, esito, periodo, null); + var view = await TradesView.LoadAsync(host.Services!, clock, filter, int.MaxValue, ct).ConfigureAwait(false); + var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); + return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv())).ToArray(), + "text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv"); + }); + // The external sources and the live feed: what is on, what is off and why (SPEC 4.4). api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) => { @@ -246,6 +257,7 @@ internal static partial class Endpoints "pause" or "pausa" when current == "active" => "paused", "resume" or "riprendi" when current == "paused" => "active", "stop" or "ferma" => "stopped", + "close" or "chiudi" => "stopped", "restart" or "riattiva" when current == "stopped" => "active", _ => null, }; @@ -256,7 +268,33 @@ internal static partial class Endpoints : "Comando non ammesso nello stato attuale del bot."); } - await settings.SetAsync(SettingsStore.BotState.Key, target, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + var by = context.User.Identity?.Name ?? "utente"; + if (host.Services.Trading is { Risk: { } risk } trading) + { + // The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops. + switch (command) + { + case "stop" or "ferma": + await risk.StopAllAsync(trading.Managers, by, "manual_stop", "Ferma tutto dall'interfaccia: annullo gli ordini in attesa e non apro posizioni. Gli stop restano.", ct) + .ConfigureAwait(false); + return (true, target); + case "close" or "chiudi": + await risk.CloseAllAsync(trading.Managers, by, ct).ConfigureAwait(false); + return (true, target); + case "restart" or "riattiva": + try + { + await risk.RestartAsync(by, ct).ConfigureAwait(false); + return (true, target); + } + catch (InvalidOperationException ex) + { + return (false, ex.Message); + } + } + } + + await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false); return (true, target); } diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index e13a5ed..92f8e34 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -35,6 +35,9 @@ internal static partial class Forms signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); signed.MapPost("/capitale/{broker}", SetCapitalAsync); signed.MapPost("/laboratorio", PlanTrialAsync); + signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); + signed.MapPost("/rischio/limiti", SetLimitsAsync); + signed.MapPost("/rischio/{key}", SetRiskSettingAsync); } private static string Back(IFormCollection form, string fallback) @@ -173,8 +176,8 @@ internal static partial class Forms private static async Task BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/"); - var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false); - return Results.Redirect(ok ? back : With(back, "errore", "bot")); + var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false); + return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot")); } /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. @@ -309,6 +312,13 @@ internal static partial class Forms return Results.Redirect(back + "?errore=importo#conti"); } + // More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4). + if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before && + await RaiseRefusalAsync(host.Services!, broker, form, ct).ConfigureAwait(false) is { } refusal) + { + return Results.Redirect(back + "?errore=" + refusal + "#conti"); + } + try { await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); @@ -325,6 +335,155 @@ internal static partial class Forms return Results.Redirect(back + "?ok=capitale#conti"); } + /// + /// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real + /// money only through the procedure, with the phrase, the password and the second factor checked by the stage book. + /// + private static async Task StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy)) + { + return Results.Redirect("/strategie?errore=scelta"); + } + + if (services.Trading?.Stages is not { } stages) + { + return Results.Redirect("/strategie?errore=motore"); + } + + var by = context.User.Identity?.Name ?? "utente"; + try + { + switch (choice) + { + case "simulazione": + var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false); + if (stage?.Qualification is not { Passed: true }) + { + // A strategy that did not pass its backtest stays in observation (SPEC 12.3). + return Results.Redirect("/strategie?errore=backtest"); + } + + await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=simulazione"); + case "osservazione": + var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false); + if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage)) + { + await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=simulazione"); + } + + await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=osservazione"); + case "reale" when Guid.TryParse(form["conto"].ToString(), out var account): + var code = form["codice"].ToString(); + await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(), + string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=reale"); + default: + return Results.Redirect("/strategie?errore=scelta"); + } + } + catch (Anubis.Trading.LiveConfirmationException ex) + { + var error = ex.Code switch + { + "phrase" => "frase", + "password" => "password", + "requirements" => "requisiti", + "account" => "conto", + Anubis.Risk.RiskReasons.NoConsent => "consenso", + _ => "scelta", + }; + return Results.Redirect("/strategie?errore=" + error); + } + } + + /// + /// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy + /// has real money needs the phrase, the password and the second factor (SPEC 12.4). + /// + private static async Task SetLimitsAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (host.IsDemo || host.Services is not { } services) + { + return Results.Redirect(back + "?errore=motore#rischio"); + } + + var current = new Dictionary(StringComparer.Ordinal); + var next = new Dictionary(StringComparer.Ordinal); + foreach (var definition in Anubis.Risk.RiskSettings.Limits) + { + current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value; + var typed = form[definition.Key].ToString().Trim().Replace(',', '.'); + if (typed.Length == 0) + { + next[definition.Key] = current[definition.Key]; + continue; + } + + if (definition.Check?.Invoke(typed) is not null) + { + return Results.Redirect(back + "?errore=limite#rischio"); + } + + next[definition.Key] = typed; + } + + var limits = Anubis.Risk.RiskSettings.From(k => next[k]); + if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss) + { + return Results.Redirect(back + "?errore=ordine-limiti#rischio"); + } + + if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits)) + { + if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal) + { + return Results.Redirect(back + "?errore=" + refusal + "#rischio"); + } + } + + var by = context.User.Identity?.Name ?? "utente"; + foreach (var (key, value) in next.Where(n => n.Value != current[n.Key])) + { + await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false); + } + + return Results.Redirect(back + "?ok=limiti#rischio"); + } + + /// The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure. + private static async Task SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key) + { + return Results.Redirect(back + "?errore=impostazione#rischio"); + } + + var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false); + return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio"); + } + + /// Null when more risk may go ahead; otherwise the error code for the page. + private static async Task RaiseRefusalAsync(AppServices services, string? broker, IFormCollection form, CancellationToken ct) + { + var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false)); + try + { + var code = form["codice"].ToString(); + await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false); + return null; + } + catch (Anubis.Trading.LiveConfirmationException ex) + { + return ex.Code == "phrase" ? "frase-rischio" : "password-rischio"; + } + } + /// /// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it. /// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address. diff --git a/src/Anubis.Server/ReasonTexts.cs b/src/Anubis.Server/ReasonTexts.cs new file mode 100644 index 0000000..8f4fbd5 --- /dev/null +++ b/src/Anubis.Server/ReasonTexts.cs @@ -0,0 +1,124 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Trading; + +namespace Anubis.Server; + +/// +/// The fixed templates that turn the reason codes of the decisions table into plain Italian (SPEC 5.2): the "why" +/// card of a trade and the diary use these, never free text written at decision time. An unknown code is shown as +/// it is, so nothing is ever hidden. +/// +internal static class ReasonTexts +{ + private static readonly Dictionary Texts = new(StringComparer.Ordinal) + { + // Strategies. + ["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.", + ["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.", + ["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.", + ["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.", + ["trend_stop"] = "Lo stop mobile è salito con il prezzo.", + ["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.", + ["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.", + ["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.", + ["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.", + ["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.", + ["momentum_stop"] = "Lo stop di protezione è stato aggiornato.", + ["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.", + ["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.", + ["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.", + ["meanrev_exit_earnings"] = "Uscita prima della trimestrale.", + ["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.", + // Exits recorded on the trade. + ["stop"] = "Stop di protezione raggiunto.", + ["exit"] = "Uscita decisa dalla strategia.", + ["signal"] = "Uscita sul segnale della strategia.", + ["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", + ["adjustment"] = "Rettifica dopo l'allineamento con il conto.", + // Correctives. + ["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.", + ["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.", + ["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.", + // Risk. + ["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.", + ["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.", + ["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.", + ["bot_paused"] = "Bot in pausa: niente nuovi ingressi.", + ["bot_stopped"] = "Bot fermato con \"Ferma tutto\".", + ["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.", + ["position_limit"] = "Ridotto al peso massimo di una posizione.", + ["crypto_limit"] = "Quota delle crypto sul totale al limite.", + ["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.", + ["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.", + ["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.", + ["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.", + ["clock_skew"] = "Orologio non allineato con quello del broker.", + ["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.", + ["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.", + ["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.", + ["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.", + ["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.", + ["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.", + ["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.", + ["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.", + ["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.", + ["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.", + ["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.", + ["unknown_instrument"] = "Strumento sconosciuto.", + }; + + // The exits in the few words of a table column; the full sentence stays for the "why" card. + private static readonly Dictionary ShortExits = new(StringComparer.Ordinal) + { + ["trend_exit"] = "La tendenza si è interrotta: prezzo sotto lo stop mobile", + ["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti", + ["momentum_exit_trend"] = "Il mercato è girato al ribasso", + ["meanrev_exit_average"] = "Tornata sopra la media a 5 giorni", + ["meanrev_exit_rsi"] = "Rimbalzo arrivato: forza tornata alta", + ["meanrev_exit_earnings"] = "Uscita prima della trimestrale", + ["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute", + ["stop"] = "Stop di protezione raggiunto", + }; + + /// Why a trade was closed, in a short sentence. + public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.'); + + public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; + + /// The lines of one stage of a decision. is the JSON of the numbers the stage used. + public static IEnumerable Stage(string stage, string outcome, IReadOnlyList reasons, string? data) + { + ArgumentNullException.ThrowIfNull(reasons); + var good = outcome is DecisionOutcomes.Passed or DecisionOutcomes.Proposed or DecisionOutcomes.Same; + if (stage == DecisionStages.Risk && outcome == DecisionOutcomes.Passed && reasons.Count == 0) + { + yield return new WhyLine("Tutti i limiti di rischio rispettati" + Asked(data), true); + yield break; + } + + foreach (var reason in reasons) + { + yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy); + } + } + + // "(chiesti 0,05, passati 0,03)" when the stage shrank the order. + private static string Asked(string? data) + { + if (data is null) + { + return ""; + } + + using var json = JsonDocument.Parse(data); + if (json.RootElement.TryGetProperty("asked", out var asked) && json.RootElement.TryGetProperty("allowed", out var allowed) && + asked.TryGetDecimal(out var a) && allowed.TryGetDecimal(out var b) && b < a) + { + return $" (chiesti {Format.Quantity(a)}, passati {Format.Quantity(b)})"; + } + + return ""; + } +} diff --git a/src/Anubis.Server/RiskView.cs b/src/Anubis.Server/RiskView.cs new file mode 100644 index 0000000..7101cda --- /dev/null +++ b/src/Anubis.Server/RiskView.cs @@ -0,0 +1,134 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A row of the limits table: what is used now against the threshold, and what happens beyond it. +internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key); + +/// A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below. +internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown); + +/// +/// The Rischio screen (SPEC 9, 13.6, mockup 07): the emergency switch, the automatic blocks, the limits with what +/// they use now, the fall from the high, the scenarios and the risk events. One world, as on Conti. +/// +internal sealed record RiskView( + string BotState, + bool StopFile, + bool CloseAllPending, + string World, + WorldRisk Risk, + RiskLimits Limits, + IReadOnlyList Rows, + IReadOnlyList Drawdown, + IReadOnlyList Scenarios, + IReadOnlyList<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)> Events, + (DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock, + (DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock, + bool PdtGuard, + bool HasPositions) +{ + public bool AnyBlock => Risk.State.Tripped || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active"; + + public static async Task LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + var engine = services.Trading?.Risk ?? new RiskEngine(services.Db, clock, new Ledger(services.Db, clock), + new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), services.Settings, new FxStore(services.Db, clock), + (_, _) => Task.FromResult(null), (_, _) => Task.FromResult(null)); + var limits = await RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); + var accounts = await AccountsView.LoadAsync(services, clock, zone, cancellationToken).ConfigureAwait(false); + var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var risk = await engine.WorldAsync(world, cancellationToken).ConfigureAwait(false); + var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; + var now = clock.UtcNow; + + var (index, sent) = await services.Db.ReadAsync(async s => + { + var i = await s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world)).ConfigureAwait(false); + var o = await s.QueryAsync( + "SELECT o.account_id, COUNT(*) AS n FROM orders o WHERE o.submitted_at >= @f AND o.purpose IN ('entry', 'exit') GROUP BY o.account_id", + r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", now - TimeSpan.FromMinutes(1))).ConfigureAwait(false); + return (i, o); + }, cancellationToken).ConfigureAwait(false); + + var shown = accounts.Accounts.Select(a => a.Id).ToHashSet(); + var equity = accounts.TotalEur; + var positions = accounts.Positions; + var biggest = positions.MaxBy(p => p.ValueEur); + var crypto = positions.Where(p => p.Broker == Venues.Okx).Sum(p => p.ValueEur); + decimal Rate(PositionRow p) => p.Last == 0m ? 0m : p.ValueEur / (p.Quantity * p.Last); + var atRisk = positions.Select(p => p.Stop is { } stop ? Math.Max(0m, p.ValueEur - (p.Quantity * stop * Rate(p))) : p.ValueEur).ToList(); + var perMinute = sent.Where(x => shown.Contains(x.Account)).Select(x => x.Count).DefaultIfEmpty(0).Max(); + + string Pct(decimal fraction, int decimals = 2, bool sign = false) => Format.Percent(fraction * 100m, decimals, sign); + decimal? Use(decimal value, decimal limit) => limit <= 0m ? null : Math.Clamp(value / limit, 0m, 1m); + var m = risk.Measures; + var rows = new List + { + new("Perdita in un giorno", m.DayChange >= 0m ? "nessuna" : Pct(m.DayChange), m.DayChange >= 0m ? $"oggi {Pct(m.DayChange, 2, true)}" : null, + Use(-m.DayChange, limits.DailyLoss), Pct(-limits.DailyLoss), "Niente nuovi ingressi per 24 ore", RiskSettings.DailyLoss.Key), + new("Perdita in una settimana", m.WeekChange >= 0m ? "nessuna" : Pct(m.WeekChange), m.WeekChange >= 0m ? $"{Pct(m.WeekChange, 2, true)}" : null, + Use(-m.WeekChange, limits.WeeklyLoss), Pct(-limits.WeeklyLoss), "Rischio dimezzato per sette giorni", RiskSettings.WeeklyLoss.Key), + new("Calo dal massimo", Pct(m.Drawdown), Worst(index, risk.State.PeakFrom) is { } worst && worst < m.Drawdown ? $"peggiore {Pct(worst)}" : null, + Use(-m.Drawdown, limits.DrawdownStop), $"{Pct(-limits.DrawdownHalf, 0)} e {Pct(-limits.DrawdownStop, 0)}", + $"A {Pct(-limits.DrawdownHalf, 0)} dimezzo il rischio. A {Pct(-limits.DrawdownStop, 0)} fermo tutto e aspetto te", RiskSettings.DrawdownStop.Key), + new("Capitale investito", equity > 0m ? Pct(accounts.InvestedEur / equity, 1) : "—", null, equity > 0m ? Use(accounts.InvestedEur / equity, limits.MaxInvested) : null, + Pct(limits.MaxInvested, 0), "Non compro altro: non uso mai soldi presi in prestito", RiskSettings.MaxInvested.Key), + new("Peso di una sola posizione", biggest is null || equity <= 0m ? "—" : Pct(biggest.ValueEur / equity, 1), biggest?.Symbol, + biggest is null || equity <= 0m ? 0m : Use(biggest.ValueEur / equity, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia", + RiskSettings.MaxPosition.Key), + new("Crypto sul totale", equity > 0m ? Pct(crypto / equity, 1) : "—", null, equity > 0m ? Use(crypto / equity, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0), + "Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key), + new("Rischio di una singola operazione", atRisk.Count == 0 || equity <= 0m ? "—" : Pct(atRisk.Average() / equity), atRisk.Count == 0 ? null : "in media, fino allo stop", + atRisk.Count == 0 || equity <= 0m ? 0m : Use(atRisk.Average() / equity, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "Rimpicciolisco l'ordine prima di inviarlo", + RiskSettings.MaxTradeRisk.Key), + new("Ordini al minuto", perMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), null, Use(perMinute, limits.OrdersPerMinute), + limits.OrdersPerMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), "Mi fermo e ti avviso: può essere un guasto", RiskSettings.OrdersPerMinute.Key), + new("Età dei prezzi", "controllata a ogni ordine", null, null, $"{(int)limits.MaxPriceAge.TotalSeconds} secondi", "Non apro posizioni finché i dati non tornano freschi", + RiskSettings.MaxPriceAge.Key), + }; + + var drawdown = new List(); + var peak = 0m; + foreach (var p in index.Where(p => risk.State.PeakFrom is null || p.At >= risk.State.PeakFrom)) + { + peak = Math.Max(peak, p.Index); + drawdown.Add(new DrawdownPoint(p.At, peak > 0m ? (p.Index / peak) - 1m : 0m)); + } + + var scenarioText = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, cancellationToken).ConfigureAwait(false)).Value; + var dollars = accounts.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity)); + var scenarios = Anubis.Risk.Scenarios.Compute(Anubis.Risk.Scenarios.Parse(scenarioText), + [.. positions.Select(p => new ScenarioPosition(p.Broker == Venues.Okx, p.ValueEur, p.Stop is { } stop ? p.Quantity * stop * Rate(p) : null))], dollars, equity); + + var calendar = await new CalendarEventStore(services.Db, clock).BetweenAsync(now.AddDays(-14), now.AddDays(14), cancellationToken).ConfigureAwait(false); + var windows = calendar.Select(e => (Event: e, Window: CalendarBlocks.Window(e))).Where(x => x.Window is not null) + .Select(x => (x.Window!.Value.From, x.Window.Value.To, x.Event.Title)).OrderBy(x => x.From).ToList(); + (DateTimeOffset, DateTimeOffset, string)? next = windows.FirstOrDefault(w => w.To > now) is { Title: not null } n ? n : null; + (DateTimeOffset, DateTimeOffset, string)? last = windows.LastOrDefault(w => w.To <= now) is { Title: not null } l ? l : null; + + return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios, + await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false), + positions.Count > 0); + } + + private static decimal? Worst(IReadOnlyList index, DateTimeOffset? from) + { + decimal? worst = null; + var peak = 0m; + foreach (var p in index.Where(p => from is null || p.At >= from)) + { + peak = Math.Max(peak, p.Index); + var d = peak > 0m ? (p.Index / peak) - 1m : 0m; + worst = worst is null ? d : Math.Min(worst.Value, d); + } + + return worst; + } +} diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs new file mode 100644 index 0000000..8e831e6 --- /dev/null +++ b/src/Anubis.Server/StrategiesView.cs @@ -0,0 +1,166 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A strategy of the Strategie screen: its stage, results, requirements and what the user can do next. +internal sealed record StrategyCard( + StrategyStage Stage, + string Name, + string Description, + IReadOnlyList Rules, + string Account, + string Currency, + decimal CapitalEur, + decimal ResultEur, + decimal ResultPercent, + decimal WorstFall, + int Closed, + int Winners, + IReadOnlyList Open, + IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve, + IReadOnlyList Requirements, + string Phrase, + int? DaysToGo) +{ + public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")"; + + public bool AllMet => Requirements.All(r => r.Met); +} + +/// +/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base +/// strategy with its requirements, and the ones in observation with the reason. +/// +internal sealed record StrategiesView(IReadOnlyList Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts) +{ + /// What each base strategy does, in four lines (SPEC 8). + public static readonly IReadOnlyDictionary> Rules = new Dictionary>(StringComparer.Ordinal) + { + [StrategyNames.CryptoTrend] = + [ + "Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC", + "Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni", + "Più una moneta è agitata, meno ne compra", + "Mai a leva, mai al ribasso", + ], + [StrategyNames.EquityMomentum] = + [ + "Rifà la classifica ogni lunedì e tiene fino a 12 titoli", + "Vende chi esce dai primi 30 o tocca lo stop", + "Compra solo quando il mercato nel suo insieme sale", + "Solo azioni singole, nessun ETF americano", + ], + [StrategyNames.EquityMeanrev] = + [ + "Solo titoli sopra la loro media a 200 giorni", + "Esce al rimbalzo, oppure dopo 5 sedute", + "Salta i giorni prima delle trimestrali", + "Mai uscita nello stesso giorno dell'acquisto", + ], + }; + + public static async Task LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock); + var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m; + var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts", + r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken) + .ConfigureAwait(false); + var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false); + var cards = new List(); + foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false)) + { + if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy)) + { + continue; + } + + var family = StrategyCatalog.Find(stage.Strategy); + var ledgerAccount = stage.OrdersAccount ?? stage.AccountId; + var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount); + var usd = account.Currency == "USD"; + decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount; + var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy); + // As on Conti: each position is valued to the cent before the sum, so both pages show the same figure. + var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero)); + var result = equity is null ? 0m : equity.Cash + held - equity.Flows; + var since = stage.StageSince ?? DateTimeOffset.MinValue; + var (curve, trades) = await services.Db.ReadAsync(async s => + { + var c = await s.QueryAsync( + "SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false); + var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"), + ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false); + return (c, t); + }, cancellationToken).ConfigureAwait(false); + var peak = 0m; + var worst = 0m; + foreach (var p in curve) + { + peak = Math.Max(peak, p.Index); + worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m); + } + + var symbols = new List(); + foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy)) + { + symbols.Add(await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", p.InstrumentId)), + cancellationToken).ConfigureAwait(false) ?? "?"); + } + + var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false); + var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced; + var days = requirements.FirstOrDefault(r => r.Key == "days"); + int? toGo = days is { Met: false } && stage.StageSince is { } from + ? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays))) + : null; + var flows = equity?.Flows ?? 0m; + cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"), + family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result), + flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)], + requirements, StageBook.Phrase(stage.Strategy, next), toGo)); + } + + var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList(); + return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live); + } + + /// A requirement not met yet only because time has to pass or nothing could be measured so far. + public static bool IsPending(Requirement requirement) + { + ArgumentNullException.ThrowIfNull(requirement); + return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione"); + } + + /// Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice. + public static string ObservationReason(StrategyStage stage) + { + ArgumentNullException.ThrowIfNull(stage); + if (stage.Qualification is { Passed: false } q) + { + return q.Verdict; + } + + if (stage.Qualification is null) + { + return "Il backtest non è ancora stato fatto: finché manca resta in osservazione."; + } + + return stage.StageReason switch + { + "user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.", + var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".", + }; + } + + /// The report of a strategy's backtest in the repository, for the link. + public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report; +} diff --git a/src/Anubis.Server/TradesView.cs b/src/Anubis.Server/TradesView.cs new file mode 100644 index 0000000..2909280 --- /dev/null +++ b/src/Anubis.Server/TradesView.cs @@ -0,0 +1,198 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Server; + +/// The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked. +internal sealed record TradeFilter(string? Search, Guid? Account, string? Strategy, string? Result, string Period, int Page) +{ + public const int PageSize = 20; + + public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("7", "Ultimi 7 giorni"), ("30", "Ultimi 30 giorni"), ("90", "Ultimi 90 giorni")]; + + public static readonly IReadOnlyList<(string Key, string Label)> Results = [("", "Guadagni e perdite"), ("guadagni", "Solo guadagni"), ("perdite", "Solo perdite")]; + + public static TradeFilter Parse(string? search, string? account, string? strategy, string? result, string? period, string? page) => new( + string.IsNullOrWhiteSpace(search) ? null : search.Trim(), + Guid.TryParse(account, out var a) ? a : null, + string.IsNullOrWhiteSpace(strategy) ? null : strategy, + result is "guadagni" or "perdite" ? result : null, + Periods.Any(p => p.Key == period) ? period! : "avvio", + int.TryParse(page, NumberStyles.None, CultureInfo.InvariantCulture, out var p) && p > 0 ? p : 1); + + /// The query string of this filter with one value changed. + public string Query(int? page = null) + { + var parts = new List(); + void Add(string key, string? value) + { + if (!string.IsNullOrEmpty(value)) + { + parts.Add(key + "=" + Uri.EscapeDataString(value)); + } + } + + Add("cerca", Search); + Add("conto", Account?.ToString()); + Add("strategia", Strategy); + Add("esito", Result); + Add("periodo", Period == "avvio" ? null : Period); + var p = page ?? Page; + Add("pagina", p > 1 ? p.ToString(CultureInfo.InvariantCulture) : null); + return parts.Count == 0 ? "" : "?" + string.Join('&', parts); + } +} + +/// A step of the "why" card: a stage of a decision in plain Italian. +internal sealed record WhyLine(string Text, bool Good); + +/// A closed trade of the Operazioni screen, in its own currency and in euro. +internal sealed record TradeRow(Guid Id, string Symbol, string Name, string Strategy, string Account, string Currency, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, + decimal Quantity, decimal EntryPrice, decimal ExitPrice, decimal Realized, decimal RealizedEur, decimal Fees, string ExitReason, string? ExitCode, + IReadOnlyList Bought, IReadOnlyList Sold, decimal? EntrySlipBp, decimal? ExitSlipBp) +{ + public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m; +} + +/// +/// The Operazioni screen (SPEC 13.6, mockup 03): closed trades with their figures, filters, the result of each +/// trade as bars, and for each one the "why" card built from the rows of the decisions table (SPEC 5.2). +/// +internal sealed record TradesView( + IReadOnlyList Rows, + int Matching, + int Total, + DateTimeOffset? Since, + decimal Gains, + decimal Losses, + int Winners, + decimal Fees, + IReadOnlyList<(DateTimeOffset At, decimal Eur, string Symbol)> Bars, + IReadOnlyList<(Guid Id, string Name)> Accounts, + IReadOnlyList Strategies) +{ + public int Losers => Matching - Winners; + + /// Euro gained for each euro lost: null while nothing was lost. + public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null; + + public decimal Net => Gains + Losses; + + public static async Task LoadAsync(AppServices services, IClock clock, TradeFilter filter, int? limit, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(filter); + var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m; + var (accounts, trades) = await services.Db.ReadAsync(async s => + { + var a = await s.QueryAsync("SELECT id, name, environment, base_currency FROM accounts ORDER BY broker DESC, created_at", + r => (Id: r.Id("id"), Name: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var t = await s.QueryAsync( + "SELECT t.id, t.account_id, t.instrument_id, t.strategy, t.opened_at, t.closed_at, t.bought_quantity, t.bought_value, t.sold_quantity, t.sold_value, t.fees, t.realized, " + + "t.exit_reason, i.symbol, i.name FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE t.status = 'closed' ORDER BY t.closed_at DESC, t.id", + r => new Closed(r.Id("id"), r.Id("account_id"), r.Id("instrument_id"), r.Text("strategy"), r.Moment("opened_at"), r.Moment("closed_at"), r.Money("bought_quantity"), + r.Money("bought_value"), r.Money("sold_quantity"), r.Money("sold_value"), r.Money("fees"), r.Money("realized"), r.TextOrNull("exit_reason"), r.Text("symbol"), + r.TextOrNull("name") ?? "")).ConfigureAwait(false); + return (a, t); + }, cancellationToken).ConfigureAwait(false); + + // One world only, as on the Conti screen: real accounts when there are any, so finto and vero never add up. + var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var shown = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToDictionary(a => a.Id); + decimal Eur(Guid account, decimal amount) => shown[account].Currency == "USD" ? (rate > 0m ? amount / rate : 0m) : amount; + var all = trades.Where(t => shown.ContainsKey(t.Account)).ToList(); + var from = filter.Period switch + { + "7" => clock.UtcNow.AddDays(-7), + "30" => clock.UtcNow.AddDays(-30), + "90" => clock.UtcNow.AddDays(-90), + _ => (DateTimeOffset?)null, + }; + var matching = all.Where(t => + (filter.Account is null || t.Account == filter.Account) && + (filter.Strategy is null || t.Strategy == filter.Strategy) && + (from is null || t.ClosedAt >= from) && + (filter.Result is null || (filter.Result == "guadagni" ? t.Realized >= 0m : t.Realized < 0m)) && + (filter.Search is null || t.Symbol.Contains(filter.Search, StringComparison.OrdinalIgnoreCase) || t.Name.Contains(filter.Search, StringComparison.OrdinalIgnoreCase))) + .ToList(); + + var page = limit is { } n ? matching.Take(n).ToList() : matching.Skip((filter.Page - 1) * TradeFilter.PageSize).Take(TradeFilter.PageSize).ToList(); + var rows = new List(); + foreach (var t in page) + { + var (bought, sold, entrySlip, exitSlip, code) = await WhyAsync(services, t, cancellationToken).ConfigureAwait(false); + var quantity = t.BoughtQuantity; + rows.Add(new TradeRow(t.Id, t.Symbol, t.Name, t.Strategy, shown[t.Account].Name, shown[t.Account].Currency, t.OpenedAt, t.ClosedAt, quantity, + quantity == 0m ? 0m : t.BoughtValue / quantity, t.SoldQuantity == 0m ? 0m : t.SoldValue / t.SoldQuantity, t.Realized, + Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Fees, ReasonTexts.Exit(code ?? t.ExitReason), code ?? t.ExitReason, bought, sold, entrySlip, + exitSlip)); + } + + var bars = matching.OrderBy(t => t.ClosedAt).Select(t => (t.ClosedAt, Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Symbol)).ToList(); + return new TradesView(rows, matching.Count, all.Count, all.Count > 0 ? all.Min(t => t.ClosedAt) : null, + bars.Where(b => b.Item2 >= 0m).Sum(b => b.Item2), bars.Where(b => b.Item2 < 0m).Sum(b => b.Item2), bars.Count(b => b.Item2 >= 0m), + matching.Sum(t => Math.Round(Eur(t.Account, t.Fees), 2, MidpointRounding.AwayFromZero)), bars, + [.. shown.Values.Select(a => (a.Id, a.Name))], [.. all.Select(t => t.Strategy).Distinct().Order(StringComparer.Ordinal)]); + } + + /// The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade. + public string Csv() + { + var text = new StringBuilder("chiusa_il;aperta_il;strumento;nome;strategia;conto;quantita;prezzo_entrata;prezzo_uscita;valuta;risultato;risultato_eur;commissioni;motivo\n"); + foreach (var r in Rows) + { + text.Append(string.Join(';', Moment(r.ClosedAt), Moment(r.OpenedAt), Clean(r.Symbol), Clean(r.Name), r.Strategy, Clean(r.Account), Number(r.Quantity), Number(r.EntryPrice), + Number(r.ExitPrice), r.Currency, Number(r.Realized), Number(r.RealizedEur), Number(r.Fees), Clean(r.ExitReason))).Append('\n'); + } + + return text.ToString(); + + static string Moment(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture); + + static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','); + + static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + } + + private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue, + decimal SoldQuantity, decimal SoldValue, decimal Fees, decimal Realized, string? ExitReason, string Symbol, string Name); + + /// + /// The decisions behind a trade: the first purchase and the last sale of its executions, matched to their decision + /// through the order key (the hash of the decision id), and every stage of those decisions in words. + /// + private static async Task<(List Bought, List Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t, + CancellationToken cancellationToken) + { + var (executions, decisions) = await services.Db.ReadAsync(async s => + { + var e = await s.QueryAsync( + "SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " + + "ORDER BY started_at, id", + r => (Side: r.Text("side"), Key: r.Text("order_key"), Reference: r.MoneyOrNull("reference_price"), Purpose: r.Text("purpose")), + ("a", t.Account), ("i", t.Instrument), ("s", t.Strategy), ("f", t.OpenedAt.AddMinutes(-5)), ("t", t.ClosedAt)).ConfigureAwait(false); + var d = await s.QueryAsync( + "SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id", + r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")), + ("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false); + return (e, d); + }, cancellationToken).ConfigureAwait(false); + + var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal); + List Lines(string? key) => key is not null && byKey.TryGetValue(key, out var rows) + ? [.. rows.SelectMany(r => ReasonTexts.Stage(r.Stage, r.Outcome, System.Text.Json.JsonSerializer.Deserialize>(r.Reasons) ?? [], r.Data))] + : []; + var buy = executions.FirstOrDefault(e => e.Side == "buy"); + var sell = executions.LastOrDefault(e => e.Side == "sell"); + var sold = Lines(sell.Key); + var code = sell.Key is not null && byKey.TryGetValue(sell.Key, out var exitRows) + ? exitRows.Where(r => r.Stage == DecisionStages.Strategy).SelectMany(r => System.Text.Json.JsonSerializer.Deserialize>(r.Reasons) ?? []).FirstOrDefault() + : sell.Purpose is "stop" or "protective" ? "stop" : null; + decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null; + decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null; + return (Lines(buy.Key), sold, entrySlip, exitSlip, code); + } +} diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 8f8494d..ae142fb 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -120,10 +120,25 @@ public static class DemoMode ["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m), }; var currencyOf = new Dictionary { [okx] = "EUR", [alpaca] = "USD" }; + // F.4: 58 days of 60 in simulation, after a passed backtest (an example: the real outcomes are in docs/backtests). foreach (var (name, account, capital, _, share) in strategies.Values) { - await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)", - cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) + var example = new Trading.Qualification + { + Passed = true, + Verdict = "Superato (dato di esempio).", + Report = "docs/backtests/" + name + ".md", + MaxDrawdown = 0.18m, + ExpectedSlippageBp = 8m, + RoundTripCost = 0.0056m, + ExpectedPathP5 = [.. Enumerable.Range(1, 365).Select(d => Math.Round(-0.012 * Math.Sqrt(d), 4))], + }; + await s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, stage_reason, qualification, capital, share, state, created_at, updated_at) " + + "VALUES (@id, @n, @a, 'simulation', @since, 'user', @q, @c, @sh, @st, @t, @t)", + cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-58)), + ("q", new DbJson(JsonSerializer.Serialize(example, Trading.Qualification.Json))), ("c", capital), ("sh", share), + ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) .ConfigureAwait(false); } @@ -177,20 +192,22 @@ public static class DemoMode [ ("account", okx, null, 4000m, 231.60m), ("account", alpaca, null, 6000m, 180.86m), - ("strategy", null, "crypto_trend", 4000m, 231.60m), - ("strategy", null, "equity_momentum", 4500m, 169.50m), - ("strategy", null, "equity_meanrev", 1500m, 11.36m), + ("strategy", okx, "crypto_trend", 4000m, 231.60m), + ("strategy", alpaca, "equity_momentum", 4500m, 169.50m), + ("strategy", alpaca, "equity_meanrev", 1500m, 11.36m), ]; foreach (var (day, equity, benchmark, drawdown) in daily) { var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0)))); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)", - cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, twr_index, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @x, @t)", + cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("x", Math.Round(equity / 10000m, 6)), ("t", now)).ConfigureAwait(false); foreach (var (scope, account, strategy, start, result) in series) { var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)", - cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false); + // Without deposits along the way the index is the value over the start. + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, twr_index, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @x, @t)", + cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("x", Math.Round(value / start, 6)), ("t", now)) + .ConfigureAwait(false); } } @@ -269,6 +286,50 @@ public static class DemoMode "VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)", cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought), ("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false); + await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken) + .ConfigureAwait(false); + } + } + + // F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on + // the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss. + private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought, + decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken) + { + var (entry, exit) = strategy switch + { + "crypto_trend" => ("trend_entry", "trend_exit"), + "equity_momentum" => ("momentum_entry", "momentum_exit_rank"), + _ => ("meanrev_entry", "meanrev_exit_average"), + }; + + async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) => + await 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, NULL, @t)", + cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome), + ("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false); + + async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) => + await s.ExecuteAsync( + "INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, @side, @p, @q, @q, @k, 1, 0, @r, @st, @at, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("side", side), ("p", purpose), ("q", quantity), + ("k", Trading.ClientOrderIds.Key(decision)), ("r", Math.Round(reference, 6)), ("st", Trading.ExecutionStates.Done), ("at", at), ("t", now)).ConfigureAwait(false); + + var buy = ids.Next(); + await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false); + await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); + await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); + await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false); + if (stopped) + { + await ExecuteAsync("sell", "protective", ids.Next(), sold / quantity * 1.0003m, closed).ConfigureAwait(false); + } + else + { + var sale = ids.Next(); + await DecideAsync(sale, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [exit], closed.AddMinutes(-1)).ConfigureAwait(false); + await ExecuteAsync("sell", "exit", sale, sold / quantity * 1.0001m, closed).ConfigureAwait(false); } } diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs index bb68abf..b0aeed2 100644 --- a/src/Anubis/Trading/RiskEngine.cs +++ b/src/Anubis/Trading/RiskEngine.cs @@ -467,6 +467,10 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo return total; } + /// What the bot as a whole remembers: a "stop and close all" still waiting for the open. + public async Task BotAsync(CancellationToken cancellationToken) => + await LoadAsync(BotRow, cancellationToken).ConfigureAwait(false) ?? new BotRiskState(); + /// 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", diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 668265b..17b27ca 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -348,6 +348,35 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, }, cancellationToken).ConfigureAwait(false); } + /// The phrase that confirms more risk while real money is in play. + public const string RaisePhrase = "confermo più rischio con soldi veri"; + + /// True when a strategy, of or of any broker when null, is in reduced or real. + public async Task AnyLiveAsync(string? broker, CancellationToken cancellationToken) => + (await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)); + + /// + /// Raising a risk limit or the capital while a strategy has real money needs the confirmation of SPEC 12.4: the + /// typed phrase and a fresh password and second factor. Without real money in play it passes as it is. + /// + public async Task ConfirmRaiseAsync(string? broker, string? phrase, string? password, string? code, CancellationToken cancellationToken) + { + if (!await AnyLiveAsync(broker, cancellationToken).ConfigureAwait(false)) + { + return; + } + + if (!string.Equals(phrase?.Trim(), RaisePhrase, StringComparison.Ordinal)) + { + throw new LiveConfirmationException("phrase", $"Con soldi veri in gioco, per alzare un limite scrivi \"{RaisePhrase}\"."); + } + + if (password is null || !await reauthenticate(password, code, cancellationToken).ConfigureAwait(false)) + { + throw new LiveConfirmationException("password", "Password o codice non corretti."); + } + } + /// /// 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. diff --git a/tests/Anubis.Tests/StrategyScreensTests.cs b/tests/Anubis.Tests/StrategyScreensTests.cs new file mode 100644 index 0000000..e5f6a40 --- /dev/null +++ b/tests/Anubis.Tests/StrategyScreensTests.cs @@ -0,0 +1,179 @@ +using System.Net; +using Anubis.Core; +using Anubis.Db; +using Anubis.Risk; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07). +/// +[TestClass] +public sealed class StrategyScreensTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + // Mockup 03: the balance of the 41 trades of appendix F, and the "why" of each from the decisions. + var trades = await server.TextAsync("/operazioni"); + foreach (var text in new[] + { + "1,62", "+239,27", "22 su 41", "53,7%", "+28,42", "20,31", "14,82", "Mostrate 20 di 41", "Tornata sopra la media a 5 giorni", + "Perché l'ho comprata", "Tutti i limiti di rischio rispettati", "Stop di protezione raggiunto", + }) + { + StringAssert.Contains(trades, text, $"Missing {text} on Operazioni."); + } + + StringAssert.Contains(await server.TextAsync("/operazioni?esito=perdite"), "Mostrate 19 di 19"); + using (var csv = await server.GetAsync("/api/operazioni.csv")) + { + Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode); + Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType); + var lines = System.Text.Encoding.UTF8.GetString((await csv.Content.ReadAsByteArrayAsync())[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries); + Assert.HasCount(42, lines, "a header and the 41 trades"); + } + + // Mockup 04: the four stages, 58 days of 60, the same result as on Conti. + var strategies = await server.TextAsync("/strategie"); + foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" }) + { + StringAssert.Contains(strategies, text, $"Missing {text} on Strategie."); + } + + Assert.IsFalse(strategies.Contains("/azioni/strategie/", StringComparison.Ordinal), "The demo changes no stage."); + + // Mockup 07: no block, the limits with their use, the worst fall of the demo, the scenarios. + var risk = await server.TextAsync("/rischio"); + foreach (var text in new[] { "Nessun blocco attivo", "64,1%", "2,82% il 5 set", "Se succedesse domani", "465", "Cosa il bot non può fare, mai" }) + { + StringAssert.Contains(risk, text, $"Missing {text} on Rischio."); + } + + var settings = await server.TextAsync("/impostazioni"); + StringAssert.Contains(settings, "Perdita in un giorno (%)"); + Assert.IsFalse(settings.Contains("/azioni/rischio/limiti", StringComparison.Ordinal), "No risk form in the demo."); + } + finally + { + TempFolder.Delete(demoRoot); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AStrategyThatFailedItsBacktestCannotEnterTheSimulation() + { + var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); + await server.SignInFirstTimeAsync(); + + // The outcome file of crypto_trend says "not passed"; the stock ones wait for the Alpaca keys. + var page = await server.TextAsync("/strategie"); + StringAssert.Contains(page, "Non supera i test"); + StringAssert.Contains(page, "In attesa dei dati"); + Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass."); + + using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione"); + Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused)); + Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task LimitsGoDownFreelyAndUpOnlyWithThePhraseWhileAStrategyUsesRealMoney() + { + var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); + var password = await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + var daily = RiskSettings.DailyLoss.Key; + + // Out of range, or the halving after the switch: nothing changes. + using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50"))) + { + Assert.AreEqual("/impostazioni?errore=limite#rischio", ServerHarness.Location(wrong)); + } + + using (var order = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (RiskSettings.DrawdownHalf.Key, "20"))) + { + Assert.AreEqual("/impostazioni?errore=ordine-limiti#rischio", ServerHarness.Location(order)); + } + + // Lower is always allowed. + using (var lower = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1,5"))) + { + Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lower)); + } + + Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value); + + // A strategy with real money: raising needs the phrase and the password, and the form asks for them. + await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", CancellationToken.None, + ("s", StrategyNames.CryptoTrend)), CancellationToken.None); + StringAssert.Contains(await server.TextAsync("/impostazioni"), StageBook.RaisePhrase); + using (var bare = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"))) + { + Assert.AreEqual("/impostazioni?errore=frase-rischio#rischio", ServerHarness.Location(bare)); + } + + using (var badPassword = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", "not-it"))) + { + Assert.AreEqual("/impostazioni?errore=password-rischio#rischio", ServerHarness.Location(badPassword)); + } + + Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value, "Refused raises change nothing."); + using (var confirmed = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", password))) + { + Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(confirmed)); + } + + Assert.AreEqual("2", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value); + + // Lowering again needs nothing, even now. + using var lowerAgain = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1")); + Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lowerAgain)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task StopCloseAndRestartGoThroughTheRiskEngine() + { + var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); + await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + async Task StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, CancellationToken.None)).Value; + + using (var stop = await server.PostFormAsync("/rischio", "/azioni/bot/ferma", ("ritorno", "/rischio"))) + { + StringAssert.StartsWith(ServerHarness.Location(stop), "/rischio"); + } + + Assert.AreEqual("stopped", await StateAsync()); + StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti"); + + // With the STOP file in the data folder the restart is refused. + var stopFile = services.Trading!.Risk!.StopFile!; + await File.WriteAllTextAsync(stopFile, ""); + using (var refused = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio"))) + { + StringAssert.Contains(ServerHarness.Location(refused), "errore=file-stop"); + } + + Assert.AreEqual("stopped", await StateAsync()); + File.Delete(stopFile); + using (var restart = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio"))) + { + Assert.IsFalse(ServerHarness.Location(restart).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(restart)); + } + + Assert.AreEqual("active", await StateAsync()); + } +} -- 2.54.1 From 17d6b8db384417471935a6ab176627eb1171bc69 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 16:19:35 +0100 Subject: [PATCH 5/8] Record the Phase 5 choices and close the roadmap items (refs #46) ADR 0011 collects what the specification leaves open or refines in this phase: strategies shared by backtest and live, correctives and risk inside the backtests, the risk engine that only refuses or shrinks, the stages as the only way to real money, the euro history and the protocol of the base backtests, and the honest "not passed" of crypto_trend. ROADMAP ticks the Phase 5 items and criteria with the tests that prove them; STATE moves to Phase 6. Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 32 +++++++-------- docs/STATE.md | 19 ++++++--- docs/adr/0011-scelte-fase-5.md | 73 ++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 21 deletions(-) create mode 100644 docs/adr/0011-scelte-fase-5.md diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ee7959f..c41d6f6 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -156,25 +156,25 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare. **Lavori** -- [ ] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend` -- [ ] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum` -- [ ] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev` -- [ ] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento -- [ ] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza -- [ ] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri -- [ ] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/ -- [ ] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari -- [ ] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5` +- [x] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend` +- [x] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum` +- [x] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev` +- [x] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento +- [x] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza +- [x] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri +- [x] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/ +- [x] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari +- [x] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5` **Criteri di accettazione** -- [ ] Ogni regola di 9.1 e 9.2 ha il suo test -- [ ] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale -- [ ] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero -- [ ] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio -- [ ] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione -- [ ] I test anti-sguardo-avanti passano -- [ ] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup +- [x] Ogni regola di 9.1 e 9.2 ha il suo test (`RiskTests` e `RiskEngineTests`: perdita del giorno, della settimana, calo dal massimo a 10 e 15%, capitale investito, posizione singola, quota crypto, rischio della singola operazione, controlli tecnici, niente vendite allo scoperto, protezione per le operazioni in giornata, avviso all'80%, ordini al minuto, file STOP; più `NoRuleEverEnlargesWhatTheStrategyAsked` e `AfterALossNoPurchaseIsLarger` come test di proprietà) +- [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`) +- [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`) +- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 29,1% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome` +- [x] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione (`AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome`; i due rapporti azionari dicono cosa manca) +- [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`) +- [x] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup (`TheDemoShowsTradesStrategiesAndRiskAsInTheMockups` e confronto a 1440 e 375 px con i mockup 03, 04 e 07) ## Fase 6 — Motore dal vivo in simulazione diff --git a/docs/STATE.md b/docs/STATE.md index 535414c..2aced80 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-11 ## Fase corrente -**Fase 4 — Backtest e laboratorio: completata.** La prossima è la Fase 5 (Strategie, portafoglio, rischio), da iniziare con il via dell'utente. Restano in attesa delle chiavi demo di OKX e di Alpaca le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2). +**Fase 5 — Strategie, portafoglio, rischio: completata.** La prossima è la Fase 6 (Motore dal vivo in simulazione), da iniziare con il via dell'utente. Nessuna delle tre strategie è ancora in simulazione: `crypto_trend` non ha superato il backtest e le due azionarie aspettano le chiavi di Alpaca. Restano in attesa delle chiavi demo di OKX e di Alpaca anche le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2). ## Fatto @@ -70,6 +70,13 @@ Aggiornato: 2026-11-11 - Laboratorio su un thread a priorità bassa, una prova alla volta, con ripresa dopo un riavvio; dati dalle barre raccolte o dallo storico di ricerca Binance. - Schermata Laboratorio: elenco delle prove, modulo per un nuovo test, rapporto completo, confronto tra due prove. Le sezioni "Migliorie in osservazione" e "Stime di costo da confermare" aspettano le Fasi 9 e 8. - Strategia d'esempio `sma_cross` (incrocio di medie) per provare il laboratorio; le strategie di base arrivano con la Fase 5. +- **Fase 5** (scelte nell'ADR 0011): + - Le tre strategie di base: `crypto_trend` (rottura su nove periodi, stop a metà del canale, pesi a volatilità obiettivo, universo dei primi dieci del mese), `equity_momentum` (revisione settimanale con il filtro di SPY, pesi a volatilità inversa, stop che segue il prezzo) e `equity_meanrev` (RSI a 2 sopra la media a 200 sedute, rischio fisso, uscita alla chiusura). Le stesse classi girano in prova e dal vivo e passano il test contro lo sguardo in avanti. + - Correttivi comuni (regime crypto, calendario economico), dimensionamento sulla quota del bot e motore del rischio completo: limiti di perdita per mondo, calo dal massimo con dimezzamento e interruttore, limiti di dimensione, controlli tecnici, niente vendite allo scoperto né leva. Toglie o riduce, mai aggiunge. Gira anche dentro i backtest. + - Ogni passo di una decisione resta scritto con i suoi codici motivo (tabella `decisions`). + - Stadi verso i soldi veri: osservazione, simulazione, reale ridotto, reale. Senza la procedura di 12.4 nessun ordine raggiunge un conto reale; una strategia retrocessa gestisce le uscite delle posizioni reali fino a zero; il gemello simulato resta fuori dai totali. In simulazione entra solo una strategia che ha superato il backtest. + - Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 29,1% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio. + - Schermate Operazioni (con la scheda "perché" e l'esportazione CSV), Strategie e Rischio come i mockup 03, 04 e 07; in Impostazioni limiti, protezione per le operazioni in giornata e scenari. Fermare, chiudere e ripartire passano dal motore del rischio; alzare un limite mentre una strategia usa soldi veri chiede frase e password. ## In corso @@ -77,7 +84,7 @@ Nulla. ## Prossimo passo -Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi, la ripartizione del capitale e il motore del rischio completo, con i backtest onesti di ciascuna strategia fatti nel Laboratorio. Con le chiavi dei conti di prova si possono chiudere i due criteri in attesa (azioni della Fase 2, conti di prova della Fase 3). +Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il processo di guardia, il recupero dopo un'assenza, il Diario, Panoramica, Telegram e la prova di durata di 48 ore. Con le chiavi del conto paper di Alpaca si possono fare i backtest azionari (`anubis backtest base`) e chiudere i criteri in attesa delle Fasi 2 e 3. ## Da sapere @@ -88,7 +95,9 @@ Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi - `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`. - Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14). - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). -- Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta, senza convertirli: una prova lavora in una sola valuta (ADR 0010, punto 13). +- Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta (ADR 0010, punto 13); i backtest delle strategie di base li convertono in euro con il cambio BCE del giorno (ADR 0011, punto 10). +- `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti. +- Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati). - Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove. - I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti. - Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2). @@ -99,8 +108,8 @@ Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi | Cosa | Da quando serve | Senza | |---|---|---| -| Via libera per la Fase 5 | Subito | Non si parte | -| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 in attesa | +| Via libera per la Fase 6 | Subito | Non si parte | +| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa | | Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | | Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server | diff --git a/docs/adr/0011-scelte-fase-5.md b/docs/adr/0011-scelte-fase-5.md new file mode 100644 index 0000000..dc02d38 --- /dev/null +++ b/docs/adr/0011-scelte-fase-5.md @@ -0,0 +1,73 @@ +# 0011 — Scelte della Fase 5: strategie, portafoglio, rischio + +Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 7.1, 7.5, 8, 9, 12, 13.1–13.6) e l'ADR 0010, senza aggiungere componenti esterni + +## Contesto + +La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del rischio, gli stadi verso i soldi veri, i backtest onesti delle strategie e le schermate Operazioni, Strategie e Rischio. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui. + +## Decisione + +**1. Le strategie sono le stesse in prova e dal vivo.** +- Le tre strategie (`crypto_trend`, `equity_momentum`, `equity_meanrev`) sono classi senza stato proprio: leggono le barre, il loro portafoglio e il patrimonio di riferimento, e restituiscono intenzioni (peso voluto e stop). Ogni intenzione ha un codice motivo, mai un testo libero. +- Il motore di backtest ha imparato ciò che le regole chiedono: l'uscita alla stessa chiusura (`equity_meanrev`, che dal vivo vende alle 15:55), lo stop messo a una distanza dal prezzo ottenuto, gli strumenti di solo dato come SPY, il calendario di borsa e la storia del patrimonio. +- Il patrimonio di riferimento di una strategia è quello della sua quota del bot (`ReferenceShare`): i limiti in percentuale si misurano sul bot, non sulla sola strategia. +- Tutte e tre passano il test contro lo sguardo in avanti dell'ADR 0010 (punto 11). + +**2. Correttivi e rischio girano anche nei backtest.** I correttivi di 8.5 (regime crypto: metà delle nuove entrate quando Bitcoin chiude sotto la media a 200 giorni o la sua volatilità supera il 90° percentile di due anni; calendario economico: niente entrate da 30 minuti prima a 30 dopo un dato USA importante, fino a 60 dopo una decisione di Fed o BCE) e le regole di 9.1 e 9.2 sono passi della decisione, gli stessi dal vivo e in prova. Nel backtest di una strategia: +- la strategia è una parte del bot e il resto conta come liquidità ferma, così una sua perdita pesa sul mondo quanto la sua quota; +- ogni chiusura è una giornata italiana a sé (mezzogiorno UTC); +- dopo che l'interruttore scatta si suppone che l'utente riparta una settimana dopo, e il massimo si misura da lì; +- età del prezzo, prezzo dell'ordine e orologio esistono solo dal vivo. + +**3. Il motore del rischio toglie o riduce, mai aggiunge.** +- Ogni intenzione lo attraversa prima di diventare un ordine; la protezione (stop e uscite) passa sempre. +- Le tre misure di 9.2 (perdita del giorno da mezzanotte italiana, degli ultimi sette giorni, calo dal massimo) vengono dall'indice ponderato nel tempo di ciascun mondo, così versamenti e prelievi non sembrano guadagni o perdite. Simulato e reale sono due mondi: un limite ferma solo il mondo dove è stato superato. +- Il monitor è una macchina a stati pura, la stessa in prova e dal vivo, e il suo moltiplicatore è sempre uno o meno. +- L'avviso parte all'80% di una soglia, una volta per superamento, senza blocchi. +- La protezione per le operazioni in giornata (`pdt_guard`) è spenta in partenza: Anubis non usa il margine. +- I test di proprietà controllano che il risultato non sia mai più grande del richiesto, e mai più grande dopo una perdita. + +**4. Fermare e ripartire passa sempre dal motore del rischio.** "Ferma tutto", "Ferma e chiudi", il file `STOP` nella cartella dei dati e l'anomalia di ordini al minuto fermano il bot finché l'utente non conferma la ripartenza. La ripartenza è rifiutata finché il file `STOP` esiste. Dopo uno scatto il massimo si misura dalla ripartenza. + +**5. Ogni passo di una decisione resta scritto.** La nuova tabella `decisions` tiene una riga per passo (strategia, correttivi, dimensionamento, rischio, ordine) con codici motivo e numeri usati. La scheda "perché" di Operazioni collega decisioni ed esecuzioni con l'id d'ordine deterministico (`ClientOrderIds.Key(decision_id)`) e scrive le frasi da modelli italiani fissi. + +**6. Gli stadi sono l'unica strada verso i soldi veri.** +- Quattro stadi: osservazione, simulazione, reale ridotto, reale. +- Un ordine su un conto reale richiede il consenso della configurazione d'avvio, tutti i requisiti di 12.3 soddisfatti, la frase scritta a mano e password (più il secondo fattore, se attivo) inseriti da poco. I gestori degli ordini sui conti reali, in caso di dubbio, rifiutano e richiedono la conferma prima di ogni ordine. +- Da osservazione a simulazione si passa con un pulsante, ma solo se il backtest della strategia è superato (`Qualification.Passed`). Una strategia che non lo ha superato resta in osservazione e la schermata dice perché. +- Una strategia retrocessa o revocata tiene le posizioni reali in sola uscita, con i loro stop, fino a zero. +- Il gemello simulato di una strategia con soldi veri resta fuori dai totali e dal patrimonio di riferimento. + +**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Ogni cambio finisce nel registro delle impostazioni. + +**8. Gli scenari sono una somma semplice.** "Se succedesse domani" applica la variazione al valore delle posizioni del momento. "Con gli stop" prende per ogni posizione la perdita più piccola tra lo scenario e la distanza dal suo stop, arrotondata a 5 € e scritta come "circa", perché uno stop non garantisce il prezzo. Lo scenario del dollaro tocca il conto in dollari e gli stop non lo riducono. + +**9. I risultati per strategia si arrotondano come in Conti.** Ogni posizione si arrotonda al centesimo prima di sommare, così Strategie e Conti mostrano lo stesso numero. + +**10. Lo storico crypto in euro, per i backtest delle strategie.** L'ADR 0010 (punto 13) lasciava i dati Binance in USDT; per le strategie di base serve l'euro, perché il bot pensa in euro. +- Le barre giornaliere USDT si dividono per il cambio BCE EUR/USD dello stesso giorno, o dell'ultimo precedente fino a 7 giorni prima; altrimenti la barra si scarta. Si salvano come sede `binance_eur`. +- Una serie si ferma al primo buco più lungo di 7 giorni (`MaxGapDays`): ciò che segue è un'altra moneta. Il LUNA rilanciato nel 2022 non si confonde con quello crollato, che si taglia al 13/05/2022. +- L'elenco degli archivi comprende le monete tolte dal listino (49 coppie, con LUNA, FTT, BCC, VEN, XMR…): l'universo passato non è scelto tra i sopravvissuti. +- `anubis backtest base --offline` scarica i cambi BCE solo se il file manca. + +**11. Il protocollo dei backtest di base.** +- Periodo dal 01/01/2019 al 31/10/2026. Le prove leggono anche 450 giorni prima dell'inizio (`TrialData.WarmupDays`), solo perché indicatori ed età minima di quotazione (400 giorni) siano pronti dal primo giorno. Il controllo "strumento vuoto" e il conteggio delle sedute guardano solo dentro il periodo. +- `crypto_trend` si prova su due universi: quello largo e solo BTC, ETH e SOL. Supera solo se superano entrambi; le misure mostrate vengono dall'universo largo. +- Nel DSR il secondo universo conta come prove precedenti anche le varianti del primo. L'id della prova viene dall'impronta del piano, così rifare il calcolo non crea prove nuove. +- Per gli strumenti dell'universo largo il limite del Laboratorio sale a 60 (`Laboratory.MaxSymbols`). +- Il costo di andata e ritorno è 2 × (commissione taker + scostamento); lo scostamento è pesato sul controvalore scambiato. +- Il percorso atteso a un anno viene da un bootstrap a blocchi stazionario: 2.000 percorsi, blocchi medi di 20 giorni, seme 20260101, 365 giorni. +- Il rapporto mostra lo Sharpe annuo (× √sedute dell'anno) e DSR e PBO con tre decimali, perché "0,90 serve ≥ 0,90" con due decimali confondeva. + +**12. L'esito dei backtest viaggia con il codice.** I file `docs/backtests/*.outcome.json` sono inclusi nell'applicazione e letti a ogni avvio. Gli esiti azionari sono "non superato, in attesa delle chiavi Alpaca": senza storico azionario le due strategie azionarie restano in osservazione. + +**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 29,1% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 11,2% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile. + +**14. La demo è coerente con i mockup.** La modalità dimostrativa semina le decisioni dietro le sue operazioni, 58 giorni di simulazione, una qualifica d'esempio e gli indici delle curve, così Operazioni, Strategie e Rischio mostrano le cifre dei mockup 03, 04 e 07. Nella demo nessuno stadio cambia e i moduli del rischio non ci sono. + +## Conseguenze + +- Nessuna strategia può arrivare alla simulazione senza un backtest superato, né ai soldi veri senza la procedura di 12.4. Oggi tutte e tre restano in osservazione: è l'esito onesto, non un difetto. +- Le prove dei backtest azionari partono quando l'utente fornisce le chiavi del conto paper di Alpaca. +- Cambiare una regola di `crypto_trend` per farla passare richiede una nuova versione della strategia e una nuova prova, che il DSR conterà insieme a quelle già fatte. -- 2.54.1 From 9ac159a7db81066f388eff221972bce2e700bbaa Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 16:48:41 +0100 Subject: [PATCH 6/8] Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46) An independent review found these, now fixed and tested: - Risk limits could be raised through PUT /api/settings without the phrase and the password. The API now refuses risk keys. - The reference equity counted results twice after reduced to real and after a demotion. Each ledger now keeps a baseline, and carried results stay in the ledger's currency until the reference is computed. - An instrument could be bought by a second strategy in the same account (SPEC 8.6), and purchases under way did not hold their cash, so several purchases sent together could exceed it. Both are refused or shrunk now. - After an automatic trip of the switch there was no way to restart from the interface. Rischio now shows the trip of both worlds and the restart. - The fresh password of SPEC 12.4 could be tried without limit. Five wrong attempts in 15 minutes now lock it. - Observation to simulation skipped the 90 days of live signals. - A new build changed the qualification of a strategy with real money, "Ferma tutto" counted as a critical incident, raising risk ignored demotion conditions in progress, and weekends counted as stock sessions. - The 12.4 confirmation now summarises capital, first purchases and limits, and live strategies show the gap with their simulated twin. The backtest converts each bar with the rate fixed before it opens, the day before, and the report now counts how often correctives and risk changed a decision. crypto_trend is still not passed: the broad universe now falls 32.8%. The outcome file also keeps the qualified parameters. Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 2 +- docs/STATE.md | 3 +- docs/adr/0011-scelte-fase-5.md | 25 +- docs/backtests/crypto_trend.md | 208 +++--- docs/backtests/crypto_trend.outcome.json | 673 +++++++++--------- docs/backtests/equity_meanrev.md | 2 +- docs/backtests/equity_momentum.md | 2 +- src/Anubis.Server/Assets/app.css | 1 + .../Components/Pages/Impostazioni.razor | 3 +- .../Components/Pages/LaboratorioProva.razor | 2 +- .../Components/Pages/Rischio.razor | 27 +- .../Components/Pages/Strategie.razor | 16 +- src/Anubis.Server/Endpoints.cs | 12 + src/Anubis.Server/Forms.cs | 22 +- src/Anubis.Server/LabText.cs | 2 + src/Anubis.Server/RiskView.cs | 34 +- src/Anubis.Server/StrategiesView.cs | 52 +- src/Anubis/Access/AccessStore.cs | 20 +- src/Anubis/Backtest/Engine.cs | 14 + src/Anubis/Backtest/Protocol.cs | 14 +- src/Anubis/Backtest/ProtocolReport.cs | 20 +- src/Anubis/Trading/RiskEngine.cs | 73 +- src/Anubis/Trading/Stages.cs | 135 +++- tests/Anubis.Tests/ProtocolTests.cs | 24 +- tests/Anubis.Tests/RiskEngineTests.cs | 114 ++- tests/Anubis.Tests/StoresTests.cs | 21 + tests/Anubis.Tests/StrategyScreensTests.cs | 26 + 27 files changed, 1015 insertions(+), 532 deletions(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index c41d6f6..f43a54c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -171,7 +171,7 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare. - [x] Ogni regola di 9.1 e 9.2 ha il suo test (`RiskTests` e `RiskEngineTests`: perdita del giorno, della settimana, calo dal massimo a 10 e 15%, capitale investito, posizione singola, quota crypto, rischio della singola operazione, controlli tecnici, niente vendite allo scoperto, protezione per le operazioni in giornata, avviso all'80%, ordini al minuto, file STOP; più `NoRuleEverEnlargesWhatTheStrategyAsked` e `AfterALossNoPurchaseIsLarger` come test di proprietà) - [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`) - [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`) -- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 29,1% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome` +- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 32,8% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome` - [x] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione (`AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome`; i due rapporti azionari dicono cosa manca) - [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`) - [x] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup (`TheDemoShowsTradesStrategiesAndRiskAsInTheMockups` e confronto a 1440 e 375 px con i mockup 03, 04 e 07) diff --git a/docs/STATE.md b/docs/STATE.md index 2aced80..97e78b9 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -75,7 +75,7 @@ Aggiornato: 2026-11-11 - Correttivi comuni (regime crypto, calendario economico), dimensionamento sulla quota del bot e motore del rischio completo: limiti di perdita per mondo, calo dal massimo con dimezzamento e interruttore, limiti di dimensione, controlli tecnici, niente vendite allo scoperto né leva. Toglie o riduce, mai aggiunge. Gira anche dentro i backtest. - Ogni passo di una decisione resta scritto con i suoi codici motivo (tabella `decisions`). - Stadi verso i soldi veri: osservazione, simulazione, reale ridotto, reale. Senza la procedura di 12.4 nessun ordine raggiunge un conto reale; una strategia retrocessa gestisce le uscite delle posizioni reali fino a zero; il gemello simulato resta fuori dai totali. In simulazione entra solo una strategia che ha superato il backtest. - - Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 29,1% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio. + - Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 32,8% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio. - Schermate Operazioni (con la scheda "perché" e l'esportazione CSV), Strategie e Rischio come i mockup 03, 04 e 07; in Impostazioni limiti, protezione per le operazioni in giornata e scenari. Fermare, chiudere e ripartire passano dal motore del rischio; alzare un limite mentre una strategia usa soldi veri chiede frase e password. ## In corso @@ -97,6 +97,7 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). - Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta (ADR 0010, punto 13); i backtest delle strategie di base li convertono in euro con il cambio BCE del giorno (ADR 0011, punto 10). - `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti. +- Il motore dal vivo (Fase 6) deve far girare una strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati. - Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati). - Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove. - I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti. diff --git a/docs/adr/0011-scelte-fase-5.md b/docs/adr/0011-scelte-fase-5.md index dc02d38..787f4c7 100644 --- a/docs/adr/0011-scelte-fase-5.md +++ b/docs/adr/0011-scelte-fase-5.md @@ -33,13 +33,25 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris **5. Ogni passo di una decisione resta scritto.** La nuova tabella `decisions` tiene una riga per passo (strategia, correttivi, dimensionamento, rischio, ordine) con codici motivo e numeri usati. La scheda "perché" di Operazioni collega decisioni ed esecuzioni con l'id d'ordine deterministico (`ClientOrderIds.Key(decision_id)`) e scrive le frasi da modelli italiani fissi. **6. Gli stadi sono l'unica strada verso i soldi veri.** -- Quattro stadi: osservazione, simulazione, reale ridotto, reale. +- Quattro stadi: osservazione, simulazione, reale ridotto, reale. Da osservazione a simulazione servono il backtest superato e almeno 90 giorni di segnali raccolti dal vivo (12.3); solo il primo avvio porta in simulazione una strategia di base che ha superato il backtest, come dice la specifica. - Un ordine su un conto reale richiede il consenso della configurazione d'avvio, tutti i requisiti di 12.3 soddisfatti, la frase scritta a mano e password (più il secondo fattore, se attivo) inseriti da poco. I gestori degli ordini sui conti reali, in caso di dubbio, rifiutano e richiedono la conferma prima di ogni ordine. -- Da osservazione a simulazione si passa con un pulsante, ma solo se il backtest della strategia è superato (`Qualification.Passed`). Una strategia che non lo ha superato resta in osservazione e la schermata dice perché. +- Da osservazione a simulazione si passa con un pulsante, ma il libro degli stadi ricontrolla i due requisiti: una strategia che non li ha resta in osservazione e la schermata dice perché. +- La password inserita per la procedura conta i tentativi come l'accesso: dopo cinque errori in 15 minuti è rifiutata anche quella giusta, finché la finestra non passa. +- Prima della conferma la schermata riassume cosa cambia: capitale usato, acquisti del primo ciclo (stimati da ciò che la simulazione tiene in quel momento), limiti e la loro base. Per una strategia con soldi veri mostra la differenza di risultato con il gemello simulato, in percentuale del capitale usato. +- Con soldi veri in gioco l'esito del backtest con cui la strategia si è qualificata non cambia, nemmeno con un aggiornamento del programma: lo riceve quando torna in simulazione. L'esito tiene anche i parametri della variante qualificata, che sono quelli che girano dal vivo (Fase 6). - Una strategia retrocessa o revocata tiene le posizioni reali in sola uscita, con i loro stop, fino a zero. - Il gemello simulato di una strategia con soldi veri resta fuori dai totali e dal patrimonio di riferimento. +- Il patrimonio di riferimento è il capitale affidato più i risultati, contati una volta sola. A ogni cambio di stadio il registro che la strategia lascia porta con sé ciò che ha prodotto da quando era in uso (per quattro se viene dal reale ridotto), e il registro che prende il suo posto parte da ciò che ha in quel momento. Così il passaggio da reale ridotto a reale, sullo stesso conto, e il ritorno al gemello dopo una retrocessione non contano due volte gli stessi guadagni. Gli importi restano nella valuta del registro e diventano euro al momento del calcolo. +- Nel calcolo della retrocessione per il percorso atteso le azioni non contano i fine settimana, in cui non ci sono sedute. -**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Ogni cambio finisce nel registro delle impostazioni. +**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Non passa comunque finché una strategia con soldi veri ha una condizione di retrocessione in corso (12.4). Ogni cambio finisce nel registro delle impostazioni. I limiti non si cambiano dall'API generale delle impostazioni (`PUT /api/settings`): solo dal modulo di Impostazioni, che fa questi controlli. + +**7 bis. Liquidità, strumenti e fermate.** +- Un acquisto in corso tiene impegnata la sua liquidità finché non è eseguito, e ogni acquisto conta al prezzo più alto a cui il suo limite può arrivare (la distanza ammessa dall'ultimo prezzo): più acquisti inviati insieme non superano la liquidità della strategia. +- In uno stesso conto uno strumento appartiene a una sola strategia alla volta (8.6): se un'altra lo tiene, o lo sta comprando, l'ingresso salta con il suo motivo. +- "Ferma tutto", il file `STOP` e l'anomalia di ordini al minuto sono eventi di gravità alta, non critici: sono il bot che fa il suo lavoro, non un controllo perso, e non bloccano per 30 giorni il passaggio di stadio (12.3). +- Quando l'interruttore scatta da solo in un mondo, il bot resta "attivo" per l'altro: la pagina Rischio mostra lo scatto di entrambi i mondi e il pulsante "Riparti" anche in questo caso. La ripartenza toglie lo scatto e lascia una pausa com'era. +- Nella pagina Rischio peso di una posizione, quota crypto e rischio di un'operazione si misurano sul patrimonio di riferimento, come nel motore del rischio. **8. Gli scenari sono una somma semplice.** "Se succedesse domani" applica la variazione al valore delle posizioni del momento. "Con gli stop" prende per ogni posizione la perdita più piccola tra lo scenario e la distanza dal suo stop, arrotondata a 5 € e scritta come "circa", perché uno stop non garantisce il prezzo. Lo scenario del dollaro tocca il conto in dollari e gli stop non lo riducono. @@ -49,6 +61,7 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris - Le barre giornaliere USDT si dividono per il cambio BCE EUR/USD dello stesso giorno, o dell'ultimo precedente fino a 7 giorni prima; altrimenti la barra si scarta. Si salvano come sede `binance_eur`. - Una serie si ferma al primo buco più lungo di 7 giorni (`MaxGapDays`): ciò che segue è un'altra moneta. Il LUNA rilanciato nel 2022 non si confonde con quello crollato, che si taglia al 13/05/2022. - L'elenco degli archivi comprende le monete tolte dal listino (49 coppie, con LUNA, FTT, BCC, VEN, XMR…): l'universo passato non è scelto tra i sopravvissuti. +- Ogni barra usa l'ultimo cambio fissato prima della sua apertura, cioè quello del giorno prima: il cambio del giorno d è fissato alle 16:00, dopo l'apertura della barra di d alle 00:00 UTC, e il backtest esegue all'apertura. - `anubis backtest base --offline` scarica i cambi BCE solo se il file manca. **11. Il protocollo dei backtest di base.** @@ -59,10 +72,14 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris - Il costo di andata e ritorno è 2 × (commissione taker + scostamento); lo scostamento è pesato sul controvalore scambiato. - Il percorso atteso a un anno viene da un bootstrap a blocchi stazionario: 2.000 percorsi, blocchi medi di 20 giorni, seme 20260101, 365 giorni. - Il rapporto mostra lo Sharpe annuo (× √sedute dell'anno) e DSR e PBO con tre decimali, perché "0,90 serve ≥ 0,90" con due decimali confondeva. +- Il rapporto conta quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato la richiesta della strategia, separate dalle note del motore (ordini sotto il minimo, residui). +- "Comprare e tenere" dell'universo largo compra fin dall'inizio tutte le 47 monete che sono state tra le prime dieci in qualche momento: è un paniere scelto col senno di poi, quindi favorisce il confronto e rende il giudizio sulla strategia più severo, non più indulgente. **12. L'esito dei backtest viaggia con il codice.** I file `docs/backtests/*.outcome.json` sono inclusi nell'applicazione e letti a ogni avvio. Gli esiti azionari sono "non superato, in attesa delle chiavi Alpaca": senza storico azionario le due strategie azionarie restano in osservazione. -**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 29,1% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 11,2% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile. +**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 32,8% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 10,4% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile. + +Una prima versione del calcolo usava il cambio dello stesso giorno della barra e dava un calo del 29,1%. Spostare il cambio di un giorno (punto 10) ha mosso il calo di quasi quattro punti: anche questo dice che il risultato è fragile. **14. La demo è coerente con i mockup.** La modalità dimostrativa semina le decisioni dietro le sue operazioni, 58 giorni di simulazione, una qualifica d'esempio e gli indici delle curve, così Operazioni, Strategie e Rischio mostrano le cifre dei mockup 03, 04 e 07. Nella demo nessuno stadio cambia e i moduli del rischio non ci sono. diff --git a/docs/backtests/crypto_trend.md b/docs/backtests/crypto_trend.md index 94d925e..bf04409 100644 --- a/docs/backtests/crypto_trend.md +++ b/docs/backtests/crypto_trend.md @@ -1,6 +1,6 @@ # Backtest di `crypto_trend` (Trend crypto) -**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 29,1%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,839, serve ≤ 0,40. Resta in osservazione. +**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 32,8%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,835, serve ≤ 0,40. Resta in osservazione. Calcolato il 2026-11-11 con la versione 1 della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo. @@ -18,94 +18,110 @@ Per rifarlo: `anubis backtest base --to 2026-10-31`. Il file dell'esito, letto d | Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito | |---|---|---:|---:|---:|---:|---:|---| -| Universo ampio | `coin_vol=10;max_stop=20` | 11,2% | −29,1% | 8.053,52 € | 0,960 | 0,143 | non superata | -| BTC, ETH e SOL | `coin_vol=20;max_stop=15` | 13,8% | −17,3% | 12.845,05 € | 0,971 | 0,839 | non superata | +| Universo ampio | `coin_vol=10;max_stop=20` | 10,4% | −32,8% | 7.264,22 € | 0,924 | 0,085 | non superata | +| BTC, ETH e SOL | `coin_vol=20;max_stop=10` | 12,2% | −15,0% | 10.274,96 € | 0,961 | 0,835 | non superata | ## Cosa conserva il bot -- Calo massimo del backtest: −29,1%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3). -- Scostamento di prezzo previsto: 11,91 punti base; costo stimato di andata e ritorno 0,64%. -- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −4,9% dopo 30 giorni, −7,6% dopo 90, −13,2% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro. +- Calo massimo del backtest: −32,8%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3). +- Scostamento di prezzo previsto: 11,94 punti base; costo stimato di andata e ritorno 0,64%. +- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −5,1% dopo 30 giorni, −8,0% dopo 90, −14,1% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro. ## Universo ampio Le 10 monete con più scambi, scelte ogni mese tra 47 coppie (anche quelle poi chiuse). -Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `737ca3a07b9c`, dei dati `8486b858321b`. +Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `b5f566d59bfa`, dei dati `840015607150`. | | Strategia | Comprare e tenere | |---|---:|---:| -| Risultato netto | 12.984,56 € | 82.750,41 € | -| Rendimento totale | 129,8% | 827,5% | -| Rendimento annuo | 11,2% | 32,9% | -| Volatilità annua | 14,0% | 74,2% | -| Calo massimo | −29,1% (11/2021 → 10/2023) | −85,8% | -| Sharpe annuo | 0,83 | 0,76 | -| Operazioni chiuse | 1826 | 0 | -| Operazioni in guadagno | 14,1% | — | -| Rapporto guadagni/perdite | 1,51 | — | -| Commissioni pagate | 2.975,10 € | 20,00 € | +| Risultato netto | 11.628,28 € | 82.820,55 € | +| Rendimento totale | 116,3% | 828,2% | +| Rendimento annuo | 10,4% | 32,9% | +| Volatilità annua | 14,2% | 74,7% | +| Calo massimo | −32,8% (11/2021 → 10/2023) | −85,8% | +| Sharpe annuo | 0,77 | 0,76 | +| Operazioni chiuse | 1842 | 0 | +| Operazioni in guadagno | 13,1% | — | +| Rapporto guadagni/perdite | 1,47 | — | +| Commissioni pagate | 2.967,95 € | 20,00 € | | Tempo investito | 16,9% | 92,0% | **Per anno** | Anno | Strategia | Comprare e tenere | |---|---:|---:| -| 2019 | 17,8% | 4,4% | -| 2020 | 34,9% | 103,9% | -| 2021 | 24,9% | 1.603,5% | -| 2022 | −10,5% | −79,9% | -| 2023 | 14,6% | 56,4% | -| 2024 | 26,8% | 34,5% | -| 2025 | −8,8% | −33,1% | -| 2026 | −2,4% | −9,4% | +| 2019 | 17,0% | 4,8% | +| 2020 | 36,2% | 103,2% | +| 2021 | 19,8% | 1.603,8% | +| 2022 | −11,2% | −79,9% | +| 2023 | 12,2% | 56,4% | +| 2024 | 26,2% | 33,8% | +| 2025 | −7,4% | −32,9% | +| 2026 | −2,6% | −9,4% | **Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme) | Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni | |---|---:|---:|---:|---:|---:| -| ×1 | 12.984,56 € | 129,8% | 0,83 | −29,1% | 2.975,10 € | -| ×2 | 8.053,52 € | 80,5% | 0,61 | −33,9% | 5.005,99 € | -| ×3 | 4.349,38 € | 43,5% | 0,40 | −36,0% | 6.495,29 € | +| ×1 | 11.628,28 € | 116,3% | 0,77 | −32,8% | 2.967,95 € | +| ×2 | 7.264,22 € | 72,6% | 0,56 | −35,8% | 5.039,47 € | +| ×3 | 3.522,91 € | 35,2% | 0,34 | −38,9% | 6.471,34 € | **Convalide** -- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 67,6%, Sharpe annuo 0,65. -- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,83, peggiore 0,83, percorsi positivi 100,0%. -- Deflated Sharpe Ratio 0,96, contando 9 varianti provate in tutto. -- Probabilità di sovra-adattamento (PBO) 0,14, su 12870 combinazioni di 9 varianti. +- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 58,4%, Sharpe annuo 0,58. +- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,77, peggiore 0,77, percorsi positivi 100,0%. +- Deflated Sharpe Ratio 0,92, contando 9 varianti provate in tutto. +- Probabilità di sovra-adattamento (PBO) 0,09, su 12870 combinazioni di 9 varianti. - Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate. **Soglie** | Controllo | Valore | Soglia | Esito | |---|---:|---:|---| -| Risultato netto con costi doppi | 8.053,52 € | > 0,00 € | superato | -| Deflated Sharpe Ratio | 0,960 | ≥ 0,9 | superato | -| Probabilità di sovra-adattamento (PBO) | 0,143 | ≤ 0,4 | superato | -| Calo massimo | 29,1% | ≤ 25% | **non superato** | +| Risultato netto con costi doppi | 7.264,22 € | > 0,00 € | superato | +| Deflated Sharpe Ratio | 0,924 | ≥ 0,9 | superato | +| Probabilità di sovra-adattamento (PBO) | 0,085 | ≤ 0,4 | superato | +| Calo massimo | 32,8% | ≤ 25% | **non superato** | | Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato | **Varianti della griglia** | Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni | |---|---:|---:|---:|---:|---:| -| `coin_vol=10;max_stop=10` | 0,58 | 0,58 | 6.383,12 € | −22,9% | 2243 | -| `coin_vol=10;max_stop=15` | 0,83 | 0,71 | 12.327,24 € | −24,6% | 1994 | -| `coin_vol=10;max_stop=20` (scelta) | 0,83 | 0,78 | 12.984,56 € | −29,1% | 1826 | -| `coin_vol=15;max_stop=10` | 0,53 | 0,53 | 6.035,84 € | −25,0% | 2257 | -| `coin_vol=15;max_stop=15` | 0,74 | 0,67 | 10.656,85 € | −29,4% | 2002 | -| `coin_vol=15;max_stop=20` | 0,74 | 0,74 | 11.167,92 € | −30,8% | 1837 | -| `coin_vol=20;max_stop=10` | 0,44 | 0,44 | 4.826,58 € | −25,0% | 2258 | -| `coin_vol=20;max_stop=15` | 0,65 | 0,63 | 8.943,30 € | −30,5% | 2008 | -| `coin_vol=20;max_stop=20` | 0,66 | 0,66 | 9.921,78 € | −31,1% | 1838 | +| `coin_vol=10;max_stop=10` | 0,54 | 0,54 | 5.784,07 € | −24,0% | 2269 | +| `coin_vol=10;max_stop=15` | 0,86 | 0,66 | 13.191,01 € | −27,8% | 2008 | +| `coin_vol=10;max_stop=20` (scelta) | 0,77 | 0,75 | 11.628,28 € | −32,8% | 1842 | +| `coin_vol=15;max_stop=10` | 0,39 | 0,39 | 3.932,83 € | −26,3% | 2281 | +| `coin_vol=15;max_stop=15` | 0,71 | 0,61 | 10.147,48 € | −31,9% | 2015 | +| `coin_vol=15;max_stop=20` | 0,68 | 0,68 | 9.971,55 € | −33,4% | 1853 | +| `coin_vol=20;max_stop=10` | 0,35 | 0,35 | 3.437,00 € | −26,8% | 2284 | +| `coin_vol=20;max_stop=15` | 0,59 | 0,55 | 7.855,25 € | −33,4% | 2021 | +| `coin_vol=20;max_stop=20` | 0,57 | 0,57 | 7.673,22 € | −34,6% | 1856 | **Interventi di correttivi e rischio sulla variante scelta** +Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva. + | Motivo | Volte | |---|---:| -| `residue_written_off` | 1823 | -| `below_min_notional` | 387 | +| `crypto_regime_below_average` | 3565 | +| `risk_reduction` | 1590 | +| `crypto_regime_high_volatility` | 151 | +| `trade_risk_limit` | 43 | +| `switch_tripped` | 34 | +| `daily_loss_block` | 14 | +| `stop_above_price` | 13 | + +**Note del motore di prova** + +Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità. + +| Motivo | Volte | +|---|---:| +| `residue_written_off` | 1837 | +| `below_min_notional` | 449 | **Strumenti** @@ -163,81 +179,95 @@ Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.00 Solo le tre coppie in euro con la liquidità migliore. -Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=15` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `3ba7de18ca85`, dei dati `f8e752dabf31`. +Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=10` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `1ce210e9cbcb`, dei dati `3b890d6f2ef3`. | | Strategia | Comprare e tenere | |---|---:|---:| -| Risultato netto | 17.515,31 € | 215.787,99 € | -| Rendimento totale | 175,2% | 2.157,9% | -| Rendimento annuo | 13,8% | 48,9% | -| Volatilità annua | 12,8% | 71,7% | -| Calo massimo | −17,3% (11/2021 → 10/2023) | −86,7% | -| Sharpe annuo | 1,07 | 0,92 | -| Operazioni chiuse | 452 | 0 | -| Operazioni in guadagno | 15,7% | — | -| Rapporto guadagni/perdite | 2,29 | — | -| Commissioni pagate | 2.282,94 € | 20,00 € | -| Tempo investito | 14,9% | 95,2% | +| Risultato netto | 14.642,97 € | 216.831,80 € | +| Rendimento totale | 146,4% | 2.168,3% | +| Rendimento annuo | 12,2% | 49,0% | +| Volatilità annua | 11,8% | 72,2% | +| Calo massimo | −15,0% (11/2021 → 10/2023) | −86,7% | +| Sharpe annuo | 1,03 | 0,92 | +| Operazioni chiuse | 539 | 0 | +| Operazioni in guadagno | 16,7% | — | +| Rapporto guadagni/perdite | 1,76 | — | +| Commissioni pagate | 2.866,85 € | 20,00 € | +| Tempo investito | 12,9% | 95,2% | **Per anno** | Anno | Strategia | Comprare e tenere | |---|---:|---:| -| 2019 | 15,0% | 28,6% | -| 2020 | 30,5% | 221,5% | -| 2021 | 20,9% | 643,3% | -| 2022 | −7,4% | −81,4% | -| 2023 | 29,4% | 256,5% | -| 2024 | 22,8% | 93,3% | -| 2025 | −0,3% | −31,6% | -| 2026 | 3,5% | −16,1% | +| 2019 | 20,8% | 29,3% | +| 2020 | 29,0% | 219,6% | +| 2021 | 14,1% | 647,5% | +| 2022 | −6,7% | −81,5% | +| 2023 | 27,3% | 257,8% | +| 2024 | 20,9% | 92,3% | +| 2025 | −5,5% | −31,3% | +| 2026 | 2,3% | −16,1% | **Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme) | Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni | |---|---:|---:|---:|---:|---:| -| ×1 | 17.515,31 € | 175,2% | 1,07 | −17,3% | 2.282,94 € | -| ×2 | 12.845,05 € | 128,5% | 0,89 | −20,9% | 4.070,32 € | -| ×3 | 9.959,70 € | 99,6% | 0,75 | −22,7% | 5.605,48 € | +| ×1 | 14.642,97 € | 146,4% | 1,03 | −15,0% | 2.866,85 € | +| ×2 | 10.274,96 € | 102,7% | 0,82 | −18,9% | 5.161,91 € | +| ×3 | 6.273,26 € | 62,7% | 0,59 | −21,3% | 6.782,83 € | **Convalide** -- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 90,3%, Sharpe annuo 0,91. -- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 1,00, peggiore 0,94, percorsi positivi 100,0%. -- Deflated Sharpe Ratio 0,97, contando 18 varianti provate in tutto. -- Probabilità di sovra-adattamento (PBO) 0,84, su 12870 combinazioni di 9 varianti. +- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 82,4%, Sharpe annuo 0,85. +- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,90, peggiore 0,82, percorsi positivi 100,0%. +- Deflated Sharpe Ratio 0,96, contando 18 varianti provate in tutto. +- Probabilità di sovra-adattamento (PBO) 0,83, su 12870 combinazioni di 9 varianti. - Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate. **Soglie** | Controllo | Valore | Soglia | Esito | |---|---:|---:|---| -| Risultato netto con costi doppi | 12.845,05 € | > 0,00 € | superato | -| Deflated Sharpe Ratio | 0,971 | ≥ 0,9 | superato | -| Probabilità di sovra-adattamento (PBO) | 0,839 | ≤ 0,4 | **non superato** | -| Calo massimo | 17,3% | ≤ 25% | superato | +| Risultato netto con costi doppi | 10.274,96 € | > 0,00 € | superato | +| Deflated Sharpe Ratio | 0,961 | ≥ 0,9 | superato | +| Probabilità di sovra-adattamento (PBO) | 0,835 | ≤ 0,4 | **non superato** | +| Calo massimo | 15,0% | ≤ 25% | superato | | Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato | **Varianti della griglia** | Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni | |---|---:|---:|---:|---:|---:| -| `coin_vol=10;max_stop=10` | 1,01 | 1,00 | 9.436,53 € | −10,9% | 532 | -| `coin_vol=10;max_stop=15` | 0,94 | 0,94 | 9.790,38 € | −13,0% | 452 | -| `coin_vol=10;max_stop=20` | 1,05 | 1,01 | 12.078,19 € | −13,0% | 388 | -| `coin_vol=15;max_stop=10` | 1,04 | 1,03 | 13.029,82 € | −13,3% | 532 | -| `coin_vol=15;max_stop=15` | 1,01 | 1,01 | 14.386,02 € | −15,8% | 452 | -| `coin_vol=15;max_stop=20` | 1,05 | 1,03 | 15.995,77 € | −15,0% | 388 | -| `coin_vol=20;max_stop=10` | 1,09 | 1,05 | 15.920,52 € | −13,9% | 532 | -| `coin_vol=20;max_stop=15` (scelta) | 1,07 | 1,06 | 17.515,31 € | −17,3% | 452 | -| `coin_vol=20;max_stop=20` | 1,08 | 1,05 | 18.543,32 € | −15,5% | 388 | +| `coin_vol=10;max_stop=10` | 0,98 | 0,95 | 8.962,80 € | −11,2% | 539 | +| `coin_vol=10;max_stop=15` | 0,91 | 0,91 | 9.287,93 € | −13,3% | 457 | +| `coin_vol=10;max_stop=20` | 0,97 | 0,95 | 10.893,96 € | −13,9% | 393 | +| `coin_vol=15;max_stop=10` | 1,00 | 0,97 | 12.333,91 € | −13,5% | 539 | +| `coin_vol=15;max_stop=15` | 0,91 | 0,91 | 12.048,69 € | −16,1% | 457 | +| `coin_vol=15;max_stop=20` | 0,99 | 0,96 | 14.421,53 € | −16,5% | 393 | +| `coin_vol=20;max_stop=10` (scelta) | 1,03 | 0,98 | 14.642,97 € | −15,0% | 539 | +| `coin_vol=20;max_stop=15` | 0,97 | 0,97 | 14.521,59 € | −17,1% | 457 | +| `coin_vol=20;max_stop=20` | 1,02 | 0,97 | 16.651,30 € | −16,6% | 393 | **Interventi di correttivi e rischio sulla variante scelta** +Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva. + | Motivo | Volte | |---|---:| -| `residue_written_off` | 450 | -| `below_min_notional` | 89 | +| `crypto_regime_below_average` | 1104 | +| `crypto_regime_high_volatility` | 52 | +| `trade_risk_limit` | 41 | +| `stop_above_price` | 3 | +| `daily_loss_block` | 1 | + +**Note del motore di prova** + +Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità. + +| Motivo | Volte | +|---|---:| +| `residue_written_off` | 539 | +| `below_min_notional` | 105 | **Strumenti** diff --git a/docs/backtests/crypto_trend.outcome.json b/docs/backtests/crypto_trend.outcome.json index 9325ceb..cdc0439 100644 --- a/docs/backtests/crypto_trend.outcome.json +++ b/docs/backtests/crypto_trend.outcome.json @@ -1,376 +1,377 @@ { "passed": false, - "verdict": "Protocollo non superato. Universo ampio: calo massimo 29,1%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,839, serve \u2264 0,40. Resta in osservazione.", + "verdict": "Protocollo non superato. Universo ampio: calo massimo 32,8%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,835, serve \u2264 0,40. Resta in osservazione.", "report": "docs/backtests/crypto_trend.md", - "plan_hash": "737ca3a07b9c67574013581d6ebc395e60b8edfa0681707804e67601112f1c12", - "max_drawdown": 0.2910, - "expected_slippage_bp": 11.91, - "round_trip_cost": 0.006382, + "plan_hash": "b5f566d59bfae84f7c0821705d243dc0707803db36f74c1eecd130fb14fed8ed", + "parameters": "coin_vol=10;max_stop=20", + "max_drawdown": 0.3278, + "expected_slippage_bp": 11.94, + "round_trip_cost": 0.006388, "expected_path_p5": [ - -0.0099, - -0.0133, - -0.0175, - -0.0205, - -0.0231, - -0.0234, - -0.0242, - -0.026, - -0.0281, - -0.0291, - -0.031, - -0.031, - -0.0334, - -0.034, - -0.0352, - -0.037, - -0.0382, + -0.01, + -0.0144, + -0.0179, + -0.0199, + -0.023, + -0.0252, + -0.0256, + -0.0269, + -0.0284, + -0.0294, + -0.0313, + -0.0316, + -0.0327, + -0.0346, + -0.0355, + -0.0373, + -0.0381, -0.0396, + -0.0411, -0.0412, - -0.0405, - -0.0401, - -0.0415, - -0.0421, - -0.0437, - -0.044, - -0.0446, - -0.0458, - -0.0467, - -0.0479, - -0.0489, - -0.0503, - -0.0517, - -0.0528, - -0.0525, - -0.0529, - -0.0539, - -0.0552, - -0.0557, - -0.0563, - -0.0568, - -0.0583, + -0.0413, + -0.0426, + -0.0429, + -0.0445, + -0.0457, + -0.0457, + -0.0468, + -0.0481, + -0.0499, + -0.0512, + -0.0507, + -0.0519, + -0.0538, + -0.0548, + -0.0558, + -0.0566, + -0.0582, -0.0585, - -0.0595, - -0.0591, -0.0583, - -0.0587, - -0.0593, - -0.0595, - -0.0596, - -0.0613, - -0.0609, - -0.0618, - -0.0629, - -0.0638, - -0.0641, + -0.0594, + -0.0599, + -0.06, + -0.06, + -0.0616, + -0.0619, + -0.0619, + -0.061, + -0.0626, -0.0634, + -0.0655, -0.0646, - -0.0649, - -0.066, - -0.0659, - -0.067, - -0.0676, - -0.0693, - -0.0692, - -0.0697, - -0.0686, - -0.0687, - -0.0693, - -0.0693, - -0.0697, - -0.0696, - -0.069, - -0.069, - -0.0716, + -0.0651, + -0.0674, + -0.0681, + -0.0683, + -0.0678, + -0.0684, + -0.0691, + -0.0705, + -0.0724, + -0.0733, -0.0725, - -0.0727, - -0.073, - -0.073, - -0.0734, - -0.0735, - -0.0738, - -0.074, - -0.0747, - -0.074, - -0.0757, - -0.0741, - -0.0742, + -0.0736, + -0.0737, -0.0746, + -0.0729, + -0.074, + -0.0737, + -0.0744, + -0.0739, + -0.0751, + -0.0742, + -0.0749, + -0.076, + -0.0754, + -0.0755, -0.0757, - -0.0756, - -0.0761, - -0.0757, - -0.0761, - -0.0771, + -0.0774, + -0.0781, + -0.0782, + -0.0776, + -0.0791, + -0.0786, -0.0785, - -0.0807, - -0.0819, - -0.0827, - -0.0823, - -0.083, - -0.0823, - -0.0831, - -0.0829, - -0.0853, - -0.0849, - -0.0836, + -0.0781, + -0.0785, + -0.0789, + -0.0788, + -0.0806, + -0.0802, + -0.0802, + -0.0802, + -0.0813, + -0.0826, + -0.0842, -0.0841, - -0.0835, - -0.084, - -0.0857, - -0.0856, - -0.0852, - -0.0861, - -0.0861, - -0.0861, - -0.0848, - -0.0861, - -0.0866, + -0.087, + -0.0859, + -0.0855, + -0.0868, + -0.0868, + -0.0875, + -0.0872, + -0.0872, -0.0876, + -0.0868, + -0.0866, + -0.0865, + -0.0867, + -0.0875, + -0.0877, + -0.0884, + -0.0882, -0.0887, - -0.0897, - -0.0906, - -0.0902, - -0.0916, - -0.0917, - -0.0922, - -0.0937, - -0.0922, - -0.0931, - -0.0926, - -0.0922, - -0.0914, - -0.0914, - -0.0901, - -0.0916, - -0.0917, - -0.0937, - -0.0937, - -0.0955, - -0.0971, + -0.0882, + -0.0888, + -0.0895, + -0.0912, + -0.0919, + -0.0915, + -0.0929, + -0.0933, + -0.0938, + -0.0941, + -0.0943, + -0.0957, + -0.096, + -0.0957, + -0.0958, + -0.0957, + -0.0973, + -0.0965, + -0.0957, + -0.0941, + -0.0956, -0.0958, -0.0969, - -0.0972, -0.0992, - -0.1007, - -0.101, - -0.1004, - -0.1008, + -0.0988, + -0.0996, -0.1003, - -0.1005, - -0.1025, - -0.1024, - -0.1034, - -0.1027, - -0.1034, - -0.1042, - -0.1034, - -0.105, - -0.1037, - -0.1054, - -0.1066, - -0.1053, - -0.1055, + -0.0996, + -0.101, + -0.1006, + -0.1041, + -0.1051, + -0.1045, + -0.1032, + -0.1035, + -0.1038, + -0.1048, + -0.1045, + -0.1067, + -0.1051, + -0.1065, + -0.1061, -0.1062, - -0.1057, - -0.1057, - -0.1072, - -0.1071, - -0.108, - -0.108, - -0.1087, - -0.1102, - -0.1118, - -0.1117, - -0.111, - -0.1112, - -0.111, - -0.1132, + -0.1082, + -0.1073, + -0.1078, + -0.1088, + -0.109, + -0.1097, + -0.1116, + -0.1089, + -0.1105, + -0.1103, + -0.1083, + -0.1116, -0.1108, - -0.1112, - -0.1119, - -0.1113, - -0.1127, - -0.1129, - -0.1129, - -0.1127, - -0.1143, - -0.1139, - -0.1162, - -0.1156, - -0.1159, - -0.1154, - -0.1173, - -0.116, - -0.1147, - -0.1162, - -0.1139, - -0.1135, - -0.1135, - -0.1138, + -0.1116, + -0.1132, -0.1133, - -0.1144, - -0.1136, - -0.1136, - -0.1139, + -0.1131, + -0.1132, -0.114, - -0.1151, - -0.1147, - -0.1148, - -0.1163, - -0.1161, - -0.1169, - -0.1164, - -0.1179, - -0.1179, - -0.1201, + -0.1141, + -0.1144, + -0.1159, + -0.116, + -0.1165, + -0.1157, + -0.1165, + -0.1191, + -0.1195, + -0.1198, + -0.1205, + -0.12, + -0.1216, + -0.1213, + -0.1219, + -0.1204, + -0.12, + -0.1217, + -0.1194, -0.1206, - -0.1211, - -0.122, - -0.1227, - -0.1218, - -0.1221, - -0.1222, - -0.1222, - -0.1233, - -0.123, - -0.123, - -0.1229, - -0.1231, - -0.1225, - -0.1212, + -0.1194, + -0.1184, + -0.1195, + -0.119, -0.1195, -0.1201, - -0.1202, - -0.1203, -0.121, - -0.1228, - -0.1225, - -0.1221, - -0.1222, - -0.1222, - -0.1223, - -0.1223, - -0.1223, - -0.1241, - -0.1238, - -0.126, - -0.1252, - -0.1269, - -0.1266, - -0.1265, - -0.1258, - -0.1245, - -0.1261, + -0.1206, + -0.1195, + -0.1217, + -0.1212, + -0.1204, + -0.1217, + -0.1229, + -0.124, + -0.1231, + -0.1232, + -0.1247, -0.1256, - -0.1258, - -0.1261, - -0.1263, - -0.1254, - -0.1272, - -0.1266, - -0.1266, - -0.1268, - -0.1273, - -0.1287, - -0.1275, - -0.1288, - -0.1269, - -0.1268, - -0.1273, - -0.1272, - -0.1269, - -0.1262, - -0.1259, - -0.1273, - -0.1267, - -0.1268, - -0.1259, - -0.1266, - -0.1257, - -0.1267, - -0.1272, - -0.1267, - -0.1268, - -0.126, - -0.1269, - -0.1267, - -0.1256, - -0.1256, - -0.1254, - -0.1258, - -0.1267, - -0.127, - -0.1275, - -0.1291, - -0.1262, - -0.1273, - -0.1287, - -0.129, - -0.1292, - -0.1278, - -0.125, - -0.1259, - -0.1273, - -0.1278, - -0.1278, - -0.1274, - -0.1253, - -0.1257, - -0.1237, - -0.1237, - -0.1244, - -0.1236, - -0.1242, - -0.1242, - -0.1248, - -0.1258, - -0.1266, - -0.127, - -0.126, - -0.126, - -0.1264, - -0.1263, - -0.1263, - -0.1268, - -0.1263, - -0.1249, - -0.1281, - -0.1282, - -0.1265, - -0.126, - -0.1262, - -0.1259, - -0.1281, - -0.1275, - -0.1296, - -0.1299, + -0.1277, -0.1286, - -0.1299, -0.1292, - -0.128, - -0.1304, - -0.1309, + -0.1271, + -0.1276, + -0.1301, + -0.1289, + -0.1273, + -0.1289, + -0.1285, + -0.1272, + -0.1265, + -0.1257, + -0.1273, + -0.127, + -0.1244, + -0.1244, + -0.125, + -0.126, + -0.1261, + -0.1262, + -0.1249, + -0.1243, + -0.1255, + -0.1267, + -0.1269, -0.1283, + -0.1288, + -0.1296, + -0.1314, + -0.1302, -0.1313, - -0.1319, - -0.1308, - -0.1308, - -0.1307, - -0.1297, - -0.1303, - -0.1298, - -0.1322, - -0.1323, - -0.1323, - -0.1316, -0.1311, - -0.1325, + -0.1322, + -0.1315, + -0.1337, + -0.1319, + -0.1309, + -0.1341, + -0.1328, + -0.1323, + -0.1346, + -0.1315, + -0.1328, + -0.1353, + -0.1347, + -0.1338, + -0.1365, + -0.1356, + -0.1338, + -0.1346, + -0.1343, + -0.134, + -0.1345, + -0.1331, -0.1332, + -0.1347, -0.1339, + -0.136, + -0.1347, + -0.1348, + -0.1368, + -0.136, + -0.1356, + -0.1313, + -0.1334, + -0.134, + -0.1349, + -0.1341, + -0.1342, + -0.1341, + -0.135, + -0.1353, + -0.1319, + -0.1345, + -0.137, + -0.1358, + -0.1369, + -0.1368, + -0.1372, + -0.1347, + -0.1376, + -0.1345, + -0.1346, + -0.1343, + -0.1344, + -0.132, + -0.1331, + -0.133, + -0.1345, + -0.1347, + -0.1355, + -0.1349, + -0.1346, + -0.1341, -0.1339, - -0.1336, - -0.1332, - -0.1318, - -0.132 + -0.1334, + -0.1326, + -0.1343, + -0.134, + -0.1342, + -0.1351, + -0.135, + -0.1352, + -0.1353, + -0.1382, + -0.1366, + -0.1363, + -0.1368, + -0.1354, + -0.1352, + -0.1383, + -0.1382, + -0.1356, + -0.1354, + -0.1349, + -0.1379, + -0.1382, + -0.1364, + -0.1364, + -0.1348, + -0.1345, + -0.1346, + -0.1353, + -0.1342, + -0.1372, + -0.1386, + -0.1385, + -0.1388, + -0.1402, + -0.1399, + -0.1397, + -0.1397, + -0.1401, + -0.1393, + -0.1394, + -0.1417, + -0.1402, + -0.1399, + -0.1409, + -0.1417, + -0.1404, + -0.1408, + -0.1418, + -0.1422, + -0.1423, + -0.1444, + -0.1423, + -0.1399, + -0.1405 ] } diff --git a/docs/backtests/equity_meanrev.md b/docs/backtests/equity_meanrev.md index db3757f..0e96292 100644 --- a/docs/backtests/equity_meanrev.md +++ b/docs/backtests/equity_meanrev.md @@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. -Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie. +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento. diff --git a/docs/backtests/equity_momentum.md b/docs/backtests/equity_momentum.md index 9f182a7..bb5b331 100644 --- a/docs/backtests/equity_momentum.md +++ b/docs/backtests/equity_momentum.md @@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione. -Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie. +Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento. diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index c445c49..d9ca913 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -472,6 +472,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .confirm-live summary { list-style: none; align-self: flex-start; display: inline-flex; } .confirm-live summary::-webkit-details-marker { display: none; } .confirm-live[open] summary { margin-bottom: 12px; } +.confirm-summary { margin: 0; padding-left: 20px; display: grid; gap: 4px; } .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px 16px; align-items: end; } .form-grid > p { grid-column: 1 / -1; } .form-grid label { display: flex; flex-direction: column; gap: 6px; font-weight: 550; } diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index cf5d79b..55c1aaa 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -443,7 +443,8 @@ "limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.", "ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.", "frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.", - "password-rischio" => "Password o codice non corretti. Non ho cambiato nulla.", + "password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.", + "retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.", "scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.", _ => PasswordMessages.For(Errore), diff --git a/src/Anubis.Server/Components/Pages/LaboratorioProva.razor b/src/Anubis.Server/Components/Pages/LaboratorioProva.razor index 723ebc7..4363256 100644 --- a/src/Anubis.Server/Components/Pages/LaboratorioProva.razor +++ b/src/Anubis.Server/Components/Pages/LaboratorioProva.razor @@ -254,7 +254,7 @@ @if (r.Notes.Count > 0) { -

Ordini non eseguiti come chiesto

+

Decisioni e ordini non eseguiti come chiesto

    @foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value)) { diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index 07cb977..d7ba40f 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -22,14 +22,21 @@

    Interruttore d'emergenza

    @BotText(v.BotState) - @if (v.BotState == "stopped") + @if (v.WaitsForRestart) {

    - @if (v.Risk.State.Tripped) + @if (v.Tripped.Count > 0) { - L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). + L'interruttore è scattato @string.Join(" e ", v.Tripped.Select(t => Where(t.World))): il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). + } + @if (v.BotState == "stopped") + { + Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi. + } + else + { + Lì non apro posizioni e non vendo per le strategie; gli stop di protezione restano attivi. Il resto continua a lavorare. } - Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi. @if (v.CloseAllPending) { Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura. @@ -48,7 +55,7 @@ } } - else + @if (v.BotState != "stopped") {

    Con Ferma tutto annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.

    @if (!Shell.IsDemo) @@ -70,9 +77,9 @@ else {
      - @if (v.Risk.State.Tripped) + @foreach (var t in v.Tripped) { -
    • Interruttore scattato @(v.Risk.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.
    • +
    • Interruttore scattato @Where(t.World) @(t.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.
    • } @if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow) { @@ -90,7 +97,7 @@ {
    • Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.
    • } - @if (v.BotState == "stopped" && !v.Risk.State.Tripped) + @if (v.BotState == "stopped" && v.Tripped.Count == 0) {
    • Ferma tutto acceso.
    • } @@ -284,7 +291,9 @@ _ => "Fermo", }; - private static string RestartText(RiskView v) => v.Risk.State.Tripped + private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato"; + + private static string RestartText(RiskView v) => v.Tripped.Count > 0 ? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?" : "Riparti: il bot torna a operare. Confermi?"; diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index 9b81385..e5b782a 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -75,6 +75,10 @@
      Calo peggiore
      @Format.Percent(s.WorstFall * 100m, 1)
      Operazioni chiuse
      @s.Closed@(s.Closed > 0 ? $", di cui {s.Winners} in guadagno" : "")
      Posizioni aperte
      @(s.Open.Count == 0 ? "nessuna" : string.Join(", ", s.Open.Distinct()))
      + @if (s.TwinGap is { } gap) + { +
      Rispetto al gemello simulato
      @Format.Percent(gap, 2, withSign: true) del capitale usato
      + }
      @@ -122,7 +126,14 @@ @target
      -

      Stai per affidare soldi veri a @s.Name@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Per confermare scrivi la frase qui sotto e la tua password.

      +

      Stai per affidare soldi veri a @s.Name@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Ecco cosa cambia:

      +
        + @foreach (var line in s.Summary) + { +
      • @line
      • + } +
      +

      Per confermare scrivi la frase qui sotto e la tua password.